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. using System; using System.Globalization; using System.Runtime.CompilerServices; /// <summary> /// Convert.ToString(System.Int32,System.Int32) /// </summary> public class ConvertToString18 { public static int Main() { ConvertToString18 testObj = new ConvertToString18(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Int32,System.Int32)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Verify value is 323 and radix is 2,8,10 or 16... "; string c_TEST_ID = "P001"; Int32 int32Value = -123; int radix; String actualValue; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = "11111111111111111111111110000101"; radix = 2; String resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 8; actualValue = "37777777605"; errorDesc = ""; resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 10; actualValue = "-123"; errorDesc = ""; resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 16; actualValue = "ffffff85"; errorDesc = ""; resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify value is Int32.MaxValue and radix is 2,8,10 or 16... "; string c_TEST_ID = "P002"; Int32 int32Value = Int32.MaxValue; int radix; String actualValue; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = "1111111111111111111111111111111"; radix = 2; String resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 8; actualValue = "17777777777"; errorDesc = ""; resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 10; actualValue = "2147483647"; errorDesc = ""; resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 16; actualValue = "7fffffff"; errorDesc = ""; resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string c_TEST_DESC = "PosTest3: Verify value is Int32.MinValue and radix is 2,8,10 or 16... "; string c_TEST_ID = "P003"; Int32 int32Value = Int32.MinValue; int radix; String actualValue; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = "10000000000000000000000000000000"; radix = 2; String resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 8; actualValue = "20000000000"; errorDesc = ""; resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 10; actualValue = "-2147483648"; errorDesc = ""; resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 16; actualValue = "80000000"; errorDesc = ""; resValue = Convert.ToString(int32Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int32Value, radix); TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("015", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region NegativeTesting public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: the radix is 32..."; const string c_TEST_ID = "N001"; Int32 int32Value = TestLibrary.Generator.GetInt32(-55); int radix = 32; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToString(int32Value, radix); TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected ." + DataString(int32Value, radix)); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + DataString(int32Value, radix)); retVal = false; } return retVal; } #endregion #region Help Methods private string DataString(Int32 int32Value, int radix) { string str; str = string.Format("\n[int32Value value]\n \"{0}\"", int32Value); str += string.Format("\n[radix value ]\n {0}", radix); return str; } #endregion }
// 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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Microsoft.AspNetCore.SignalR.Client { /// <summary> /// Extension methods for <see cref="HubConnectionExtensions"/>. /// </summary> public static partial class HubConnectionExtensions { /// <summary> /// Invokes a hub method on the server using the specified method name. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, Array.Empty<object>(), cancellationToken); } /// <summary> /// Invokes a hub method on the server using the specified method name and argument. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, object? arg1, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, new[] { arg1 }, cancellationToken); } /// <summary> /// Invokes a hub method on the server using the specified method name and arguments. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, object? arg1, object? arg2, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, new[] { arg1, arg2 }, cancellationToken); } /// <summary> /// Invokes a hub method on the server using the specified method name and arguments. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, object? arg1, object? arg2, object? arg3, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, new[] { arg1, arg2, arg3 }, cancellationToken); } /// <summary> /// Invokes a hub method on the server using the specified method name and arguments. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> /// <param name="arg4">The fourth argument.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, object? arg1, object? arg2, object? arg3, object? arg4, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, new[] { arg1, arg2, arg3, arg4 }, cancellationToken); } /// <summary> /// Invokes a hub method on the server using the specified method name and arguments. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> /// <param name="arg4">The fourth argument.</param> /// <param name="arg5">The fifth argument.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, object? arg1, object? arg2, object? arg3, object? arg4, object? arg5, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, new[] { arg1, arg2, arg3, arg4, arg5 }, cancellationToken); } /// <summary> /// Invokes a hub method on the server using the specified method name and arguments. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> /// <param name="arg4">The fourth argument.</param> /// <param name="arg5">The fifth argument.</param> /// <param name="arg6">The sixth argument.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, object? arg1, object? arg2, object? arg3, object? arg4, object? arg5, object? arg6, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, new[] { arg1, arg2, arg3, arg4, arg5, arg6 }, cancellationToken); } /// <summary> /// Invokes a hub method on the server using the specified method name and arguments. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> /// <param name="arg4">The fourth argument.</param> /// <param name="arg5">The fifth argument.</param> /// <param name="arg6">The sixth argument.</param> /// <param name="arg7">The seventh argument.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, object? arg1, object? arg2, object? arg3, object? arg4, object? arg5, object? arg6, object? arg7, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, new[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7 }, cancellationToken); } /// <summary> /// Invokes a hub method on the server using the specified method name and arguments. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> /// <param name="arg4">The fourth argument.</param> /// <param name="arg5">The fifth argument.</param> /// <param name="arg6">The sixth argument.</param> /// <param name="arg7">The seventh argument.</param> /// <param name="arg8">The eighth argument.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, object? arg1, object? arg2, object? arg3, object? arg4, object? arg5, object? arg6, object? arg7, object? arg8, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, new[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 }, cancellationToken); } /// <summary> /// Invokes a hub method on the server using the specified method name and arguments. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> /// <param name="arg4">The fourth argument.</param> /// <param name="arg5">The fifth argument.</param> /// <param name="arg6">The sixth argument.</param> /// <param name="arg7">The seventh argument.</param> /// <param name="arg8">The eighth argument.</param> /// <param name="arg9">The ninth argument.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, object? arg1, object? arg2, object? arg3, object? arg4, object? arg5, object? arg6, object? arg7, object? arg8, object? arg9, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, new[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 }, cancellationToken); } /// <summary> /// Invokes a hub method on the server using the specified method name and arguments. /// Does not wait for a response from the receiver. /// </summary> /// <param name="hubConnection">The hub connection.</param> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> /// <param name="arg4">The fourth argument.</param> /// <param name="arg5">The fifth argument.</param> /// <param name="arg6">The sixth argument.</param> /// <param name="arg7">The seventh argument.</param> /// <param name="arg8">The eighth argument.</param> /// <param name="arg9">The ninth argument.</param> /// <param name="arg10">The tenth argument.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous invoke.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendAsync(this HubConnection hubConnection, string methodName, object? arg1, object? arg2, object? arg3, object? arg4, object? arg5, object? arg6, object? arg7, object? arg8, object? arg9, object? arg10, CancellationToken cancellationToken = default) { return hubConnection.SendCoreAsync(methodName, new[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10 }, cancellationToken); } } }
// 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.Buffers; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using Internal.Cryptography; using ErrorCode = Interop.NCrypt.ErrorCode; using AsymmetricPaddingMode = Interop.NCrypt.AsymmetricPaddingMode; using BCRYPT_OAEP_PADDING_INFO = Interop.BCrypt.BCRYPT_OAEP_PADDING_INFO; namespace System.Security.Cryptography { #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS internal static partial class RSAImplementation { #endif public sealed partial class RSACng : RSA { private const int Pkcs1PaddingOverhead = 11; /// <summary>Encrypts data using the public key.</summary> public override unsafe byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => EncryptOrDecrypt(data, padding, encrypt: true); /// <summary>Decrypts data using the private key.</summary> public override unsafe byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => EncryptOrDecrypt(data, padding, encrypt: false); /// <summary>Encrypts data using the public key.</summary> public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) => TryEncryptOrDecrypt(data, destination, padding, encrypt: true, bytesWritten: out bytesWritten); /// <summary>Decrypts data using the private key.</summary> public override bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) => TryEncryptOrDecrypt(data, destination, padding, encrypt: false, bytesWritten: out bytesWritten); // Conveniently, Encrypt() and Decrypt() are identical save for the actual P/Invoke call to CNG. Thus, both // array-based APIs invoke this common helper with the "encrypt" parameter determining whether encryption or decryption is done. private unsafe byte[] EncryptOrDecrypt(byte[] data, RSAEncryptionPadding padding, bool encrypt) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize); if (!encrypt && data.Length != modulusSizeInBytes) { throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize); } if (encrypt && padding.Mode == RSAEncryptionPaddingMode.Pkcs1 && data.Length > modulusSizeInBytes - Pkcs1PaddingOverhead) { throw new CryptographicException( SR.Format(SR.Cryptography_Encryption_MessageTooLong, modulusSizeInBytes - Pkcs1PaddingOverhead)); } using (SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle()) { if (encrypt && data.Length == 0) { byte[] rented = ArrayPool<byte>.Shared.Rent(modulusSizeInBytes); Span<byte> paddedMessage = new Span<byte>(rented, 0, modulusSizeInBytes); try { if (padding == RSAEncryptionPadding.Pkcs1) { RsaPaddingProcessor.PadPkcs1Encryption(data, paddedMessage); } else if (padding.Mode == RSAEncryptionPaddingMode.Oaep) { RsaPaddingProcessor processor = RsaPaddingProcessor.OpenProcessor(padding.OaepHashAlgorithm); processor.PadOaep(data, paddedMessage); } else { throw new CryptographicException(SR.Cryptography_UnsupportedPaddingMode); } return EncryptOrDecrypt(keyHandle, paddedMessage, AsymmetricPaddingMode.NCRYPT_NO_PADDING_FLAG, null, encrypt); } finally { CryptographicOperations.ZeroMemory(paddedMessage); ArrayPool<byte>.Shared.Return(rented); } } switch (padding.Mode) { case RSAEncryptionPaddingMode.Pkcs1: return EncryptOrDecrypt(keyHandle, data, AsymmetricPaddingMode.NCRYPT_PAD_PKCS1_FLAG, null, encrypt); case RSAEncryptionPaddingMode.Oaep: IntPtr namePtr = Marshal.StringToHGlobalUni(padding.OaepHashAlgorithm.Name); try { var paddingInfo = new BCRYPT_OAEP_PADDING_INFO() { pszAlgId = namePtr, // It would nice to put randomized data here but RSAEncryptionPadding does not at this point provide support for this. pbLabel = IntPtr.Zero, cbLabel = 0, }; return EncryptOrDecrypt(keyHandle, data, AsymmetricPaddingMode.NCRYPT_PAD_OAEP_FLAG, &paddingInfo, encrypt); } finally { Marshal.FreeHGlobal(namePtr); } default: throw new CryptographicException(SR.Cryptography_UnsupportedPaddingMode); } } } // Conveniently, Encrypt() and Decrypt() are identical save for the actual P/Invoke call to CNG. Thus, both // span-based APIs invoke this common helper with the "encrypt" parameter determining whether encryption or decryption is done. private unsafe bool TryEncryptOrDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, bool encrypt, out int bytesWritten) { if (padding == null) { throw new ArgumentNullException(nameof(padding)); } int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize); if (!encrypt && data.Length != modulusSizeInBytes) { throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize); } if (encrypt && padding.Mode == RSAEncryptionPaddingMode.Pkcs1 && data.Length > modulusSizeInBytes - Pkcs1PaddingOverhead) { throw new CryptographicException( SR.Format(SR.Cryptography_Encryption_MessageTooLong, modulusSizeInBytes - Pkcs1PaddingOverhead)); } using (SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle()) { if (encrypt && data.Length == 0) { byte[] rented = ArrayPool<byte>.Shared.Rent(modulusSizeInBytes); Span<byte> paddedMessage = new Span<byte>(rented, 0, modulusSizeInBytes); try { if (padding == RSAEncryptionPadding.Pkcs1) { RsaPaddingProcessor.PadPkcs1Encryption(data, paddedMessage); } else if (padding.Mode == RSAEncryptionPaddingMode.Oaep) { RsaPaddingProcessor processor = RsaPaddingProcessor.OpenProcessor(padding.OaepHashAlgorithm); processor.PadOaep(data, paddedMessage); } else { throw new CryptographicException(SR.Cryptography_UnsupportedPaddingMode); } return TryEncryptOrDecrypt(keyHandle, paddedMessage, destination, AsymmetricPaddingMode.NCRYPT_NO_PADDING_FLAG, null, encrypt, out bytesWritten); } finally { CryptographicOperations.ZeroMemory(paddedMessage); ArrayPool<byte>.Shared.Return(rented); } } switch (padding.Mode) { case RSAEncryptionPaddingMode.Pkcs1: return TryEncryptOrDecrypt(keyHandle, data, destination, AsymmetricPaddingMode.NCRYPT_PAD_PKCS1_FLAG, null, encrypt, out bytesWritten); case RSAEncryptionPaddingMode.Oaep: IntPtr namePtr = Marshal.StringToHGlobalUni(padding.OaepHashAlgorithm.Name); try { var paddingInfo = new BCRYPT_OAEP_PADDING_INFO() { pszAlgId = namePtr, pbLabel = IntPtr.Zero, // It would nice to put randomized data here but RSAEncryptionPadding does not at this point provide support for this. cbLabel = 0, }; return TryEncryptOrDecrypt(keyHandle, data, destination, AsymmetricPaddingMode.NCRYPT_PAD_OAEP_FLAG, &paddingInfo, encrypt, out bytesWritten); } finally { Marshal.FreeHGlobal(namePtr); } default: throw new CryptographicException(SR.Cryptography_UnsupportedPaddingMode); } } } // Now that the padding mode and information have been marshaled to their native counterparts, perform the encryption or decryption. private unsafe byte[] EncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan<byte> input, AsymmetricPaddingMode paddingMode, void* paddingInfo, bool encrypt) { int estimatedSize = KeySize / 8; #if DEBUG estimatedSize = 2; // Make sure the NTE_BUFFER_TOO_SMALL scenario gets exercised. #endif byte[] output = new byte[estimatedSize]; int numBytesNeeded; ErrorCode errorCode = encrypt ? Interop.NCrypt.NCryptEncrypt(key, input, input.Length, paddingInfo, output, output.Length, out numBytesNeeded, paddingMode) : Interop.NCrypt.NCryptDecrypt(key, input, input.Length, paddingInfo, output, output.Length, out numBytesNeeded, paddingMode); if (errorCode == ErrorCode.NTE_BUFFER_TOO_SMALL) { output = new byte[numBytesNeeded]; errorCode = encrypt ? Interop.NCrypt.NCryptEncrypt(key, input, input.Length, paddingInfo, output, output.Length, out numBytesNeeded, paddingMode) : Interop.NCrypt.NCryptDecrypt(key, input, input.Length, paddingInfo, output, output.Length, out numBytesNeeded, paddingMode); } if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } Array.Resize(ref output, numBytesNeeded); return output; } // Now that the padding mode and information have been marshaled to their native counterparts, perform the encryption or decryption. private unsafe bool TryEncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan<byte> input, Span<byte> output, AsymmetricPaddingMode paddingMode, void* paddingInfo, bool encrypt, out int bytesWritten) { int numBytesNeeded; ErrorCode errorCode = encrypt ? Interop.NCrypt.NCryptEncrypt(key, input, input.Length, paddingInfo, output, output.Length, out numBytesNeeded, paddingMode) : Interop.NCrypt.NCryptDecrypt(key, input, input.Length, paddingInfo, output, output.Length, out numBytesNeeded, paddingMode); switch (errorCode) { case ErrorCode.ERROR_SUCCESS: bytesWritten = numBytesNeeded; return true; case ErrorCode.NTE_BUFFER_TOO_SMALL: bytesWritten = 0; return false; default: throw errorCode.ToCryptographicException(); } } } #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS } #endif }
// // Encog(tm) Core v3.2 - .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 Encog.MathUtil.Matrices; using Encog.MathUtil.Matrices.Decomposition; using Encog.MathUtil.Randomize; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.Util; namespace Encog.ML.HMM.Distributions { /// <summary> /// A continuous distribution represents an infinite range of choices between two /// real numbers. A gaussian distribution is used to distribute the probability. /// </summary> [Serializable] public class ContinousDistribution : IStateDistribution { /// <summary> /// The covariance matrix. /// </summary> private readonly Matrix _covariance; /// <summary> /// The dimensions. /// </summary> private readonly int _dimension; /// <summary> /// The means for each dimension. /// </summary> private readonly double[] _mean; /// <summary> /// Random number generator. /// </summary> private readonly GaussianRandomizer _randomizer = new GaussianRandomizer(0.0, 1.0); /// <summary> /// Used to perform a decomposition. /// </summary> private CholeskyDecomposition _cd; /// <summary> /// The covariance determinant. /// </summary> private double _covarianceDet; /// <summary> /// The covariance inverse. /// </summary> private Matrix _covarianceInv; /// <summary> /// The covariance left side. /// </summary> private Matrix _covarianceL; /// <summary> /// Construct a continuous distribution. /// </summary> /// <param name="mean">The mean.</param> /// <param name="covariance">The covariance.</param> public ContinousDistribution(double[] mean, double[][] covariance) { _dimension = covariance.Length; _mean = EngineArray.ArrayCopy(mean); _covariance = new Matrix(covariance); Update(covariance); } /// <summary> /// Construct a continuous distribution with the specified number of dimensions. /// </summary> /// <param name="dimension">The dimensions.</param> public ContinousDistribution(int dimension) { if (dimension <= 0) { throw new EncogError("Invalid number of dimensions"); } _dimension = dimension; _mean = new double[dimension]; _covariance = new Matrix(dimension, dimension); } /// <summary> /// The mean for the dimensions of the gaussian curve. /// </summary> public double[] Mean { get { return _mean; } } /// <summary> /// The covariance matrix. /// </summary> public Matrix Covariance { get { return _covariance; } } #region IStateDistribution Members /// <inheritdoc/> public void Fit(IMLDataSet co) { var weights = new double[co.Count]; EngineArray.Fill(weights, 1.0 / co.Count); Fit(co, weights); } /// <inheritdoc/> public void Fit(IMLDataSet co, double[] weights) { int i; if ((co.Count < 1) || (co.Count != weights.Length)) { throw new EncogError("Invalid weight size"); } // Compute mean var mean = new double[_dimension]; for (int r = 0; r < _dimension; r++) { i = 0; foreach (IMLDataPair o in co) { mean[r] += o.Input[r] * weights[i++]; } } // Compute covariance double[][] covariance = EngineArray.AllocateDouble2D(_dimension, _dimension); i = 0; foreach (IMLDataPair o in co) { //double[] obs = o.Input.CreateCentroid(); var omm = new double[o.Input.Count]; for (int j = 0; j < omm.Length; j++) { omm[j] = o.Input[j] - mean[j]; } for (int r = 0; r < _dimension; r++) { for (int c = 0; c < _dimension; c++) { covariance[r][c] += omm[r] * omm[c] * weights[i]; } } i++; } Update(covariance); } /// <inheritdoc/> public IMLDataPair Generate() { var d = new double[_dimension]; for (int i = 0; i < _dimension; i++) { d[i] = _randomizer.Randomize(0); } double[] d2 = MatrixMath.Multiply(_covarianceL, d); return new BasicMLDataPair(new BasicMLData(EngineArray.Add(d2, _mean))); } /// <inheritdoc/> public double Probability(IMLDataPair o) { // double[] v = o.InputArray; // Matrix vmm = Matrix.CreateColumnMatrix(EngineArray.Subtract(v, Matrix vmm = Matrix.CreateColumnMatrix(EngineArray.Subtract(o.Input, _mean)); Matrix t = MatrixMath.Multiply(_covarianceInv, vmm); double expArg = MatrixMath.Multiply(MatrixMath.Transpose(vmm), t) [0, 0] * -0.5; return Math.Exp(expArg) / (Math.Pow(2.0 * Math.PI, _dimension / 2.0) * Math.Pow( _covarianceDet, 0.5)); } /// <inheritdoc/> IStateDistribution IStateDistribution.Clone() { return new ContinousDistribution((double[])_mean.Clone(), (double[][])_covariance.Data.Clone()); } #endregion /// <summary> /// Update the covariance. /// </summary> /// <param name="covariance">The new covariance.</param> public void Update(double[][] covariance) { _cd = new CholeskyDecomposition(new Matrix(covariance)); _covarianceL = _cd.L; _covarianceInv = _cd.InverseCholesky(); _covarianceDet = _cd.GetDeterminant(); } } }
// // ChangePhotoPathGui.cs // // Author: // Stephane Delcroix <sdelcroix*novell.com> // // Copyright (C) 2008 Novell, Inc. // Copyright (C) 2008 Stephane Delcroix // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // ChangePhotoPath.IChangePhotoPathGui.cs: The Gui to change the photo path in photos.db // // Author: // Bengt Thuree ([email protected]) // // Copyright (C) 2007 // using FSpot.Extensions; using FSpot.UI.Dialog; using System; //using Gnome.Vfs; using Gtk; using Hyena; using Hyena.Widgets; namespace FSpot.Tools.ChangePhotoPath { public class Dump : Gtk.Dialog, ICommand, IChangePhotoPathGui { private string dialog_name = "ChangePhotoPath"; private GtkBeans.Builder builder; private Gtk.Dialog dialog; private ChangePathController contr; private ProgressDialog progress_dialog; private int progress_dialog_total = 0; [GtkBeans.Builder.Object] Gtk.Entry old_common_uri; [GtkBeans.Builder.Object] Gtk.Label new_common_uri; private bool LaunchController() { try { contr = new ChangePathController ( this ); } catch (Exception e) { Log.Exception(e); return false; } return true; } public void create_progress_dialog(string txt, int total) { progress_dialog = new ProgressDialog (txt, ProgressDialog.CancelButtonType.Stop, total, dialog); } public void LaunchDialog() { CreateDialog(); Dialog.Modal = false; Dialog.TransientFor = null; if (LaunchController() && contr.CanWeRun()) { DisplayDoNotStopFSpotMsg(); Dialog.ShowAll(); Dialog.Response += HandleResponse; } else { DisplayOrigBasePathNotFoundMsg(); Dialog.Destroy(); } } private void CreateDialog() { builder = new GtkBeans.Builder (null, "ChangePhotoPath.ui", null); builder.Autoconnect (this); } private Gtk.Dialog Dialog { get { if (dialog == null) dialog = new Gtk.Dialog (builder.GetRawObject (dialog_name)); return dialog; } } private void DisplayMsg(Gtk.MessageType MessageType, string msg) { HigMessageDialog.RunHigMessageDialog ( null, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, MessageType, Gtk.ButtonsType.Ok, msg, null); } private void DisplayDoNotStopFSpotMsg() { DisplayMsg (Gtk.MessageType.Info, "It will take a long time for SqLite to update the database if you have many photos." + "\nWe recommend you to let F-Spot be running during the night to ensure everything is written to disk."+ "\nChanging path on 23000 photos took 2 hours until sqlite had updated all photos in the database."); } private void DisplayOrigBasePathNotFoundMsg() { DisplayMsg (Gtk.MessageType.Error, "Could not find an old base path. /YYYY/MM/DD need to start with /20, /19 or /18."); } private void DisplayCancelledMsg() { DisplayMsg (Gtk.MessageType.Warning, "Operation aborted. Database has not been modified."); } private void DisplaySamePathMsg() { DisplayMsg (Gtk.MessageType.Warning, "New and Old base path are the same."); } private void DisplayNoPhotosFoundMsg() { DisplayMsg (Gtk.MessageType.Warning, "Did not find any photos with the old base path."); } private void DisplayExecutionOkMsg() { DisplayMsg (Gtk.MessageType.Info, "Completed successfully. Please ensure you wait 1-2 hour before you exit f-spot. This to ensure the database cache is written to disk."); } private void DisplayExecutionNotOkMsg() { DisplayMsg (Gtk.MessageType.Error, "An error occured. Reverted all changes to the database."); } private void HandleResponse (object sender, Gtk.ResponseArgs args) { bool destroy_dialog = false; ChangePhotoPath.ProcessResult tmp_res; if (args.ResponseId == Gtk.ResponseType.Ok) { tmp_res = contr.ChangePathOnPhotos (old_common_uri.Text, new_common_uri.Text); switch (tmp_res) { case ProcessResult.Ok : DisplayExecutionOkMsg(); destroy_dialog=true; break; case ProcessResult.Cancelled : DisplayCancelledMsg(); break; case ProcessResult.Error : DisplayExecutionNotOkMsg(); break; case ProcessResult.SamePath : DisplaySamePathMsg(); break; case ProcessResult.NoPhotosFound : DisplayNoPhotosFoundMsg(); break; case ProcessResult.Processing : Log.Debug ("processing"); break; } } else destroy_dialog = true; remove_progress_dialog(); if (destroy_dialog) Dialog.Destroy(); return; } public void DisplayDefaultPaths (string oldpath, string newpath) { old_common_uri.Text = oldpath; new_common_uri.Text = newpath; } public void remove_progress_dialog () { if (progress_dialog != null) { progress_dialog.Destroy(); progress_dialog = null; } } public void check_if_remove_progress_dialog (int total) { if (total != progress_dialog_total) remove_progress_dialog(); } public bool UpdateProgressBar (string hdr_txt, string txt, int total) { if (progress_dialog != null) check_if_remove_progress_dialog(total); if (progress_dialog == null) create_progress_dialog(hdr_txt, total); progress_dialog_total = total; return progress_dialog.Update (String.Format ("{0} ", txt)); } public void Run (object sender, EventArgs args) { try { LaunchDialog( ); } catch (Exception e) { Log.Exception(e); } } } }
using System; using System.Collections.Generic; using System.IO; using Loon.Core; using Loon.Core.Geom; using Loon.Core.Resource; using Loon.Core.Graphics.Opengl; using Loon.Core.Input; using Loon.Utils.Xml; using Loon.Utils; namespace Loon.Action.Map.Tmx { public class TMXTiledMap : LRelease { protected internal int width; protected internal int height; protected internal int tileWidth; protected internal int tileHeight; private RectBox screenRect; protected internal string tilesLocation; protected internal TMXProperty props; protected internal List<TMXTileSet> tileSets = new List<TMXTileSet>(); protected internal List<TMXLayer> layers = new List<TMXLayer>(); protected internal List<TMXTileGroup> objectGroups = new List<TMXTileGroup>(); private bool loadTileSets = true; private int defWidth, defHeight; public TMXTiledMap(string fileName):this(fileName, true) { } public TMXTiledMap(string fileName, bool loadTileSets_0) { this.loadTileSets = loadTileSets_0; fileName = fileName.Replace('\\', '/'); string res = null; if (fileName.IndexOf("/") != -1) { res = fileName.Substring(0, (fileName.LastIndexOf("/")) - (0)); } else { res = fileName; } try { this.Load(Resources.OpenStream(fileName), res); } catch (Exception e) { Console.Error.WriteLine(e.StackTrace); } } public TMXTiledMap(string fileName, string tileSetsLocation) { try { Load(Resources.OpenStream(fileName), tileSetsLocation); } catch (IOException e) { Console.Error.WriteLine(e.StackTrace); } } public TMXTiledMap(Stream ins0) { Load(ins0, ""); } public TMXTiledMap(Stream ins0, string tileSetsLocation) { Load(ins0, tileSetsLocation); } public string GetTilesLocation() { return tilesLocation; } public int GetLayerIndex(string name) { for (int i = 0; i < layers.Count; i++) { TMXLayer layer = layers[i]; if (layer.name.Equals(name)) { return i; } } return -1; } public LTexture GetTileImage(int x, int y, int layerIndex) { TMXLayer layer = layers[layerIndex]; int tileSetIndex = layer.data[x,y,0]; if ((tileSetIndex >= 0) && (tileSetIndex < tileSets.Count)) { TMXTileSet tileSet = tileSets[tileSetIndex]; int sheetX = tileSet.GetTileX(layer.data[x,y,1]); int sheetY = tileSet.GetTileY(layer.data[x,y,1]); return tileSet.tiles.GetSubImage(sheetX, sheetY); } return null; } public int GetWidth() { return width; } public int GetHeight() { return height; } public int GetTileHeight() { return tileHeight; } public int GetTileWidth() { return tileWidth; } public TMXLayer GetLayer(int id) { return layers[id]; } public int GetTileId(int x, int y, int layerIndex) { TMXLayer layer = layers[layerIndex]; return layer.GetTileID(x, y); } public void SetTileId(int x, int y, int layerIndex, int tileid) { TMXLayer layer = layers[layerIndex]; layer.SetTileID(x, y, tileid); } public string GetMapProperty(string propertyName, string def) { if (props == null) return def; return props.GetProperty(propertyName, def); } public string GetLayerProperty(int layerIndex, string propertyName, string def) { TMXLayer layer = layers[layerIndex]; if (layer == null || layer.props == null) return def; return layer.props.GetProperty(propertyName, def); } public string GetTileProperty(int tileID, string propertyName, string def) { if (tileID == 0) { return def; } TMXTileSet set = FindTileSet(tileID); TMXProperty props_0 = set.GetProperties(tileID); if (props_0 == null) { return def; } return props_0.GetProperty(propertyName, def); } public void Draw(GLEx g, LTouch e) { int x = e.X() / tileWidth; int y = e.Y() / tileHeight; Draw(g, 0, 0, x, y, width - defWidth, height - defHeight, false); } public void Draw(GLEx g, int tx, int ty) { Draw(g, 0, 0, tx, ty); } public void Draw(GLEx g, int x, int y, int tx, int ty) { Draw(g, x, y, tx, ty, defWidth, defHeight, false); } public void Draw(GLEx g, int x, int y, int layer) { Draw(g, x, y, 0, 0, GetWidth(), GetHeight(), layer, false); } public void Draw(GLEx g, int x, int y, int sx, int sy, int width, int height) { Draw(g, x, y, sx, sy, width, height, false); } public void Draw(GLEx g, int x, int y, int sx, int sy, int width, int height, int index, bool lineByLine) { TMXLayer layer = layers[index]; layer.Draw(g, x, y, sx, sy, width, height, lineByLine, tileWidth, tileHeight); } public void Draw(GLEx g, int x, int y, int sx, int sy, int width, int height, bool lineByLine) { for (int i = 0; i < layers.Count; i++) { TMXLayer layer = layers[i]; layer.Draw(g, x, y, sx, sy, width, height, lineByLine, tileWidth, tileHeight); } } public int GetLayerCount() { return layers.Count; } private void Load(Stream ins, string tileSetsLocation) { screenRect = LSystem.screenRect; tilesLocation = tileSetsLocation; try { XMLDocument doc = XMLParser.Parse(ins); XMLElement docElement = doc.GetRoot(); string orient = docElement.GetAttribute("orientation", ""); if (!"orthogonal".Equals(orient)) { throw new Exception( "Only orthogonal maps supported, found " + orient); } width = docElement.GetIntAttribute("width", 0); height = docElement.GetIntAttribute("height", 0); tileWidth = docElement.GetIntAttribute("tilewidth", 0); tileHeight = docElement.GetIntAttribute("tileheight", 0); XMLElement propsElement = docElement .GetChildrenByName("properties"); if (propsElement != null) { props = new TMXProperty(); List<XMLElement> property = propsElement.List("property"); for (int i = 0; i < property.Count; i++) { XMLElement propElement = property[i]; string name = propElement.GetAttribute("name", null); string value_ren = propElement.GetAttribute("value", null); props.SetProperty(name, value_ren); } } if (loadTileSets) { TMXTileSet tileSet = null; TMXTileSet lastSet = null; List<XMLElement> setNodes = docElement.List("tileset"); for (int i_0 = 0; i_0 < setNodes.Count; i_0++) { XMLElement current = setNodes[i_0]; tileSet = new TMXTileSet(this, current, true); tileSet.index = i_0; if (lastSet != null) { lastSet.SetLimit(tileSet.firstGID - 1); } lastSet = tileSet; CollectionUtils.Add(tileSets, tileSet); } } List<XMLElement> layerNodes = docElement.List("layer"); for (int i_1 = 0; i_1 < layerNodes.Count; i_1++) { XMLElement current_2 = layerNodes[i_1]; TMXLayer layer = new TMXLayer(this, current_2); layer.index = i_1; CollectionUtils.Add(layers, layer); } List<XMLElement> objectGroupNodes = docElement .List("objectgroup"); for (int i_3 = 0; i_3 < objectGroupNodes.Count; i_3++) { XMLElement current_4 = objectGroupNodes[i_3]; TMXTileGroup objectGroup = new TMXTileGroup(current_4); objectGroup.index = i_3; CollectionUtils.Add(objectGroups, objectGroup); } defWidth = (int)(screenRect.GetWidth() / tileWidth); defHeight = (int)(screenRect.GetHeight() / tileHeight); } catch (Exception ex) { Console.Error.WriteLine(ex.StackTrace); throw new Exception("Failed to parse map", ex); } } public int GetScreenWidth() { return defWidth; } public int GetScreenHeight() { return defHeight; } public int GetTileSetCount() { return tileSets.Count; } public TMXTileSet GetTileSet(int index) { return tileSets[index]; } public TMXTileSet GetTileSetByGID(int gid) { for (int i = 0; i < tileSets.Count; i++) { TMXTileSet set = tileSets[i]; if (set.Contains(gid)) { return set; } } return null; } public TMXTileSet FindTileSet(int gid) { for (int i = 0; i < tileSets.Count; i++) { TMXTileSet set = tileSets[i]; if (set.Contains(gid)) { return set; } } return null; } protected internal void Draw(GLEx g, int x, int y, int sx, int sy, int width, int height, int layer) { } public int GetObjectGroupCount() { return objectGroups.Count; } public int GetObjectCount(int groupID) { if (groupID >= 0 && groupID < objectGroups.Count) { TMXTileGroup grp = objectGroups[groupID]; return grp.objects.Count; } return -1; } public string GetObjectName(int groupID, int objectID) { if (groupID >= 0 && groupID < objectGroups.Count) { TMXTileGroup grp = objectGroups[groupID]; if (objectID >= 0 && objectID < grp.objects.Count) { TMXTile obj0 = grp.objects[objectID]; return obj0.name; } } return null; } public string GetObjectType(int groupID, int objectID) { if (groupID >= 0 && groupID < objectGroups.Count) { TMXTileGroup grp = objectGroups[groupID]; if (objectID >= 0 && objectID < grp.objects.Count) { TMXTile obj0 = grp.objects[objectID]; return obj0.type; } } return null; } public int GetObjectX(int groupID, int objectID) { if (groupID >= 0 && groupID < objectGroups.Count) { TMXTileGroup grp = objectGroups[groupID]; if (objectID >= 0 && objectID < grp.objects.Count) { TMXTile obj0 = grp.objects[objectID]; return obj0.x; } } return -1; } public int GetObjectY(int groupID, int objectID) { if (groupID >= 0 && groupID < objectGroups.Count) { TMXTileGroup grp = objectGroups[groupID]; if (objectID >= 0 && objectID < grp.objects.Count) { TMXTile obj0 = grp.objects[objectID]; return obj0.y; } } return -1; } public int GetObjectWidth(int groupID, int objectID) { if (groupID >= 0 && groupID < objectGroups.Count) { TMXTileGroup grp = objectGroups[groupID]; if (objectID >= 0 && objectID < grp.objects.Count) { TMXTile obj0 = grp.objects[objectID]; return obj0.width; } } return -1; } public int GetObjectHeight(int groupID, int objectID) { if (groupID >= 0 && groupID < objectGroups.Count) { TMXTileGroup grp = objectGroups[groupID]; if (objectID >= 0 && objectID < grp.objects.Count) { TMXTile obj0 = grp.objects[objectID]; return obj0.height; } } return -1; } public string GetObjectImage(int groupID, int objectID) { if (groupID >= 0 && groupID < objectGroups.Count) { TMXTileGroup grp = objectGroups[groupID]; if (objectID >= 0 && objectID < grp.objects.Count) { TMXTile obj0 = grp.objects[objectID]; if (obj0 == null) { return null; } return obj0.image; } } return null; } public string GetObjectProperty(int groupID, int objectID, string propertyName, string def) { if (groupID >= 0 && groupID < objectGroups.Count) { TMXTileGroup grp = objectGroups[groupID]; if (objectID >= 0 && objectID < grp.objects.Count) { TMXTile obj0 = grp.objects[objectID]; if (obj0 == null) { return def; } if (obj0.props == null) { return def; } return obj0.props.GetProperty(propertyName, def); } } return def; } public virtual void Dispose() { if (tileSets != null) { foreach (TMXTileSet tmx in tileSets) { if (tmx != null) { tmx.Dispose(); } } } } } }
using System.IO; using NMock2.Matchers; using NMock2.Monitoring; using NMock2.Test.Monitoring; using NUnit.Framework; namespace NMock2.Internal.Test { [TestFixture] public class BuildableExpectationTest { private Invocation invocation; [SetUp] public void SetUp() { invocation = new Invocation("receiver", new MethodInfoStub("method"), new object[] { "arg" }); } [Test] public void MatchesIfAllMatchersMatch() { BuildableExpectation e = BuildExpectation(true, true, true, true, true, true, true); Assert.IsTrue( e.Matches(this.invocation), "should match"); } [Test] public void DoesNotMatchIfAnyMatcherDoesNotMatch() { const bool ignoreRequiredCallCount = true; for (int i = 1; i < 64; i++) { BuildableExpectation e = BuildExpectation( ignoreRequiredCallCount, (i & 1) == 0, (i & 2) == 0, (i & 4) == 0, (i & 8) == 0, (i & 16) == 0, (i & 32) == 0); Assert.IsFalse(e.Matches(this.invocation), "should not match (iteration "+i+")"); } } [Test] public void InvokesAListOfActionsToPerformAnInvocation() { BuildableExpectation e = BuildExpectation(true,true,true,true,true,true,true); MockAction action1 = new MockAction(); MockAction action2 = new MockAction(); e.AddAction(action1); e.AddAction(action2); e.Perform(invocation); Assert.AreSame( invocation, action1.Received, "action1 received"); Assert.AreSame( invocation, action2.Received, "action1 received"); } [Test] public void MatchesCallCountWhenMatchingInvocation() { Matcher irrelevant = Is.Anything; BuildableExpectation expectation = BuildExpectation( "description", irrelevant, Is.AtMost(4), irrelevant, irrelevant, irrelevant, irrelevant, irrelevant); AssertIsActive(expectation, "should be active before any invocation"); Assert.IsTrue(expectation.Matches(invocation), "should match 1st invocation"); expectation.Perform(invocation); AssertIsActive(expectation, "should be active before 2nd invocation"); Assert.IsTrue(expectation.Matches(invocation), "should match 2nd invocation"); expectation.Perform(invocation); AssertIsActive(expectation, "should be active before 3rd invocation"); Assert.IsTrue(expectation.Matches(invocation), "should match 3rd invocation"); expectation.Perform(invocation); AssertIsActive(expectation, "should be active before 4th invocation"); Assert.IsTrue(expectation.Matches(invocation), "should match 4th invocation"); expectation.Perform(invocation); AssertIsNotActive(expectation, "should not be active after 4th invocation"); Assert.IsFalse(expectation.Matches(invocation), "should not match 5th invocation"); } [Test] public void ChecksCallCountToAssertThatItHasBeenMet() { Matcher irrelevant = Is.Anything; BuildableExpectation expectation = BuildExpectation( "description", Is.AtLeast(2), Is.AtMost(4), irrelevant, irrelevant, irrelevant, irrelevant, irrelevant); AssertHasNotBeenMet(expectation, "should not have been met after no invocations"); expectation.Perform(invocation); AssertHasNotBeenMet(expectation, "should not have been met after 1 invocation"); expectation.Perform(invocation); AssertHasBeenMet(expectation, "should have been met after 2 invocations"); expectation.Perform(invocation); AssertHasBeenMet(expectation, "should have been met after 3 invocations"); expectation.Perform(invocation); AssertHasBeenMet(expectation, "should have been met after 4 invocations"); } [Test] public void HasReadableDescription() { BuildableExpectation expectation = BuildExpectation( "expectation", "required call count description is ignored", "matching call count description is ignored", "receiver", "method", "(arguments)", "extra matcher 1", "extra matcher 2" ); expectation.AddAction(new MockAction("action 1")); expectation.AddAction(new MockAction("action 2")); AssertDescriptionIsEqual(expectation, "expectation: receiver.method(arguments), extra matcher 1, extra matcher 2, will action 1, action 2 [called 0 times]"); } [Test] public void WillNotPrintAPeriodBetweenReceiverAndMethodIfToldToDescribeItselfAsAnIndexer() { BuildableExpectation expectation = BuildExpectation( "expectation", "required call count description is ignored", "matching call count description is ignored", "receiver", "", "[arguments]", "extra matcher 1", "extra matcher 2" ); expectation.AddAction(new MockAction("action 1")); expectation.AddAction(new MockAction("action 2")); expectation.DescribeAsIndexer(); AssertDescriptionIsEqual(expectation, "expectation: receiver[arguments], extra matcher 1, extra matcher 2, will action 1, action 2 [called 0 times]"); } private static BuildableExpectation BuildExpectation( bool matchRequiredCallCount, bool matchMatchingCallCount, bool matchReceiver, bool matchMethod, bool matchArguments, params bool[] matchExtraMatchers) { Matcher[] extraMatchers = new Matcher[matchExtraMatchers.Length]; for (int i = 0; i < extraMatchers.Length; i++) { extraMatchers[i] = new AlwaysMatcher(matchExtraMatchers[i], "extra matcher "+(i+1)); } return BuildExpectation( "description", new AlwaysMatcher(matchRequiredCallCount, "required call count"), new AlwaysMatcher(matchMatchingCallCount, "matching call count"), new AlwaysMatcher(matchReceiver, "receiver"), new AlwaysMatcher(matchMethod, "method"), new AlwaysMatcher(matchArguments, "argument"), extraMatchers ); } private static BuildableExpectation BuildExpectation( string expectationDescription, string matchRequiredCallCountDescription, string matchMatchingCallCountDescription, string matchReceiverDescription, string matchMethodDescription, string matchArgumentsDescription, params string[] extraMatcherDescriptions) { bool irrelevant = true; Matcher[] extraMatchers = new Matcher[extraMatcherDescriptions.Length]; for (int i = 0; i < extraMatchers.Length; i++) { extraMatchers[i] = new AlwaysMatcher(irrelevant, extraMatcherDescriptions[i]); } return BuildExpectation( expectationDescription, new AlwaysMatcher(irrelevant, matchRequiredCallCountDescription), new AlwaysMatcher(irrelevant, matchMatchingCallCountDescription), new AlwaysMatcher(irrelevant, matchReceiverDescription), new AlwaysMatcher(irrelevant, matchMethodDescription), new AlwaysMatcher(irrelevant, matchArgumentsDescription), extraMatchers); } private static BuildableExpectation BuildExpectation( string description, Matcher requiredCallCountMatcher, Matcher matchingCallCountMatcher, Matcher receiverMatcher, Matcher methodMatcher, Matcher argumentsMatcher, params Matcher[] extraMatchers) { BuildableExpectation e = new BuildableExpectation(description, requiredCallCountMatcher, matchingCallCountMatcher); e.ArgumentsMatcher = argumentsMatcher; e.MethodMatcher = methodMatcher; e.ReceiverMatcher = receiverMatcher; foreach (Matcher extraMatcher in extraMatchers) e.AddInvocationMatcher(extraMatcher); return e; } private void AssertIsActive(IExpectation expectation, string message) { Assert.IsTrue(expectation.IsActive, message); } private void AssertHasBeenMet(IExpectation expectation, string message) { Assert.IsTrue(expectation.HasBeenMet, message); } private void AssertHasNotBeenMet(IExpectation expectation, string message) { Assert.IsFalse(expectation.HasBeenMet, message); } private void AssertIsNotActive(IExpectation expectation, string message) { Assert.IsFalse(expectation.IsActive, message); } private void AssertDescriptionIsEqual(BuildableExpectation expectation, string expected) { DescriptionWriter writer = new DescriptionWriter(); expectation.DescribeActiveExpectationsTo(writer); Assert.AreEqual(expected, writer.ToString()); } } class MockAction : IAction { public Invocation Received = null; public MockAction Previous = null; public string Description; public MockAction() : this("MockAction") { } public MockAction(string description) { this.Description = description; } public void Invoke(Invocation invocation) { if (Previous != null) Assert.IsNotNull(Previous.Received, "called out of order"); Received = invocation; } public void DescribeTo(TextWriter writer) { writer.Write(Description); } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at [email protected] // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using MbUnit.Framework; using Subtext.Scripting; namespace UnitTests.Subtext.Scripting { /// <summary> /// Tests parsing template parameters in a script. /// </summary> [TestFixture] public class TemplateParameterParseTests { [Test] public void AddWithNullTemplateParameterThrowsArgumentNullException() { var collection = new TemplateParameterCollection(); UnitTestHelper.AssertThrowsArgumentNullException(() => collection.Add((TemplateParameter)null)); } [Test] public void AddWithNullRegexMatchThrowsArgumentNullException() { var collection = new TemplateParameterCollection(); UnitTestHelper.AssertThrowsArgumentNullException(() => collection.Add((Match)null)); } [Test] public void CanClearCollection() { var collection = new TemplateParameterCollection {new TemplateParameter("name", "string", "0")}; Assert.AreEqual(1, collection.Count); collection.Clear(); Assert.AreEqual(0, collection.Count); } [Test] public void CopyToEmptyArrayLeavesNotEmptyArray() { var collection = new TemplateParameterCollection {new TemplateParameter("test", "string", "")}; var parameters = new TemplateParameter[1]; collection.CopyTo(parameters, 0); Assert.AreEqual("test", parameters[0].Name); } [Test] public void IndexOfFindsTemplate() { var collection = new TemplateParameterCollection(); var param = new TemplateParameter("test", "string", ""); collection.Add(param); Assert.AreEqual(0, collection.IndexOf(param)); } [Test] public void IsReadOnlyReturnsFalse() { var collection = new TemplateParameterCollection(); Assert.IsFalse(collection.IsReadOnly); } [Test] public void RemoveRemovesTemplate() { var collection = new TemplateParameterCollection(); var param = new TemplateParameter("test", "string", ""); collection.Add(param); Assert.AreEqual(1, collection.Count); collection.Remove(param); Assert.AreEqual(0, collection.Count); } [Test] public void TemplateParameterCollectionDoesNotStoreDuplicateParameters() { var collection = new TemplateParameterCollection {new TemplateParameter("MyTest", "int", 0.ToString())}; Assert.AreEqual(1, collection.Count, "Our one parameter is in there."); collection.Add(new TemplateParameter("MyTest", "nvarchar(32)", "Blah")); Assert.AreEqual(1, collection.Count, "Should only be one parameter still."); } [Test] public void ScriptDoesNotStoreDuplicateParameters() { string scriptText = "SELECT TOP <name, int, 0> * FROM Somewhere" + Environment.NewLine + "GO" + Environment.NewLine + "SELECT TOP <name, int, 1> * FROM SomewhereElse"; ScriptCollection scripts = Script.ParseScripts(scriptText); Assert.AreEqual(2, scripts.Count, "Did not parse the script."); Assert.AreEqual(1, scripts.TemplateParameters.Count, "did not merge or parse the template params."); } /// <summary> /// Tests the contains method. /// </summary> [Test] public void ContainsReturnsCorrectParameter() { var collection = new TemplateParameterCollection(); Assert.IsFalse(collection.Contains("test"), "An empty collection should not contain a parameter."); var parameter = new TemplateParameter("test", "type", "something"); Assert.IsFalse(collection.Contains(parameter), "An empty collection should not contain a parameter."); collection.Add(parameter); Assert.IsTrue(collection.Contains(parameter)); Assert.IsTrue(collection.Contains("test")); var differentParameter = new TemplateParameter("differentName", "", ""); Assert.IsFalse(collection.Contains(differentParameter), "Contains should not be a \"yes\" method."); Assert.IsFalse(collection.Contains(differentParameter.Name), "Contains should not be a \"yes\" method."); var newParameterWithSameName = new TemplateParameter("test", "type", "something"); Assert.IsTrue(collection.Contains(newParameterWithSameName), "Even though this is a separate instance, we match parameters by name. So we should already contain this one."); } /// <summary> /// Tests parsing simple scripts with template parameters. /// </summary> /// <param name="scriptText">The script.</param> /// <param name="name">The name.</param> /// <param name="dataType">Type of the data.</param> /// <param name="defaultValue">The default value.</param> [RowTest] [Row("<name,varchar(100),'default'>", "name", "varchar(100)", "'default'")] [Row("XYZ <name,varchar(100),'default'> ABC", "name", "varchar(100)", "'default'")] [Row("<name , varchar(100) , 'default' >", "name ", "varchar(100) ", "'default' ")] [Row("<name, int,10>", "name", "int", "10")] [Row("<name, int,>", "name", "int", "")] [Row("<name, int, 10>", "name", "int", "10")] public void TestParseSimpleScripts(string scriptText, string name, string dataType, string defaultValue) { var script = new Script(scriptText); TemplateParameterCollection parameters = script.TemplateParameters; Assert.AreEqual(1, parameters.Count, "Expected one parameter."); TemplateParameter parameter = parameters[0]; Assert.AreEqual(name, parameter.Name, "Parameter name was not parsed correctly."); Assert.AreEqual(dataType, parameter.DataType, "Data Type was not parsed correctly."); Assert.AreEqual(defaultValue, parameter.Value, "DefaultValue was not parsed correctly."); } /// <summary> /// Tests parsing simple scripts with template parameters. /// </summary> /// <param name="scriptText">The script.</param> /// <param name="replaceValue"></param> /// <param name="expectedResult"></param> [RowTest] [Row("<name,varchar(100),'default'>", "'MyValue'", "'MyValue'")] [Row("<name , varchar(100) , default >", "default", "default")] [Row("ABC <name , varchar(100) , default > XYZ", "default", "ABC default XYZ")] [Row("<name, int,10>", "15", "15")] [Row("ABC<name, int,10>XYZ", "15", "ABC15XYZ")] [Row("<name, int,>", "", "")] public void TestReplaceSimpleScripts(string scriptText, string replaceValue, string expectedResult) { var script = new Script(scriptText); script.TemplateParameters[0].Value = replaceValue; Assert.AreEqual(expectedResult, script.ScriptText, "Expected a replacement to occur."); } /// <summary> /// Tests parsing simple scripts with template parameters that have default values. /// </summary> /// <param name="scriptText">The script.</param> /// <param name="expectedResult"></param> [RowTest] [Row("<name,varchar(100),'default'>", "'default'")] [Row("<name , varchar(100) , default >", "default ")] [Row("ABC <name , varchar(100) , default > XYZ", "ABC default XYZ")] [Row("<name, int,10>", "10")] [Row("ABC<name, int,10>XYZ", "ABC10XYZ")] [Row("<name, int,>", "")] [Row("AND DateAdded < DateAdd(day, 1, @StopDate) AND PostConfig & 1 <> CASE ", "AND DateAdded < DateAdd(day, 1, @StopDate) AND PostConfig & 1 <> CASE ")] public void TestReplaceSimpleScriptsWithDefaults(string scriptText, string expectedResult) { var script = new Script(scriptText); Assert.AreEqual(expectedResult, script.ScriptText, "Expected a replacement to occur."); } /// <summary> /// Tests the more complex script. /// </summary> /// <remarks> /// The script itself is non-sensical, but that's not the point. /// </remarks> [Test] public void TestMoreComplexScript() { string scriptText = "<name,varchar,default>SELECT * FROM <name,varchar,default> WHERE " + Environment.NewLine + "<name,varchar,default> = <name2,int,10> and <name3,decimal,>"; var script = new Script(scriptText); script.TemplateParameters.SetValue("name", "subtext_Config"); script.TemplateParameters.SetValue("name3", "'32'"); string expected = "subtext_ConfigSELECT * FROM subtext_Config WHERE " + Environment.NewLine + "subtext_Config = 10 and '32'"; Assert.AreEqual(expected, script.ScriptText, "The template replacements failed"); } /// <summary> /// Tests expanding a templated collection of scripts without changing any defaults. /// </summary> [Test] public void TestScriptCollectionsDefaultExpansion() { Stream stream = UnitTestHelper.UnpackEmbeddedResource("Scripting.TestTemplateSqlScript.txt"); var scriptRunner = new SqlScriptRunner(stream, Encoding.UTF8); Assert.AreEqual(5, scriptRunner.TemplateParameters.Count, "Not the expected number of template parameters. Make sure it merges correctly."); string expectedDefault = UnitTestHelper.UnpackEmbeddedResource("Scripting.TestTemplateSqlScriptExpectedDefault.txt", Encoding.UTF8); Assert.AreEqual(expectedDefault, scriptRunner.ScriptCollection.ExpandedScriptText); } /// <summary> /// Tests expanding a templated collection of scripts with changes to the defaults. /// </summary> [Test] public void TestScriptCollectionsExpansionWithChanges() { Stream stream = UnitTestHelper.UnpackEmbeddedResource("Scripting.TestTemplateSqlScript.txt"); var scriptRunner = new SqlScriptRunner(stream, Encoding.UTF8); Assert.AreEqual(5, scriptRunner.TemplateParameters.Count, "Not the expected number of template parameters. Make sure it merges correctly."); string expectedDefault = UnitTestHelper.UnpackEmbeddedResource("Scripting.TestTemplateSqlScriptExpectedChanges.txt", Encoding.UTF8); scriptRunner.TemplateParameters["subtext_db_name"].Value = "SubtextDB"; scriptRunner.TemplateParameters["dottext_db_name"].Value = "dbDotText"; scriptRunner.TemplateParameters["dotTextDbUser"].Value = "haacked"; scriptRunner.TemplateParameters["someOtherTemplate"].Value = "NotABlogId"; string expected = expectedDefault.Trim(); string result = scriptRunner.ScriptCollection.ExpandedScriptText.Trim(); expected = expected.Replace("" + (char)13, ""); //Ugly hack! I know. I'll Explain later. result = result.Replace("" + ((char)13), ""); //Ugly hack! I know. I'll Explain later. UnitTestHelper.AssertStringsEqualCharacterByCharacter(expected, result); } } }
using System; using System.Linq; using System.Text; using System.Collections.Generic; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using global::Xamarin.Auth; [assembly: UsesPermission(Android.Manifest.Permission.Internet)] namespace Xamarin.Auth.Sample.XamarinAndroid { [Activity ( Label = "Xamarin.Auth.Sample.XamarinAndroid", MainLauncher = true, Icon = "@drawable/icon" ) ] public class MainActivity : ListActivity { //================================================================= // Xamarin.Auth API test switch // true - Native UI // Android - [Chrome] Custom Tabs // iOS - Safari View Controller // false - embedded WebViews // Android - WebView // iOS - UIWebView or WKWebView bool test_native_ui = true; //================================================================= protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); //================================================================= // switching between // embbedded browsers (WebView) // and // Native UI ([Chrome] Custom Tabs) // read the docs about pros and cons test_native_ui = true; //================================================================= ListAdapter = new ArrayAdapter<String>(this, global::Android.Resource.Layout.SimpleListItem1, provider_list); InitializeNativeUICustomTabs(); return; } string[] provider_list = ProviderSamples.Data.TestCases.Keys.ToArray(); string provider = null; protected override void OnListItemClick(ListView l, View v, int position, long id) { provider = provider_list[position]; Xamarin.Auth.ProviderSamples.Helpers.OAuth auth; if (!ProviderSamples.Data.TestCases.TryGetValue(provider, out auth)) { Toast.MakeText(this, "Unknown OAuth Provider!", ToastLength.Long); } if (auth is Xamarin.Auth.ProviderSamples.Helpers.OAuth1) { Authenticate(auth as Xamarin.Auth.ProviderSamples.Helpers.OAuth1); } else { Authenticate(auth as Xamarin.Auth.ProviderSamples.Helpers.OAuth2); } return; } global::Android.Support.CustomTabs.Chromium.SharedUtilities.CustomTabActivityHelper custom_tab_activity_helper = null; protected override void OnStart() { base.OnStart(); // Step 2.2 Customizing the UI - Native UI [OPTIONAL] // [Chrome] Custom Tabs WarmUp and prefetch custom_tab_activity_helper.BindCustomTabsService(this); return; } protected override void OnStop() { base.OnStop(); // Step 2.2 Customizing the UI - Native UI [OPTIONAL] // [Chrome] Custom Tabs WarmUp and prefetch custom_tab_activity_helper.UnbindCustomTabsService(this); return; } protected void InitializeNativeUICustomTabs() { // Step 2.2 Customizing the UI - Native UI [OPTIONAL] // [Chrome] Custom Tabs WarmUp and prefetch custom_tab_activity_helper = new global::Android.Support.CustomTabs.Chromium.SharedUtilities.CustomTabActivityHelper(); //----------------------------------------------------------------------------------------------- // Xamarin.Auth initialization // User-Agent tweaks for Embedded WebViews (UIWebView and WKWebView) global::Xamarin.Auth.WebViewConfiguration.Android.UserAgent = "moljac++"; //................................................................ // Xamarin.Auth CustomTabs Initialization/Customisation // Note this API is still under development and subject to changes! // CustomTabs closing Toast message (null to turn it of, otherwise define it here) global::Xamarin.Auth.CustomTabsConfiguration.CustomTabsClosingMessage = null; //global::Xamarin.Auth.CustomTabsConfiguration.CustomTabsClosingMessage = "Closing? Let us know"; global::Xamarin.Auth.CustomTabsConfiguration.ActionLabel = null; global::Xamarin.Auth.CustomTabsConfiguration.MenuItemTitle = null; global::Xamarin.Auth.CustomTabsConfiguration.AreAnimationsUsed = true; global::Xamarin.Auth.CustomTabsConfiguration.IsShowTitleUsed = false; global::Xamarin.Auth.CustomTabsConfiguration.IsUrlBarHidingUsed = false; global::Xamarin.Auth.CustomTabsConfiguration.IsCloseButtonIconUsed = false; global::Xamarin.Auth.CustomTabsConfiguration.IsActionButtonUsed = false; global::Xamarin.Auth.CustomTabsConfiguration.IsActionBarToolbarIconUsed = false; global::Xamarin.Auth.CustomTabsConfiguration.IsDefaultShareMenuItemUsed = false; global::Android.Graphics.Color color_xamarin_blue; color_xamarin_blue = new global::Android.Graphics.Color(0x34, 0x98, 0xdb); global::Xamarin.Auth.CustomTabsConfiguration.ToolbarColor = color_xamarin_blue; //................................................................ // ActivityFlags for tweaking closing of CustomTabs // please report findings! global::Xamarin.Auth.CustomTabsConfiguration. ActivityFlags = global::Android.Content.ActivityFlags.NoHistory | global::Android.Content.ActivityFlags.SingleTop | global::Android.Content.ActivityFlags.NewTask ; global::Xamarin.Auth.CustomTabsConfiguration.IsWarmUpUsed = true; global::Xamarin.Auth.CustomTabsConfiguration.IsPrefetchUsed = true; //----------------------------------------------------------------------------------------------- return; } public static OAuth1Authenticator Auth1 = null; private void Authenticate(Xamarin.Auth.ProviderSamples.Helpers.OAuth1 oauth1) { // Step 1.1 Creating and configuring an Authenticator Auth1 = new OAuth1Authenticator ( consumerKey: oauth1.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer, consumerSecret: oauth1.OAuth1_SecretKey_ConsumerSecret_APISecret, requestTokenUrl: oauth1.OAuth1_UriRequestToken, authorizeUrl: oauth1.OAuth_UriAuthorization, accessTokenUrl: oauth1.OAuth_UriAccessToken_UriRequestToken, callbackUrl: oauth1.OAuth_UriCallbackAKARedirect, // Native UI API switch // true - NEW native UI support // false - OLD embedded browser API [DEFAULT] // DEFAULT will be switched to true in the near future 2017-04 isUsingNativeUI: test_native_ui ) { AllowCancel = oauth1.AllowCancel, }; // Step 1.2 Subscribing to Authenticator events // If authorization succeeds or is canceled, .Completed will be fired. Auth1.Completed += Auth_Completed; Auth1.Error += Auth_Error; Auth1.BrowsingCompleted += Auth_BrowsingCompleted; // Step 2.1 Creating Login UI global::Android.Content.Intent ui_object = Auth1.GetUI(this); if (Auth2.IsUsingNativeUI == true) { // Step 2.2 Customizing the UI - Native UI [OPTIONAL] // In order to access CustomTabs API InitializeNativeUICustomTabs(); } // Step 3 Present/Launch the Login UI StartActivity(ui_object); return; } public static OAuth2Authenticator Auth2 = null; private void Authenticate(Xamarin.Auth.ProviderSamples.Helpers.OAuth2 oauth2) { if (string.IsNullOrEmpty(oauth2.OAuth_SecretKey_ConsumerSecret_APISecret)) { if (oauth2.OAuth_UriAccessToken_UriRequestToken == null) { // Step 1.1 Creating and configuring an Authenticator Auth2 = new OAuth2Authenticator ( clientId: oauth2.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer, scope: oauth2.OAuth2_Scope, authorizeUrl: oauth2.OAuth_UriAuthorization, redirectUrl: oauth2.OAuth_UriCallbackAKARedirect, // Native UI API switch // true - NEW native UI support // false - OLD embedded browser API [DEFAULT] // DEFAULT will be switched to true in the near future 2017-04 isUsingNativeUI: test_native_ui ) { ShowErrors = false, AllowCancel = oauth2.AllowCancel, }; } else //if (oauth2.OAuth_UriAccessToken_UriRequestToken != null) { // Step 1.1 Creating and configuring an Authenticator Auth2 = new OAuth2Authenticator ( clientId: oauth2.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer, clientSecret: oauth2.OAuth_SecretKey_ConsumerSecret_APISecret, scope: oauth2.OAuth2_Scope, authorizeUrl: oauth2.OAuth_UriAuthorization, redirectUrl: oauth2.OAuth_UriCallbackAKARedirect, accessTokenUrl: oauth2.OAuth_UriAccessToken_UriRequestToken, // Native UI API switch // true - NEW native UI support // false - OLD embedded browser API [DEFAULT] // DEFAULT will be switched to true in the near future 2017-04 isUsingNativeUI: test_native_ui ) { ShowErrors = false, AllowCancel = oauth2.AllowCancel, }; } } else { // Step 1.1 Creating and configuring an Authenticator Auth2 = new OAuth2Authenticator ( clientId: oauth2.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer, clientSecret: oauth2.OAuth_SecretKey_ConsumerSecret_APISecret, scope: oauth2.OAuth2_Scope, authorizeUrl: oauth2.OAuth_UriAuthorization, redirectUrl: oauth2.OAuth_UriCallbackAKARedirect, accessTokenUrl: oauth2.OAuth_UriAccessToken_UriRequestToken, // Native UI API switch // true - NEW native UI support // false - OLD embedded browser API [DEFAULT] // DEFAULT will be switched to true in the near future 2017-04 isUsingNativeUI: test_native_ui ) { ShowErrors = false, AllowCancel = oauth2.AllowCancel, }; } // Step 1.2 Subscribing to Authenticator events // If authorization succeeds or is canceled, .Completed will be fired. Auth2.Completed += Auth_Completed; Auth2.Error += Auth_Error; Auth2.BrowsingCompleted += Auth_BrowsingCompleted; // Step 2.1 Creating Login UI global::Android.Content.Intent ui_object = Auth2.GetUI(this); if (Auth2.IsUsingNativeUI == true) { InitializeNativeUICustomTabs(); } // Step 3 Present/Launch the Login UI StartActivity(ui_object); return; } private void Auth_Error(object sender, AuthenticatorErrorEventArgs ee) { string title = "OAuth Error"; string msg = ""; StringBuilder sb = new StringBuilder(); sb.Append("Message = ").Append(ee.Message) .Append(System.Environment.NewLine); msg = sb.ToString(); Toast.MakeText ( this, "Message = " + msg, ToastLength.Long ).Show(); return; } private void Auth_BrowsingCompleted(object sender, EventArgs ee) { string title = "OAuth Browsing Completed"; string msg = ""; StringBuilder sb = new StringBuilder(); msg = sb.ToString(); Toast.MakeText ( this, "Message = " + msg, ToastLength.Long ).Show(); return; } public void Auth_Completed(object sender, AuthenticatorCompletedEventArgs ee) { var builder = new AlertDialog.Builder(this); if (!ee.IsAuthenticated) { builder.SetMessage("Not Authenticated"); } else { AccountStoreTests(sender, ee); AccountStoreTestsAsync(sender, ee); try { //------------------------------------------------------------------ Account account = ee.Account; string token = default(string); if (null != account) { string token_name = default(string); Type t = sender.GetType(); if (t == typeof(Xamarin.Auth.OAuth2Authenticator)) { token_name = "access_token"; token = account.Properties[token_name].ToString(); } else if (t == typeof(Xamarin.Auth.OAuth1Authenticator)) { token_name = "oauth_token"; token = account.Properties[token_name].ToString(); } } //------------------------------------------------------------------ StringBuilder sb = new StringBuilder(); sb.Append("IsAuthenticated = ").Append(ee.IsAuthenticated) .Append(System.Environment.NewLine); sb.Append("Account.UserName = ").Append(ee.Account.Username) .Append(System.Environment.NewLine); sb.Append("token = ").Append(token) .Append(System.Environment.NewLine); builder.SetTitle("AuthenticationResults"); builder.SetMessage(sb.ToString()); } catch (global::Android.OS.OperationCanceledException) { builder.SetTitle("Task Canceled"); } catch (Exception ex) { builder.SetTitle("Error"); builder.SetMessage(ex.ToString()); } } //ee.Account builder.SetPositiveButton("Ok", (o, e) => { }); builder.Create().Show(); return; } private void AccountStoreTests(object authenticator, AuthenticatorCompletedEventArgs ee) { // Step 4.2 Store the account AccountStore account_store = AccountStore.Create(this); account_store.Save(ee.Account, provider); //------------------------------------------------------------------ // Android // https://kb.xamarin.com/agent/case/225411 // cannot reproduce // Step 4.3 Retrieve stored accounts Account account1 = account_store.FindAccountsForService(provider).FirstOrDefault(); if (null != account1) { //------------------------------------------------------------------ string token = default(string); if (null != account1) { string token_name = default(string); Type t = authenticator.GetType(); if (t == typeof(Xamarin.Auth.OAuth2Authenticator)) { token_name = "access_token"; token = account1.Properties[token_name].ToString(); } else if (t == typeof(Xamarin.Auth.OAuth1Authenticator)) { token_name = "oauth_token"; token = account1.Properties[token_name].ToString(); } } //------------------------------------------------------------------ Toast.MakeText ( this, "access_token = " + token, ToastLength.Long ).Show(); } //------------------------------------------------------------------ AccountStore.Create(this).Save(ee.Account, provider + ".v.2"); //------------------------------------------------------------------ // throws on iOS // Account account2 = AccountStore.Create(this).FindAccountsForService(provider + ".v.2").FirstOrDefault(); if (null != account2) { //------------------------------------------------------------------ string token = default(string); if (null != account2) { string token_name = default(string); Type t = authenticator.GetType(); if (t == typeof(Xamarin.Auth.OAuth2Authenticator)) { token_name = "access_token"; token = account2.Properties[token_name].ToString(); } else if (t == typeof(Xamarin.Auth.OAuth1Authenticator)) { token_name = "oauth_token"; token = account2.Properties[token_name].ToString(); } } //------------------------------------------------------------------ Toast.MakeText ( this, "access_token = " + token, ToastLength.Long ).Show(); } //------------------------------------------------------------------ return; } private async void AccountStoreTestsAsync(object authenticator, AuthenticatorCompletedEventArgs ee) { AccountStore account_store = AccountStore.Create(this); await account_store.SaveAsync(ee.Account, provider); //------------------------------------------------------------------ // Android // https://kb.xamarin.com/agent/case/225411 // cannot reproduce Account account1 = (await account_store.FindAccountsForServiceAsync(provider)).FirstOrDefault(); if (null != account1) { //------------------------------------------------------------------ string token = default(string); if (null != account1) { string token_name = default(string); Type t = authenticator.GetType(); if (t == typeof(Xamarin.Auth.OAuth2Authenticator)) { token_name = "access_token"; token = account1.Properties[token_name].ToString(); } else if (t == typeof(Xamarin.Auth.OAuth1Authenticator)) { token_name = "oauth_token"; token = account1.Properties[token_name].ToString(); } } //------------------------------------------------------------------ Toast.MakeText ( this, "access_token = " + token, ToastLength.Long ).Show(); } //------------------------------------------------------------------ AccountStore.Create(this).Save(ee.Account, provider + ".v.2"); //------------------------------------------------------------------ // throws on iOS // IEnumerable<Account> accounts = await (AccountStore.Create(this).FindAccountsForServiceAsync(provider + ".v.2")); Account account2 = accounts.FirstOrDefault(); if (null != account2) { //------------------------------------------------------------------ string token = default(string); if (null != account2) { string token_name = default(string); Type t = authenticator.GetType(); if (t == typeof(Xamarin.Auth.OAuth2Authenticator)) { token_name = "access_token"; token = account2.Properties[token_name].ToString(); } else if (t == typeof(Xamarin.Auth.OAuth1Authenticator)) { token_name = "oauth_token"; token = account2.Properties[token_name].ToString(); } } //------------------------------------------------------------------ Toast.MakeText ( this, "access_token = " + token, ToastLength.Long ).Show(); } //------------------------------------------------------------------ return; } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Linq; using Csla; using Csla.Data; using Invoices.DataAccess; namespace Invoices.Business { /// <summary> /// SupplierList (read only list).<br/> /// This is a generated base class of <see cref="SupplierList"/> business object. /// This class is a root collection. /// </summary> /// <remarks> /// The items of the collection are <see cref="SupplierInfo"/> objects. /// </remarks> [Serializable] #if WINFORMS public partial class SupplierList : ReadOnlyBindingListBase<SupplierList, SupplierInfo> #else public partial class SupplierList : ReadOnlyListBase<SupplierList, SupplierInfo> #endif { #region Event handler properties [NotUndoable] private static bool _singleInstanceSavedHandler = true; /// <summary> /// Gets or sets a value indicating whether only a single instance should handle the Saved event. /// </summary> /// <value> /// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>. /// </value> public static bool SingleInstanceSavedHandler { get { return _singleInstanceSavedHandler; } set { _singleInstanceSavedHandler = value; } } #endregion #region Collection Business Methods /// <summary> /// Determines whether a <see cref="SupplierInfo"/> item is in the collection. /// </summary> /// <param name="supplierId">The SupplierId of the item to search for.</param> /// <returns><c>true</c> if the SupplierInfo is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int supplierId) { foreach (var supplierInfo in this) { if (supplierInfo.SupplierId == supplierId) { return true; } } return false; } #endregion #region Private Fields private static SupplierList _list; #endregion #region Cache Management Methods /// <summary> /// Clears the in-memory SupplierList cache so it is reloaded on the next request. /// </summary> public static void InvalidateCache() { _list = null; } /// <summary> /// Used by async loaders to load the cache. /// </summary> /// <param name="list">The list to cache.</param> internal static void SetCache(SupplierList list) { _list = list; } internal static bool IsCached { get { return _list != null; } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="SupplierList"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="SupplierList"/> collection.</returns> public static SupplierList GetSupplierList() { if (_list == null) _list = DataPortal.Fetch<SupplierList>(); return _list; } /// <summary> /// Factory method. Loads a <see cref="SupplierList"/> collection, based on given parameters. /// </summary> /// <param name="name">The Name parameter of the SupplierList to fetch.</param> /// <returns>A reference to the fetched <see cref="SupplierList"/> collection.</returns> public static SupplierList GetSupplierList(string name) { return DataPortal.Fetch<SupplierList>(name); } /// <summary> /// Factory method. Asynchronously loads a <see cref="SupplierList"/> collection. /// </summary> /// <param name="callback">The completion callback method.</param> public static void GetSupplierList(EventHandler<DataPortalResult<SupplierList>> callback) { if (_list == null) DataPortal.BeginFetch<SupplierList>((o, e) => { _list = e.Object; callback(o, e); }); else callback(null, new DataPortalResult<SupplierList>(_list, null, null)); } /// <summary> /// Factory method. Asynchronously loads a <see cref="SupplierList"/> collection, based on given parameters. /// </summary> /// <param name="name">The Name parameter of the SupplierList to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetSupplierList(string name, EventHandler<DataPortalResult<SupplierList>> callback) { DataPortal.BeginFetch<SupplierList>(name, callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="SupplierList"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public SupplierList() { // Use factory methods and do not use direct creation. SupplierEditSaved.Register(this); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = false; AllowEdit = false; AllowRemove = false; RaiseListChangedEvents = rlce; } #endregion #region Saved Event Handler /// <summary> /// Handle Saved events of <see cref="SupplierEdit"/> to update the list of <see cref="SupplierInfo"/> objects. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> internal void SupplierEditSavedHandler(object sender, Csla.Core.SavedEventArgs e) { var obj = (SupplierEdit)e.NewObject; if (((SupplierEdit)sender).IsNew) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; Add(SupplierInfo.LoadInfo(obj)); RaiseListChangedEvents = rlce; IsReadOnly = true; } else if (((SupplierEdit)sender).IsDeleted) { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.SupplierId == obj.SupplierId) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; this.RemoveItem(index); RaiseListChangedEvents = rlce; IsReadOnly = true; break; } } } else { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.SupplierId == obj.SupplierId) { child.UpdatePropertiesOnSaved(obj); #if !WINFORMS var notifyCollectionChangedEventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index); OnCollectionChanged(notifyCollectionChangedEventArgs); #else var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index); OnListChanged(listChangedEventArgs); #endif break; } } } } #endregion #region Data Access /// <summary> /// Loads a <see cref="SupplierList"/> collection from the database or from the cache. /// </summary> protected void DataPortal_Fetch() { if (IsCached) { LoadCachedList(); return; } var args = new DataPortalHookArgs(); OnFetchPre(args); using (var dalManager = DalFactoryInvoices.GetManager()) { var dal = dalManager.GetProvider<ISupplierListDal>(); var data = dal.Fetch(); LoadCollection(data); } OnFetchPost(args); _list = this; } private void LoadCachedList() { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AddRange(_list); RaiseListChangedEvents = rlce; IsReadOnly = true; } /// <summary> /// Loads a <see cref="SupplierList"/> collection from the database, based on given criteria. /// </summary> /// <param name="name">The Name.</param> protected void DataPortal_Fetch(string name) { var args = new DataPortalHookArgs(name); OnFetchPre(args); using (var dalManager = DalFactoryInvoices.GetManager()) { var dal = dalManager.GetProvider<ISupplierListDal>(); var data = dal.Fetch(name); LoadCollection(data); } OnFetchPost(args); } private void LoadCollection(IDataReader data) { using (var dr = new SafeDataReader(data)) { Fetch(dr); } } /// <summary> /// Loads all <see cref="SupplierList"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(DataPortal.FetchChild<SupplierInfo>(dr)); } RaiseListChangedEvents = rlce; IsReadOnly = true; } #endregion #region DataPortal Hooks /// <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); #endregion #region SupplierEditSaved nested class // TODO: edit "SupplierList.cs", uncomment the "OnDeserialized" method and add the following line: // TODO: SupplierEditSaved.Register(this); /// <summary> /// Nested class to manage the Saved events of <see cref="SupplierEdit"/> /// to update the list of <see cref="SupplierInfo"/> objects. /// </summary> private static class SupplierEditSaved { private static List<WeakReference> _references; private static bool Found(object obj) { return _references.Any(reference => Equals(reference.Target, obj)); } /// <summary> /// Registers a SupplierList instance to handle Saved events. /// to update the list of <see cref="SupplierInfo"/> objects. /// </summary> /// <param name="obj">The SupplierList instance.</param> public static void Register(SupplierList obj) { var mustRegister = _references == null; if (mustRegister) _references = new List<WeakReference>(); if (SupplierList.SingleInstanceSavedHandler) _references.Clear(); if (!Found(obj)) _references.Add(new WeakReference(obj)); if (mustRegister) SupplierEdit.SupplierEditSaved += SupplierEditSavedHandler; } /// <summary> /// Handles Saved events of <see cref="SupplierEdit"/>. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> public static void SupplierEditSavedHandler(object sender, Csla.Core.SavedEventArgs e) { foreach (var reference in _references) { if (reference.IsAlive) ((SupplierList) reference.Target).SupplierEditSavedHandler(sender, e); } } /// <summary> /// Removes event handling and clears all registered SupplierList instances. /// </summary> public static void Unregister() { SupplierEdit.SupplierEditSaved -= SupplierEditSavedHandler; _references = null; } } #endregion } }
using System; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Linq; using System.Runtime.CompilerServices; using Umbraco.Core.Events; using umbraco.DataLayer; using umbraco.cms.businesslogic; using System.Collections.Generic; using DeleteEventArgs = umbraco.cms.businesslogic.DeleteEventArgs; namespace umbraco.BusinessLogic { /// <summary> /// Summary description for Permission. /// </summary> public class Permission { public int NodeId { get; private set; } public int UserId { get; private set; } public char PermissionId { get; private set; } /// <summary> /// Private constructor, this class cannot be directly instantiated /// </summary> private Permission() { } private static ISqlHelper SqlHelper { get { return Application.SqlHelper; } } public static void MakeNew(User User, CMSNode Node, char PermissionKey) { MakeNew(User, Node, PermissionKey, true); } [MethodImpl(MethodImplOptions.Synchronized)] internal static void MakeNew(User user, IEnumerable<CMSNode> nodes, char permissionKey, bool raiseEvents) { var asArray = nodes.ToArray(); foreach (var node in asArray) { var parameters = new[] { SqlHelper.CreateParameter("@userId", user.Id), SqlHelper.CreateParameter("@nodeId", node.Id), SqlHelper.CreateParameter("@permission", permissionKey.ToString()) }; // Method is synchronized so exists remains consistent (avoiding race condition) var exists = SqlHelper.ExecuteScalar<int>( "SELECT COUNT(userId) FROM umbracoUser2nodePermission WHERE userId = @userId AND nodeId = @nodeId AND permission = @permission", parameters) > 0; if (exists) return; SqlHelper.ExecuteNonQuery( "INSERT INTO umbracoUser2nodePermission (userId, nodeId, permission) VALUES (@userId, @nodeId, @permission)", parameters); } if (raiseEvents) { OnNew(new UserPermission(user, asArray, new[] { permissionKey }), new NewEventArgs()); } } private static void MakeNew(User User, CMSNode Node, char PermissionKey, bool raiseEvents) { MakeNew(User, new[] {Node}, PermissionKey, raiseEvents); } /// <summary> /// Returns the permissions for a user /// </summary> /// <param name="user"></param> /// <returns></returns> public static IEnumerable<Permission> GetUserPermissions(User user) { var items = new List<Permission>(); using (IRecordsReader dr = SqlHelper.ExecuteReader("select * from umbracoUser2NodePermission where userId = @userId order by nodeId", SqlHelper.CreateParameter("@userId", user.Id))) { while (dr.Read()) { items.Add(new Permission() { NodeId = dr.GetInt("nodeId"), PermissionId = Convert.ToChar(dr.GetString("permission")), UserId = dr.GetInt("userId") }); } } return items; } /// <summary> /// Returns the permissions for a node /// </summary> /// <param name="node"></param> /// <returns></returns> public static IEnumerable<Permission> GetNodePermissions(CMSNode node) { var items = new List<Permission>(); using (IRecordsReader dr = SqlHelper.ExecuteReader("select * from umbracoUser2NodePermission where nodeId = @nodeId order by nodeId", SqlHelper.CreateParameter("@nodeId", node.Id))) { while (dr.Read()) { items.Add(new Permission() { NodeId = dr.GetInt("nodeId"), PermissionId = Convert.ToChar(dr.GetString("permission")), UserId = dr.GetInt("userId") }); } } return items; } /// <summary> /// Delets all permissions for the node/user combination /// </summary> /// <param name="user"></param> /// <param name="node"></param> public static void DeletePermissions(User user, CMSNode node) { DeletePermissions(user, node, true); } internal static void DeletePermissions(User user, CMSNode node, bool raiseEvents) { // delete all settings on the node for this user SqlHelper.ExecuteNonQuery("delete from umbracoUser2NodePermission where userId = @userId and nodeId = @nodeId", SqlHelper.CreateParameter("@userId", user.Id), SqlHelper.CreateParameter("@nodeId", node.Id)); if (raiseEvents) { OnDeleted(new UserPermission(user, node, null), new DeleteEventArgs()); } } /// <summary> /// deletes all permissions for the user /// </summary> /// <param name="user"></param> public static void DeletePermissions(User user) { // delete all settings on the node for this user SqlHelper.ExecuteNonQuery("delete from umbracoUser2NodePermission where userId = @userId", SqlHelper.CreateParameter("@userId", user.Id)); OnDeleted(new UserPermission(user, Enumerable.Empty<CMSNode>(), null), new DeleteEventArgs()); } public static void DeletePermissions(int iUserID, int[] iNodeIDs) { var sql = "DELETE FROM umbracoUser2NodePermission WHERE nodeID IN ({0}) AND userID=@userID"; var nodeIDs = string.Join(",", Array.ConvertAll(iNodeIDs, Converter)); sql = string.Format(sql, nodeIDs); SqlHelper.ExecuteNonQuery(sql, new[] { SqlHelper.CreateParameter("@userID", iUserID) }); OnDeleted(new UserPermission(iUserID, iNodeIDs), new DeleteEventArgs()); } public static void DeletePermissions(int iUserID, int iNodeID) { DeletePermissions(iUserID, new[] { iNodeID }); } private static string Converter(int from) { return from.ToString(); } /// <summary> /// delete all permissions for this node /// </summary> /// <param name="node"></param> public static void DeletePermissions(CMSNode node) { SqlHelper.ExecuteNonQuery( "delete from umbracoUser2NodePermission where nodeId = @nodeId", SqlHelper.CreateParameter("@nodeId", node.Id)); OnDeleted(new UserPermission(null, node, null), new DeleteEventArgs()); } [MethodImpl(MethodImplOptions.Synchronized)] public static void UpdateCruds(User user, CMSNode node, string permissions) { // delete all settings on the node for this user //false = do not raise events DeletePermissions(user, node, false); // Loop through the permissions and create them foreach (char c in permissions) { //false = don't raise events since we'll raise a custom event after MakeNew(user, node, c, false); } OnUpdated(new UserPermission(user, node, permissions.ToCharArray()), new SaveEventArgs()); } internal static event TypedEventHandler<UserPermission, DeleteEventArgs> Deleted; private static void OnDeleted(UserPermission permission, DeleteEventArgs args) { if (Deleted != null) { Deleted(permission, args); } } internal static event TypedEventHandler<UserPermission, SaveEventArgs> Updated; private static void OnUpdated(UserPermission permission, SaveEventArgs args) { if (Updated != null) { Updated(permission, args); } } internal static event TypedEventHandler<UserPermission, NewEventArgs> New; private static void OnNew(UserPermission permission, NewEventArgs args) { if (New != null) { New(permission, args); } } } internal class UserPermission { private int? _userId; private readonly int[] _nodeIds; internal UserPermission(int userId) { _userId = userId; } internal UserPermission(int userId, IEnumerable<int> nodeIds) { _userId = userId; _nodeIds = nodeIds.ToArray(); } internal UserPermission(User user, CMSNode node, char[] permissionKeys) { User = user; Nodes = new[] { node }; PermissionKeys = permissionKeys; } internal UserPermission(User user, IEnumerable<CMSNode> nodes, char[] permissionKeys) { User = user; Nodes = nodes; PermissionKeys = permissionKeys; } internal int UserId { get { if (_userId.HasValue) { return _userId.Value; } if (User != null) { return User.Id; } return -1; } } internal IEnumerable<int> NodeIds { get { if (_nodeIds != null) { return _nodeIds; } if (Nodes != null) { return Nodes.Select(x => x.Id); } return Enumerable.Empty<int>(); } } internal User User { get; private set; } internal IEnumerable<CMSNode> Nodes { get; private set; } internal char[] PermissionKeys { get; private set; } } }
countriesList.Add(new Country { label = "AD", description = "Andorra" }); countriesList.Add(new Country { label = "AE", description = "United Arab Emirates" }); countriesList.Add(new Country { label = "AF", description = "Afghanistan" }); countriesList.Add(new Country { label = "AG", description = "Antigua & Barbuda" }); countriesList.Add(new Country { label = "AI", description = "Anguilla" }); countriesList.Add(new Country { label = "AL", description = "Albania" }); countriesList.Add(new Country { label = "AM", description = "Armenia" }); countriesList.Add(new Country { label = "AO", description = "Angola" }); countriesList.Add(new Country { label = "AQ", description = "Antarctica" }); countriesList.Add(new Country { label = "AR", description = "Argentina" }); countriesList.Add(new Country { label = "AS", description = "Samoa (American)" }); countriesList.Add(new Country { label = "AT", description = "Austria" }); countriesList.Add(new Country { label = "AU", description = "Australia" }); countriesList.Add(new Country { label = "AW", description = "Aruba" }); countriesList.Add(new Country { label = "AX", description = "Aaland Islands" }); countriesList.Add(new Country { label = "AZ", description = "Azerbaijan" }); countriesList.Add(new Country { label = "BA", description = "Bosnia & Herzegovina" }); countriesList.Add(new Country { label = "BB", description = "Barbados" }); countriesList.Add(new Country { label = "BD", description = "Bangladesh" }); countriesList.Add(new Country { label = "BE", description = "Belgium" }); countriesList.Add(new Country { label = "BF", description = "Burkina Faso" }); countriesList.Add(new Country { label = "BG", description = "Bulgaria" }); countriesList.Add(new Country { label = "BH", description = "Bahrain" }); countriesList.Add(new Country { label = "BI", description = "Burundi" }); countriesList.Add(new Country { label = "BJ", description = "Benin" }); countriesList.Add(new Country { label = "BL", description = "St Barthelemy" }); countriesList.Add(new Country { label = "BM", description = "Bermuda" }); countriesList.Add(new Country { label = "BN", description = "Brunei" }); countriesList.Add(new Country { label = "BO", description = "Bolivia" }); countriesList.Add(new Country { label = "BQ", description = "Caribbean Netherlands" }); countriesList.Add(new Country { label = "BR", description = "Brazil" }); countriesList.Add(new Country { label = "BS", description = "Bahamas" }); countriesList.Add(new Country { label = "BT", description = "Bhutan" }); countriesList.Add(new Country { label = "BV", description = "Bouvet Island" }); countriesList.Add(new Country { label = "BW", description = "Botswana" }); countriesList.Add(new Country { label = "BY", description = "Belarus" }); countriesList.Add(new Country { label = "BZ", description = "Belize" }); countriesList.Add(new Country { label = "CA", description = "Canada" }); countriesList.Add(new Country { label = "CC", description = "Cocos (Keeling) Islands" }); countriesList.Add(new Country { label = "CD", description = "Congo (Dem. Rep.)" }); countriesList.Add(new Country { label = "CF", description = "Central African Rep." }); countriesList.Add(new Country { label = "CG", description = "Congo (Rep.)" }); countriesList.Add(new Country { label = "CH", description = "Switzerland" }); countriesList.Add(new Country { label = "CI", description = "Cote d'Ivoire" }); countriesList.Add(new Country { label = "CK", description = "Cook Islands" }); countriesList.Add(new Country { label = "CL", description = "Chile" }); countriesList.Add(new Country { label = "CM", description = "Cameroon" }); countriesList.Add(new Country { label = "CN", description = "China" }); countriesList.Add(new Country { label = "CO", description = "Colombia" }); countriesList.Add(new Country { label = "CR", description = "Costa Rica" }); countriesList.Add(new Country { label = "CU", description = "Cuba" }); countriesList.Add(new Country { label = "CV", description = "Cape Verde" }); countriesList.Add(new Country { label = "CW", description = "Curacao" }); countriesList.Add(new Country { label = "CX", description = "Christmas Island" }); countriesList.Add(new Country { label = "CY", description = "Cyprus" }); countriesList.Add(new Country { label = "CZ", description = "Czech Republic" }); countriesList.Add(new Country { label = "DE", description = "Germany" }); countriesList.Add(new Country { label = "DJ", description = "Djibouti" }); countriesList.Add(new Country { label = "DK", description = "Denmark" }); countriesList.Add(new Country { label = "DM", description = "Dominica" }); countriesList.Add(new Country { label = "DO", description = "Dominican Republic" }); countriesList.Add(new Country { label = "DZ", description = "Algeria" }); countriesList.Add(new Country { label = "EC", description = "Ecuador" }); countriesList.Add(new Country { label = "EE", description = "Estonia" }); countriesList.Add(new Country { label = "EG", description = "Egypt" }); countriesList.Add(new Country { label = "EH", description = "Western Sahara" }); countriesList.Add(new Country { label = "ER", description = "Eritrea" }); countriesList.Add(new Country { label = "ES", description = "Spain" }); countriesList.Add(new Country { label = "ET", description = "Ethiopia" }); countriesList.Add(new Country { label = "FI", description = "Finland" }); countriesList.Add(new Country { label = "FJ", description = "Fiji" }); countriesList.Add(new Country { label = "FK", description = "Falkland Islands" }); countriesList.Add(new Country { label = "FM", description = "Micronesia" }); countriesList.Add(new Country { label = "FO", description = "Faroe Islands" }); countriesList.Add(new Country { label = "FR", description = "France" }); countriesList.Add(new Country { label = "GA", description = "Gabon" }); countriesList.Add(new Country { label = "GB", description = "Britain (UK)" }); countriesList.Add(new Country { label = "GD", description = "Grenada" }); countriesList.Add(new Country { label = "GE", description = "Georgia" }); countriesList.Add(new Country { label = "GF", description = "French Guiana" }); countriesList.Add(new Country { label = "GG", description = "Guernsey" }); countriesList.Add(new Country { label = "GH", description = "Ghana" }); countriesList.Add(new Country { label = "GI", description = "Gibraltar" }); countriesList.Add(new Country { label = "GL", description = "Greenland" }); countriesList.Add(new Country { label = "GM", description = "Gambia" }); countriesList.Add(new Country { label = "GN", description = "Guinea" }); countriesList.Add(new Country { label = "GP", description = "Guadeloupe" }); countriesList.Add(new Country { label = "GQ", description = "Equatorial Guinea" }); countriesList.Add(new Country { label = "GR", description = "Greece" }); countriesList.Add(new Country { label = "GS", description = "South Georgia & the South Sandwich Islands" }); countriesList.Add(new Country { label = "GT", description = "Guatemala" }); countriesList.Add(new Country { label = "GU", description = "Guam" }); countriesList.Add(new Country { label = "GW", description = "Guinea-Bissau" }); countriesList.Add(new Country { label = "GY", description = "Guyana" }); countriesList.Add(new Country { label = "HK", description = "Hong Kong" }); countriesList.Add(new Country { label = "HM", description = "Heard Island & McDonald Islands" }); countriesList.Add(new Country { label = "HN", description = "Honduras" }); countriesList.Add(new Country { label = "HR", description = "Croatia" }); countriesList.Add(new Country { label = "HT", description = "Haiti" }); countriesList.Add(new Country { label = "HU", description = "Hungary" }); countriesList.Add(new Country { label = "ID", description = "Indonesia" }); countriesList.Add(new Country { label = "IE", description = "Ireland" }); countriesList.Add(new Country { label = "IL", description = "Israel" }); countriesList.Add(new Country { label = "IM", description = "Isle of Man" }); countriesList.Add(new Country { label = "IN", description = "India" }); countriesList.Add(new Country { label = "IO", description = "British Indian Ocean Territory" }); countriesList.Add(new Country { label = "IQ", description = "Iraq" }); countriesList.Add(new Country { label = "IR", description = "Iran" }); countriesList.Add(new Country { label = "IS", description = "Iceland" }); countriesList.Add(new Country { label = "IT", description = "Italy" }); countriesList.Add(new Country { label = "JE", description = "Jersey" }); countriesList.Add(new Country { label = "JM", description = "Jamaica" }); countriesList.Add(new Country { label = "JO", description = "Jordan" }); countriesList.Add(new Country { label = "JP", description = "Japan" }); countriesList.Add(new Country { label = "KE", description = "Kenya" }); countriesList.Add(new Country { label = "KG", description = "Kyrgyzstan" }); countriesList.Add(new Country { label = "KH", description = "Cambodia" }); countriesList.Add(new Country { label = "KI", description = "Kiribati" }); countriesList.Add(new Country { label = "KM", description = "Comoros" }); countriesList.Add(new Country { label = "KN", description = "St Kitts & Nevis" }); countriesList.Add(new Country { label = "KP", description = "Korea (North)" }); countriesList.Add(new Country { label = "KR", description = "Korea (South)" }); countriesList.Add(new Country { label = "KW", description = "Kuwait" }); countriesList.Add(new Country { label = "KY", description = "Cayman Islands" }); countriesList.Add(new Country { label = "KZ", description = "Kazakhstan" }); countriesList.Add(new Country { label = "LA", description = "Laos" }); countriesList.Add(new Country { label = "LB", description = "Lebanon" }); countriesList.Add(new Country { label = "LC", description = "St Lucia" }); countriesList.Add(new Country { label = "LI", description = "Liechtenstein" }); countriesList.Add(new Country { label = "LK", description = "Sri Lanka" }); countriesList.Add(new Country { label = "LR", description = "Liberia" }); countriesList.Add(new Country { label = "LS", description = "Lesotho" }); countriesList.Add(new Country { label = "LT", description = "Lithuania" }); countriesList.Add(new Country { label = "LU", description = "Luxembourg" }); countriesList.Add(new Country { label = "LV", description = "Latvia" }); countriesList.Add(new Country { label = "LY", description = "Libya" }); countriesList.Add(new Country { label = "MA", description = "Morocco" }); countriesList.Add(new Country { label = "MC", description = "Monaco" }); countriesList.Add(new Country { label = "MD", description = "Moldova" }); countriesList.Add(new Country { label = "ME", description = "Montenegro" }); countriesList.Add(new Country { label = "MF", description = "St Martin (French part)" }); countriesList.Add(new Country { label = "MG", description = "Madagascar" }); countriesList.Add(new Country { label = "MH", description = "Marshall Islands" }); countriesList.Add(new Country { label = "MK", description = "Macedonia" }); countriesList.Add(new Country { label = "ML", description = "Mali" }); countriesList.Add(new Country { label = "MM", description = "Myanmar (Burma)" }); countriesList.Add(new Country { label = "MN", description = "Mongolia" }); countriesList.Add(new Country { label = "MO", description = "Macau" }); countriesList.Add(new Country { label = "MP", description = "Northern Mariana Islands" }); countriesList.Add(new Country { label = "MQ", description = "Martinique" }); countriesList.Add(new Country { label = "MR", description = "Mauritania" }); countriesList.Add(new Country { label = "MS", description = "Montserrat" }); countriesList.Add(new Country { label = "MT", description = "Malta" }); countriesList.Add(new Country { label = "MU", description = "Mauritius" }); countriesList.Add(new Country { label = "MV", description = "Maldives" }); countriesList.Add(new Country { label = "MW", description = "Malawi" }); countriesList.Add(new Country { label = "MX", description = "Mexico" }); countriesList.Add(new Country { label = "MY", description = "Malaysia" }); countriesList.Add(new Country { label = "MZ", description = "Mozambique" }); countriesList.Add(new Country { label = "NA", description = "Namibia" }); countriesList.Add(new Country { label = "NC", description = "New Caledonia" }); countriesList.Add(new Country { label = "NE", description = "Niger" }); countriesList.Add(new Country { label = "NF", description = "Norfolk Island" }); countriesList.Add(new Country { label = "NG", description = "Nigeria" }); countriesList.Add(new Country { label = "NI", description = "Nicaragua" }); countriesList.Add(new Country { label = "NL", description = "Netherlands" }); countriesList.Add(new Country { label = "NO", description = "Norway" }); countriesList.Add(new Country { label = "NP", description = "Nepal" }); countriesList.Add(new Country { label = "NR", description = "Nauru" }); countriesList.Add(new Country { label = "NU", description = "Niue" }); countriesList.Add(new Country { label = "NZ", description = "New Zealand" }); countriesList.Add(new Country { label = "OM", description = "Oman" }); countriesList.Add(new Country { label = "PA", description = "Panama" }); countriesList.Add(new Country { label = "PE", description = "Peru" }); countriesList.Add(new Country { label = "PF", description = "French Polynesia" }); countriesList.Add(new Country { label = "PG", description = "Papua New Guinea" }); countriesList.Add(new Country { label = "PH", description = "Philippines" }); countriesList.Add(new Country { label = "PK", description = "Pakistan" }); countriesList.Add(new Country { label = "PL", description = "Poland" }); countriesList.Add(new Country { label = "PM", description = "St Pierre & Miquelon" }); countriesList.Add(new Country { label = "PN", description = "Pitcairn" }); countriesList.Add(new Country { label = "PR", description = "Puerto Rico" }); countriesList.Add(new Country { label = "PS", description = "Palestine" }); countriesList.Add(new Country { label = "PT", description = "Portugal" }); countriesList.Add(new Country { label = "PW", description = "Palau" }); countriesList.Add(new Country { label = "PY", description = "Paraguay" }); countriesList.Add(new Country { label = "QA", description = "Qatar" }); countriesList.Add(new Country { label = "RE", description = "Reunion" }); countriesList.Add(new Country { label = "RO", description = "Romania" }); countriesList.Add(new Country { label = "RS", description = "Serbia" }); countriesList.Add(new Country { label = "RU", description = "Russia" }); countriesList.Add(new Country { label = "RW", description = "Rwanda" }); countriesList.Add(new Country { label = "SA", description = "Saudi Arabia" }); countriesList.Add(new Country { label = "SB", description = "Solomon Islands" }); countriesList.Add(new Country { label = "SC", description = "Seychelles" }); countriesList.Add(new Country { label = "SD", description = "Sudan" }); countriesList.Add(new Country { label = "SE", description = "Sweden" }); countriesList.Add(new Country { label = "SG", description = "Singapore" }); countriesList.Add(new Country { label = "SH", description = "St Helena" }); countriesList.Add(new Country { label = "SI", description = "Slovenia" }); countriesList.Add(new Country { label = "SJ", description = "Svalbard & Jan Mayen" }); countriesList.Add(new Country { label = "SK", description = "Slovakia" }); countriesList.Add(new Country { label = "SL", description = "Sierra Leone" }); countriesList.Add(new Country { label = "SM", description = "San Marino" }); countriesList.Add(new Country { label = "SN", description = "Senegal" }); countriesList.Add(new Country { label = "SO", description = "Somalia" }); countriesList.Add(new Country { label = "SR", description = "Suriname" }); countriesList.Add(new Country { label = "SS", description = "South Sudan" }); countriesList.Add(new Country { label = "ST", description = "Sao Tome & Principe" }); countriesList.Add(new Country { label = "SV", description = "El Salvador" }); countriesList.Add(new Country { label = "SX", description = "St Maarten (Dutch part)" }); countriesList.Add(new Country { label = "SY", description = "Syria" }); countriesList.Add(new Country { label = "SZ", description = "Swaziland" }); countriesList.Add(new Country { label = "TC", description = "Turks & Caicos Is" }); countriesList.Add(new Country { label = "TD", description = "Chad" }); countriesList.Add(new Country { label = "TF", description = "French Southern & Antarctic Lands" }); countriesList.Add(new Country { label = "TG", description = "Togo" }); countriesList.Add(new Country { label = "TH", description = "Thailand" }); countriesList.Add(new Country { label = "TJ", description = "Tajikistan" }); countriesList.Add(new Country { label = "TK", description = "Tokelau" }); countriesList.Add(new Country { label = "TL", description = "East Timor" }); countriesList.Add(new Country { label = "TM", description = "Turkmenistan" }); countriesList.Add(new Country { label = "TN", description = "Tunisia" }); countriesList.Add(new Country { label = "TO", description = "Tonga" }); countriesList.Add(new Country { label = "TR", description = "Turkey" }); countriesList.Add(new Country { label = "TT", description = "Trinidad & Tobago" }); countriesList.Add(new Country { label = "TV", description = "Tuvalu" }); countriesList.Add(new Country { label = "TW", description = "Taiwan" }); countriesList.Add(new Country { label = "TZ", description = "Tanzania" }); countriesList.Add(new Country { label = "UA", description = "Ukraine" }); countriesList.Add(new Country { label = "UG", description = "Uganda" }); countriesList.Add(new Country { label = "UM", description = "US minor outlying islands" }); countriesList.Add(new Country { label = "US", description = "United States" }); countriesList.Add(new Country { label = "UY", description = "Uruguay" }); countriesList.Add(new Country { label = "UZ", description = "Uzbekistan" }); countriesList.Add(new Country { label = "VA", description = "Vatican City" }); countriesList.Add(new Country { label = "VC", description = "St Vincent" }); countriesList.Add(new Country { label = "VE", description = "Venezuela" }); countriesList.Add(new Country { label = "VG", description = "Virgin Islands (UK)" }); countriesList.Add(new Country { label = "VI", description = "Virgin Islands (US)" }); countriesList.Add(new Country { label = "VN", description = "Vietnam" }); countriesList.Add(new Country { label = "VU", description = "Vanuatu" }); countriesList.Add(new Country { label = "WF", description = "Wallis & Futuna" }); countriesList.Add(new Country { label = "WS", description = "Samoa (western)" }); countriesList.Add(new Country { label = "YE", description = "Yemen" }); countriesList.Add(new Country { label = "YT", description = "Mayotte" }); countriesList.Add(new Country { label = "ZA", description = "South Africa" }); countriesList.Add(new Country { label = "ZM", description = "Zambia" }); countriesList.Add(new Country { label = "ZW", description = "Zimbabwe" });
using System; using System.Collections.Generic; using System.Linq; using Bedrock.Modularity; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Bedrock.Tests.Modularity { [TestClass] public class ModuleCatalogFixture { [TestMethod] public void CanCreateCatalogFromList() { var moduleInfo = new ModuleInfo("MockModule", "type"); List<ModuleInfo> moduleInfos = new List<ModuleInfo> { moduleInfo }; var moduleCatalog = new ModuleCatalog(moduleInfos); Assert.AreEqual(1, moduleCatalog.Modules.Count()); Assert.AreEqual(moduleInfo, moduleCatalog.Modules.ElementAt(0)); } [TestMethod] public void CanGetDependenciesForModule() { // A <- B var moduleInfoA = CreateModuleInfo("A"); var moduleInfoB = CreateModuleInfo("B", "A"); List<ModuleInfo> moduleInfos = new List<ModuleInfo> { moduleInfoA , moduleInfoB }; var moduleCatalog = new ModuleCatalog(moduleInfos); IEnumerable<ModuleInfo> dependentModules = moduleCatalog.GetDependentModules(moduleInfoB); Assert.AreEqual(1, dependentModules.Count()); Assert.AreEqual(moduleInfoA, dependentModules.ElementAt(0)); } [TestMethod] public void CanCompleteListWithTheirDependencies() { // A <- B <- C var moduleInfoA = CreateModuleInfo("A"); var moduleInfoB = CreateModuleInfo("B", "A"); var moduleInfoC = CreateModuleInfo("C", "B"); var moduleInfoOrphan = CreateModuleInfo("X", "B"); List<ModuleInfo> moduleInfos = new List<ModuleInfo> { moduleInfoA , moduleInfoB , moduleInfoC , moduleInfoOrphan }; var moduleCatalog = new ModuleCatalog(moduleInfos); IEnumerable<ModuleInfo> dependantModules = moduleCatalog.CompleteListWithDependencies(new[] { moduleInfoC }); Assert.AreEqual(3, dependantModules.Count()); Assert.IsTrue(dependantModules.Contains(moduleInfoA)); Assert.IsTrue(dependantModules.Contains(moduleInfoB)); Assert.IsTrue(dependantModules.Contains(moduleInfoC)); } [TestMethod] [ExpectedException(typeof(CyclicDependencyFoundException))] public void ShouldThrowOnCyclicDependency() { // A <- B <- C <- A var moduleInfoA = CreateModuleInfo("A", "C"); var moduleInfoB = CreateModuleInfo("B", "A"); var moduleInfoC = CreateModuleInfo("C", "B"); List<ModuleInfo> moduleInfos = new List<ModuleInfo> { moduleInfoA , moduleInfoB , moduleInfoC }; new ModuleCatalog(moduleInfos).Validate(); } [TestMethod] [ExpectedException(typeof(DuplicateModuleException))] public void ShouldThrowOnDuplicateModule() { var moduleInfoA1 = CreateModuleInfo("A"); var moduleInfoA2 = CreateModuleInfo("A"); List<ModuleInfo> moduleInfos = new List<ModuleInfo> { moduleInfoA1 , moduleInfoA2 }; new ModuleCatalog(moduleInfos).Validate(); } [TestMethod] [ExpectedException(typeof(ModularityException))] public void ShouldThrowOnMissingDependency() { var moduleInfoA = CreateModuleInfo("A", "B"); List<ModuleInfo> moduleInfos = new List<ModuleInfo> { moduleInfoA }; new ModuleCatalog(moduleInfos).Validate(); } [TestMethod] public void CanAddModules() { var catalog = new ModuleCatalog(); catalog.AddModule(typeof(MockModule)); Assert.AreEqual(1, catalog.Modules.Count()); Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName); } [TestMethod] public void CanAddGroups() { var catalog = new ModuleCatalog(); ModuleInfo moduleInfo = new ModuleInfo(); ModuleInfoGroup group = new ModuleInfoGroup { moduleInfo }; catalog.Items.Add(group); Assert.AreEqual(1, catalog.Modules.Count()); Assert.AreSame(moduleInfo, catalog.Modules.ElementAt(0)); } [TestMethod] public void ShouldAggregateGroupsAndLooseModuleInfos() { var catalog = new ModuleCatalog(); ModuleInfo moduleInfo1 = new ModuleInfo(); ModuleInfo moduleInfo2 = new ModuleInfo(); ModuleInfo moduleInfo3 = new ModuleInfo(); catalog.Items.Add(new ModuleInfoGroup() { moduleInfo1 }); catalog.Items.Add(new ModuleInfoGroup() { moduleInfo2 }); catalog.AddModule(moduleInfo3); Assert.AreEqual(3, catalog.Modules.Count()); Assert.IsTrue(catalog.Modules.Contains(moduleInfo1)); Assert.IsTrue(catalog.Modules.Contains(moduleInfo2)); Assert.IsTrue(catalog.Modules.Contains(moduleInfo3)); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void CompleteListWithDependenciesThrowsWithNull() { var catalog = new ModuleCatalog(); catalog.CompleteListWithDependencies(null); } [TestMethod] public void LooseModuleIfDependentOnModuleInGroupThrows() { var catalog = new ModuleCatalog(); catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") }); catalog.AddModule(CreateModuleInfo("ModuleB", "ModuleA")); try { catalog.Validate(); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(ModularityException)); Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName); return; } Assert.Fail("Exception not thrown."); } [TestMethod] public void ModuleInGroupDependsOnModuleInOtherGroupThrows() { var catalog = new ModuleCatalog(); catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") }); catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleB", "ModuleA") }); try { catalog.Validate(); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(ModularityException)); Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName); return; } Assert.Fail("Exception not thrown."); } [TestMethod] public void ShouldRevalidateWhenAddingNewModuleIfValidated() { var testableCatalog = new TestableModuleCatalog(); testableCatalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") }); testableCatalog.Validate(); testableCatalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleB") }); Assert.IsTrue(testableCatalog.ValidateCalled); } [TestMethod] public void ModuleInGroupCanDependOnModuleInSameGroup() { var catalog = new ModuleCatalog(); var moduleA = CreateModuleInfo("ModuleA"); var moduleB = CreateModuleInfo("ModuleB", "ModuleA"); catalog.Items.Add(new ModuleInfoGroup() { moduleA, moduleB }); var moduleBDependencies = catalog.GetDependentModules(moduleB); Assert.AreEqual(1, moduleBDependencies.Count()); Assert.AreEqual(moduleA, moduleBDependencies.First()); } [TestMethod] public void StartupModuleDependentOnAnOnDemandModuleThrows() { var catalog = new ModuleCatalog(); var moduleOnDemand = CreateModuleInfo("ModuleA"); moduleOnDemand.InitializationMode = InitializationMode.OnDemand; catalog.AddModule(moduleOnDemand); catalog.AddModule(CreateModuleInfo("ModuleB", "ModuleA")); try { catalog.Validate(); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(ModularityException)); Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName); return; } Assert.Fail("Exception not thrown."); } [TestMethod] public void ShouldReturnInCorrectRetrieveOrderWhenCompletingListWithDependencies() { // A <- B <- C <- D, C <- X var moduleA = CreateModuleInfo("A"); var moduleB = CreateModuleInfo("B", "A"); var moduleC = CreateModuleInfo("C", "B"); var moduleD = CreateModuleInfo("D", "C"); var moduleX = CreateModuleInfo("X", "C"); var moduleCatalog = new ModuleCatalog(); // Add the modules in random order moduleCatalog.AddModule(moduleB); moduleCatalog.AddModule(moduleA); moduleCatalog.AddModule(moduleD); moduleCatalog.AddModule(moduleX); moduleCatalog.AddModule(moduleC); var dependantModules = moduleCatalog.CompleteListWithDependencies(new[] { moduleD, moduleX }).ToList(); Assert.AreEqual(5, dependantModules.Count); Assert.IsTrue(dependantModules.IndexOf(moduleA) < dependantModules.IndexOf(moduleB)); Assert.IsTrue(dependantModules.IndexOf(moduleB) < dependantModules.IndexOf(moduleC)); Assert.IsTrue(dependantModules.IndexOf(moduleC) < dependantModules.IndexOf(moduleD)); Assert.IsTrue(dependantModules.IndexOf(moduleC) < dependantModules.IndexOf(moduleX)); } // // [TestMethod] // public void CanLoadCatalogFromXaml() // { // Stream stream = // Assembly.GetExecutingAssembly().GetManifestResourceStream( // "Bedrock.Tests.Modularity.ModuleCatalogXaml.SimpleModuleCatalog.xaml"); // // var catalog = ModuleCatalog.CreateFromXaml(stream); // Assert.IsNotNull(catalog); // // Assert.AreEqual(4, catalog.Modules.Count()); // } [TestMethod] public void ShouldLoadAndValidateOnInitialize() { var catalog = new TestableModuleCatalog(); var testableCatalog = new TestableModuleCatalog(); Assert.IsFalse(testableCatalog.LoadCalled); Assert.IsFalse(testableCatalog.ValidateCalled); testableCatalog.Initialize(); Assert.IsTrue(testableCatalog.LoadCalled); Assert.IsTrue(testableCatalog.ValidateCalled); Assert.IsTrue(testableCatalog.LoadCalledFirst); } [TestMethod] public void ShouldNotLoadAgainIfInitializedCalledMoreThanOnce() { var catalog = new TestableModuleCatalog(); var testableCatalog = new TestableModuleCatalog(); Assert.IsFalse(testableCatalog.LoadCalled); Assert.IsFalse(testableCatalog.ValidateCalled); testableCatalog.Initialize(); Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount); testableCatalog.Initialize(); Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount); } [TestMethod] public void ShouldNotLoadAgainDuringInitialize() { var catalog = new TestableModuleCatalog(); var testableCatalog = new TestableModuleCatalog(); Assert.IsFalse(testableCatalog.LoadCalled); Assert.IsFalse(testableCatalog.ValidateCalled); testableCatalog.Load(); Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount); testableCatalog.Initialize(); Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount); } [TestMethod] public void ShouldAllowLoadToBeInvokedTwice() { var catalog = new TestableModuleCatalog(); var testableCatalog = new TestableModuleCatalog(); testableCatalog.Load(); Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount); testableCatalog.Load(); Assert.AreEqual<int>(2, testableCatalog.LoadCalledCount); } [TestMethod] public void CanAddModule1() { ModuleCatalog catalog = new ModuleCatalog(); catalog.AddModule("Module", "ModuleType", InitializationMode.OnDemand, "DependsOn1", "DependsOn2"); Assert.AreEqual(1, catalog.Modules.Count()); Assert.AreEqual("Module", catalog.Modules.First().ModuleName); Assert.AreEqual("ModuleType", catalog.Modules.First().ModuleType); Assert.AreEqual(InitializationMode.OnDemand, catalog.Modules.First().InitializationMode); Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count); Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]); Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]); } [TestMethod] public void CanAddModule2() { ModuleCatalog catalog = new ModuleCatalog(); catalog.AddModule("Module", "ModuleType", "DependsOn1", "DependsOn2"); Assert.AreEqual(1, catalog.Modules.Count()); Assert.AreEqual("Module", catalog.Modules.First().ModuleName); Assert.AreEqual("ModuleType", catalog.Modules.First().ModuleType); Assert.AreEqual(InitializationMode.WhenAvailable, catalog.Modules.First().InitializationMode); Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count); Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]); Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]); } [TestMethod] public void CanAddModule3() { ModuleCatalog catalog = new ModuleCatalog(); catalog.AddModule(typeof(MockModule), InitializationMode.OnDemand, "DependsOn1", "DependsOn2"); Assert.AreEqual(1, catalog.Modules.Count()); Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName); Assert.AreEqual(typeof(MockModule).AssemblyQualifiedName, catalog.Modules.First().ModuleType); Assert.AreEqual(InitializationMode.OnDemand, catalog.Modules.First().InitializationMode); Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count); Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]); Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]); } [TestMethod] public void CanAddModule4() { ModuleCatalog catalog = new ModuleCatalog(); catalog.AddModule(typeof(MockModule), "DependsOn1", "DependsOn2"); Assert.AreEqual(1, catalog.Modules.Count()); Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName); Assert.AreEqual(typeof(MockModule).AssemblyQualifiedName, catalog.Modules.First().ModuleType); Assert.AreEqual(InitializationMode.WhenAvailable, catalog.Modules.First().InitializationMode); Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count); Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]); Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]); } [TestMethod] public void CanAddGroup() { ModuleCatalog catalog = new ModuleCatalog(); catalog.Items.Add(new ModuleInfoGroup()); catalog.AddGroup(InitializationMode.OnDemand, "Ref1", new ModuleInfo("M1", "T1"), new ModuleInfo("M2", "T2", "M1")); Assert.AreEqual(2, catalog.Modules.Count()); var module1 = catalog.Modules.First(); var module2 = catalog.Modules.Skip(1).First(); Assert.AreEqual("M1", module1.ModuleName); Assert.AreEqual("T1", module1.ModuleType); Assert.AreEqual("Ref1", module1.Ref); Assert.AreEqual(InitializationMode.OnDemand, module1.InitializationMode); Assert.AreEqual("M2", module2.ModuleName); Assert.AreEqual("T2", module2.ModuleType); Assert.AreEqual("Ref1", module2.Ref); Assert.AreEqual(InitializationMode.OnDemand, module2.InitializationMode); } private class TestableModuleCatalog : ModuleCatalog { public bool ValidateCalled { get; set; } public bool LoadCalledFirst { get; set; } public bool LoadCalled { get { return LoadCalledCount > 0; } } public int LoadCalledCount { get; set; } public override void Validate() { ValidateCalled = true; Validated = true; } protected override void InnerLoad() { if (ValidateCalled == false && !LoadCalled) LoadCalledFirst = true; LoadCalledCount++; } } private static ModuleInfo CreateModuleInfo(string name, params string[] dependsOn) { ModuleInfo moduleInfo = new ModuleInfo(name, name); moduleInfo.DependsOn.AddRange(dependsOn); return moduleInfo; } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Nfs { using System; using System.Globalization; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; internal sealed class RpcTcpTransport : IDisposable { private const int RetryLimit = 20; private string _address; private int _port; private int _localPort; private Socket _socket; private NetworkStream _tcpStream; public RpcTcpTransport(string address, int port) : this(address, port, 0) { } public RpcTcpTransport(string address, int port, int localPort) { _address = address; _port = port; _localPort = localPort; } public void Dispose() { if (_tcpStream != null) { _tcpStream.Dispose(); _tcpStream = null; } if (_socket != null) { #if NETCORE _socket.Dispose(); #else _socket.Close(); #endif _socket = null; } } public byte[] Send(byte[] message) { int retries = 0; int retryLimit = RetryLimit; Exception lastException = null; bool isNewConnection = _socket == null; if (isNewConnection) { retryLimit = 1; } byte[] response = null; while (response == null && retries < retryLimit) { while (retries < retryLimit && (_socket == null || !_socket.Connected)) { try { if (_tcpStream != null) { _tcpStream.Dispose(); _tcpStream = null; } if (_socket != null) { #if NETCORE _socket.Dispose(); #else _socket.Close(); #endif _socket = null; } _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _socket.NoDelay = true; if (_localPort != 0) { _socket.Bind(new IPEndPoint(0, _localPort)); } _socket.Connect(_address, _port); _tcpStream = new NetworkStream(_socket, false); } catch (IOException connectException) { retries++; lastException = connectException; if (!isNewConnection) { Thread.Sleep(1000); } } catch (SocketException se) { retries++; lastException = se; if (!isNewConnection) { Thread.Sleep(1000); } } } if (_tcpStream != null) { try { byte[] header = new byte[4]; Utilities.WriteBytesBigEndian((uint)(0x80000000 | (uint)message.Length), header, 0); _tcpStream.Write(header, 0, 4); _tcpStream.Write(message, 0, message.Length); _tcpStream.Flush(); response = Receive(); } catch (IOException sendReceiveException) { lastException = sendReceiveException; _tcpStream.Dispose(); _tcpStream = null; #if NETCORE _socket.Dispose(); #else _socket.Close(); #endif _socket = null; } retries++; } } if (response == null) { throw new IOException(string.Format(CultureInfo.InvariantCulture, "Unable to send RPC message to {0}:{1}", _address, _port), lastException); } return response; } private byte[] Receive() { MemoryStream ms = null; bool lastFragFound = false; while (!lastFragFound) { byte[] header = Utilities.ReadFully(_tcpStream, 4); uint headerVal = Utilities.ToUInt32BigEndian(header, 0); lastFragFound = (headerVal & 0x80000000) != 0; byte[] frag = Utilities.ReadFully(_tcpStream, (int)(headerVal & 0x7FFFFFFF)); if (ms != null) { ms.Write(frag, 0, frag.Length); } else if (!lastFragFound) { ms = new MemoryStream(); ms.Write(frag, 0, frag.Length); } else { return frag; } } return ms.ToArray(); } } }
using System; using System.Diagnostics; using NUnit.Framework; using Shouldly; namespace StructureMap.Testing { // SAMPLE: auto-wiring-sample public interface Xman { } public class Cyclops : Xman { } public interface Avenger { } public class IronMan : Avenger { } public class CrossoverEvent { public Xman Xman { get; set; } public Avenger Avenger { get; set; } public CrossoverEvent(Xman xman, Avenger avenger) { Xman = xman; Avenger = avenger; } } public class UsingCrossover { [Test] public void showing_auto_wiring() { var container = new Container(x => { x.For<Xman>().Use<Cyclops>(); x.For<Avenger>().Use<IronMan>(); }); // Notice that at no point did we define how to // build CrossoverEvent. var @event = container.GetInstance<CrossoverEvent>(); @event.Avenger.ShouldBeOfType<IronMan>(); @event.Xman.ShouldBeOfType<Cyclops>(); } } // ENDSAMPLE public interface IValidator { } public class Validator : IValidator { private readonly string _name; public Validator(string name) { _name = name; } public override string ToString() { return string.Format("Name: {0}", _name); } } public class ClassThatUsesValidators { private readonly IValidator[] _validators; public ClassThatUsesValidators(IValidator[] validators) { _validators = validators; } public void Write() { foreach (var validator in _validators) { Debug.WriteLine(validator); } } } [TestFixture] public class ValidatorExamples { #region Setup/Teardown [SetUp] public void SetUp() { container = new Container(x => { x.For<IValidator>().AddInstances(o => { o.Type<Validator>().Ctor<string>("name").Is("Red").Named("Red"); o.Type<Validator>().Ctor<string>("name").Is("Blue").Named("Blue"); o.Type<Validator>().Ctor<string>("name").Is("Purple").Named("Purple"); o.Type<Validator>().Ctor<string>("name").Is("Green").Named("Green"); }); x.For<ClassThatUsesValidators>().AddInstances(o => { // Define an Instance of ClassThatUsesValidators that depends on AutoWiring o.Type<ClassThatUsesValidators>().Named("WithAutoWiring"); // Define an Instance of ClassThatUsesValidators that overrides AutoWiring o.Type<ClassThatUsesValidators>().Named("ExplicitArray") .EnumerableOf<IValidator>().Contains(y => { y.TheInstanceNamed("Red"); y.TheInstanceNamed("Green"); }); }); }); } #endregion private Container container; public class DataContext { private readonly Guid _id = Guid.NewGuid(); public override string ToString() { return string.Format("Id: {0}", _id); } } public class Class1 { private readonly DataContext _context; public Class1(DataContext context) { _context = context; } public override string ToString() { return string.Format("Class1 has session: {0}", _context); } } public class Class2 { private readonly Class1 _class1; private readonly DataContext _context; public Class2(Class1 class1, DataContext context) { _class1 = class1; _context = context; } public override string ToString() { return string.Format("Class2 has session: {0}\n{1}", _context, _class1); } } public class Class3 { private readonly Class2 _class2; private readonly DataContext _context; public Class3(Class2 class2, DataContext context) { _class2 = class2; _context = context; } public override string ToString() { return string.Format("Class3 has session: {0}\n{1}", _context, _class2); } } [Test] public void demonstrate_session_identity() { var class3 = container.GetInstance<Class3>(); Debug.WriteLine(class3); } [Test] public void demonstrate_session_identity_with_explicit_argument() { var context = new DataContext(); Debug.WriteLine("The context being passed in is " + context); var class3 = container.With(context).GetInstance<Class3>(); Debug.WriteLine(class3); } [Test] public void what_are_the_validators() { Debug.WriteLine("With Auto Wiring"); container.GetInstance<ClassThatUsesValidators>("WithAutoWiring").Write(); Debug.WriteLine("================================="); Debug.WriteLine("With Explicit Configuration"); container.GetInstance<ClassThatUsesValidators>("ExplicitArray").Write(); } } }
//------------------------------------------------------------------------------ // <copyright file="ImageMap.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.ComponentModel; using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Util; using System.Web; /// <devdoc> /// <para>ImageMap class. Provides support for multiple /// region-defined actions within an image.</para> /// </devdoc> [ DefaultEvent("Click"), DefaultProperty("HotSpots"), ParseChildren(true, "HotSpots"), SupportsEventValidation, ] public class ImageMap : Image, IPostBackEventHandler { private static readonly object EventClick = new object(); private bool _hasHotSpots; private HotSpotCollection _hotSpots; [ Browsable(true), EditorBrowsableAttribute(EditorBrowsableState.Always) ] public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; } } /// <devdoc> /// <para>Gets the HotSpotCollection with defines the regions of ImageMap hot spots.</para> /// </devdoc> [ WebCategory("Behavior"), WebSysDescription(SR.ImageMap_HotSpots), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerDefaultProperty) ] public HotSpotCollection HotSpots { get { if (_hotSpots == null) { _hotSpots = new HotSpotCollection(); if (IsTrackingViewState) { ((IStateManager)_hotSpots).TrackViewState(); } } return _hotSpots; } } /// <devdoc> /// <para>Gets or sets the HotSpotMode to either postback or navigation.</para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(HotSpotMode.NotSet), WebSysDescription(SR.HotSpot_HotSpotMode), ] public virtual HotSpotMode HotSpotMode { get { object obj = ViewState["HotSpotMode"]; return (obj == null) ? HotSpotMode.NotSet : (HotSpotMode)obj; } set { if (value < HotSpotMode.NotSet || value > HotSpotMode.Inactive) { throw new ArgumentOutOfRangeException("value"); } ViewState["HotSpotMode"] = value; } } /// <devdoc> /// <para>Gets or sets the name of the window for navigation.</para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(""), WebSysDescription(SR.HotSpot_Target), ] public virtual string Target { get { object value = ViewState["Target"]; return (value == null)? String.Empty : (string)value; } set { ViewState["Target"] = value; } } /// <devdoc> /// <para>The event raised when a hotspot is clicked.</para> /// </devdoc> [ Category("Action"), WebSysDescription(SR.ImageMap_Click) ] public event ImageMapEventHandler Click { add { Events.AddHandler(EventClick, value); } remove { Events.RemoveHandler(EventClick, value); } } /// <internalonly/> /// <devdoc> /// <para>Overridden to add the "usemap" attribute the the image tag. /// Overrides WebControl.AddAttributesToRender.</para> /// </devdoc> protected override void AddAttributesToRender(HtmlTextWriter writer) { base.AddAttributesToRender(writer); if (_hasHotSpots) { writer.AddAttribute(HtmlTextWriterAttribute.Usemap, "#ImageMap" + ClientID, false); } } /// <devdoc> /// <para>Restores view-state information that was saved by SaveViewState. /// Implements IStateManager.LoadViewState.</para> /// </devdoc> protected override void LoadViewState(object savedState) { object baseState = null; object[] myState = null; if (savedState != null) { myState = (object[])savedState; if (myState.Length != 2) { throw new ArgumentException(SR.GetString(SR.ViewState_InvalidViewState)); } baseState = myState[0]; } base.LoadViewState(baseState); if ((myState != null) && (myState[1] != null)) { ((IStateManager)HotSpots).LoadViewState(myState[1]); } } /// <devdoc> /// <para>Called when the user clicks the ImageMap.</para> /// </devdoc> protected virtual void OnClick(ImageMapEventArgs e) { ImageMapEventHandler clickHandler = (ImageMapEventHandler)Events[EventClick]; if (clickHandler != null) { clickHandler(this, e); } } /// <internalonly/> /// <devdoc> /// <para>Sends server control content to a provided HtmlTextWriter, which writes the content /// to be rendered to the client. /// Overrides Control.Render.</para> /// </devdoc> protected internal override void Render(HtmlTextWriter writer) { if (Enabled && !IsEnabled && SupportsDisabledAttribute) { // We need to do the cascade effect on the server, because the browser // only renders as disabled, but doesn't disable the functionality. writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled"); } _hasHotSpots = ((_hotSpots != null) && (_hotSpots.Count > 0)); base.Render(writer); if (_hasHotSpots) { string fullClientID = "ImageMap" + ClientID; writer.AddAttribute(HtmlTextWriterAttribute.Name, fullClientID); writer.AddAttribute(HtmlTextWriterAttribute.Id, fullClientID); writer.RenderBeginTag(HtmlTextWriterTag.Map); HotSpotMode mapMode = HotSpotMode; if (mapMode == HotSpotMode.NotSet) { mapMode = HotSpotMode.Navigate; } HotSpotMode spotMode; int hotSpotIndex = 0; string controlTarget = Target; foreach (HotSpot item in _hotSpots) { writer.AddAttribute(HtmlTextWriterAttribute.Shape, item.MarkupName, false); writer.AddAttribute(HtmlTextWriterAttribute.Coords, item.GetCoordinates()); spotMode = item.HotSpotMode; if (spotMode == HotSpotMode.NotSet) { spotMode = mapMode; } if (spotMode == HotSpotMode.PostBack) { // Make sure the page has a server side form if we are posting back if (Page != null) { Page.VerifyRenderingInServerForm(this); } if ((RenderingCompatibility < VersionUtil.Framework40) || IsEnabled) { string eventArgument = hotSpotIndex.ToString(CultureInfo.InvariantCulture); writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackClientHyperlink(this, eventArgument, true)); } } else if (spotMode == HotSpotMode.Navigate) { if ((RenderingCompatibility < VersionUtil.Framework40) || IsEnabled) { String resolvedUrl = ResolveClientUrl(item.NavigateUrl); writer.AddAttribute(HtmlTextWriterAttribute.Href, resolvedUrl); } // Use HotSpot target first, if not specified, use ImageMap's target string target = item.Target; if (target.Length == 0) target = controlTarget; if (target.Length > 0) writer.AddAttribute(HtmlTextWriterAttribute.Target, target); } else if (spotMode == HotSpotMode.Inactive) { writer.AddAttribute("nohref", "true"); } writer.AddAttribute(HtmlTextWriterAttribute.Title, item.AlternateText); writer.AddAttribute(HtmlTextWriterAttribute.Alt, item.AlternateText); string s = item.AccessKey; if (s.Length > 0) { writer.AddAttribute(HtmlTextWriterAttribute.Accesskey, s); } int n = item.TabIndex; if (n != 0) { writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, n.ToString(NumberFormatInfo.InvariantInfo)); } writer.RenderBeginTag(HtmlTextWriterTag.Area); writer.RenderEndTag(); ++hotSpotIndex; } writer.RenderEndTag(); // Map } } /// <devdoc> /// <para>Saves any server control view-state changes that have /// occurred since the time the page was posted back to the server. /// Implements IStateManager.SaveViewState.</para> /// </devdoc> protected override object SaveViewState() { object baseState = base.SaveViewState(); object hotSpotsState = null; if ((_hotSpots != null) && (_hotSpots.Count > 0)) { hotSpotsState = ((IStateManager)_hotSpots).SaveViewState(); } if ((baseState != null) || (hotSpotsState != null)) { object[] savedState = new object[2]; savedState[0] = baseState; savedState[1] = hotSpotsState; return savedState; } return null; } /// <devdoc> /// <para>Causes the tracking of view-state changes to the server control. /// Implements IStateManager.TrackViewState.</para> /// </devdoc> protected override void TrackViewState() { base.TrackViewState(); if (_hotSpots != null) { ((IStateManager)_hotSpots).TrackViewState(); } } #region Implementation of IPostBackEventHandler /// <internalonly/> /// <devdoc> /// <para>Notifies the server control that caused the postback that /// it should handle an incoming post back event. /// Implements IPostBackEventHandler.</para> /// </devdoc> void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { RaisePostBackEvent(eventArgument); } /// <internalonly/> /// <devdoc> /// <para>Notifies the server control that caused the postback that /// it should handle an incoming post back event. /// Implements IPostBackEventHandler.</para> /// </devdoc> protected virtual void RaisePostBackEvent(string eventArgument) { ValidateEvent(UniqueID, eventArgument); string postBackValue = null; if (eventArgument != null && _hotSpots != null) { int hotSpotIndex = Int32.Parse(eventArgument, CultureInfo.InvariantCulture); if (hotSpotIndex >= 0 && hotSpotIndex < _hotSpots.Count) { HotSpot hotSpot = _hotSpots[hotSpotIndex]; HotSpotMode mode = hotSpot.HotSpotMode; if (mode == HotSpotMode.NotSet) { mode = HotSpotMode; } if (mode == HotSpotMode.PostBack) { postBackValue = hotSpot.PostBackValue; } } } // Ignore invalid indexes silently(VSWhidbey 185738) if (postBackValue != null) { OnClick(new ImageMapEventArgs(postBackValue)); } } #endregion } }
using System; using System.Diagnostics; using System.IO; using System.Net; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Web; using Recurly.Configuration; [assembly: InternalsVisibleTo("Recurly.Test")] namespace Recurly { /// <summary> /// Class for the Recurly client library. /// </summary> internal class Client { // refactored all these settings for increased testability public Settings Settings { get; protected set; } private static Client _instance; internal static Client Instance { get { return _instance ?? (_instance = new Client(Settings.Instance)); } } protected Client(Settings settings) { Settings = settings; } internal static void ChangeInstance(Client client) { _instance = client; } internal void ApplySettings(Settings settings) { Settings = settings; } public enum HttpRequestMethod { /// <summary> /// Lookup information about an object /// </summary> Get, /// <summary> /// Create a new object /// </summary> Post, /// <summary> /// Update an existing object /// </summary> Put, /// <summary> /// Delete an object /// </summary> Delete } /// <summary> /// Delegate to read a raw HTTP response from the server. /// </summary> public delegate void ReadResponseDelegate(HttpWebResponse response); /// <summary> /// Delegate to read the XML response from the server. /// </summary> /// <param name="xmlReader"></param> public delegate void ReadXmlDelegate(XmlTextReader xmlReader); /// <summary> /// Reads paged XML responses from the server /// </summary> /// <param name="xmlReader"></param> /// <param name="records"></param> public delegate void ReadXmlListDelegate(XmlTextReader xmlReader, int records, string start, string next, string prev); /// <summary> /// Delegate to write the XML request to the server. /// </summary> /// <param name="xmlWriter"></param> public delegate void WriteXmlDelegate(XmlTextWriter xmlWriter); public HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath) { return PerformRequest(method, urlPath, null, null, null, null); } public HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath, ReadXmlDelegate readXmlDelegate) { return PerformRequest(method, urlPath, null, readXmlDelegate, null, null); } public HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath, WriteXmlDelegate writeXmlDelegate) { return PerformRequest(method, urlPath, writeXmlDelegate, null, null, null); } public HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath, WriteXmlDelegate writeXmlDelegate, ReadXmlDelegate readXmlDelegate) { return PerformRequest(method, urlPath, writeXmlDelegate, readXmlDelegate, null, null); } public HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath, ReadXmlListDelegate readXmlListDelegate) { return PerformRequest(method, urlPath, null, null, readXmlListDelegate, null); } public HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath, WriteXmlDelegate writeXmlDelegate, ReadResponseDelegate responseDelegate) { return PerformRequest(method, urlPath, writeXmlDelegate, null, null, responseDelegate); } protected virtual HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath, WriteXmlDelegate writeXmlDelegate, ReadXmlDelegate readXmlDelegate, ReadXmlListDelegate readXmlListDelegate, ReadResponseDelegate reseponseDelegate) { var url = Settings.GetServerUri(urlPath); #if (DEBUG) Console.WriteLine("Requesting " + method + " " + url); #endif var request = (HttpWebRequest)WebRequest.Create(url); request.Accept = "application/xml"; // Tells the server to return XML instead of HTML request.ContentType = "application/xml; charset=utf-8"; // The request is an XML document request.SendChunked = false; // Send it all as one request request.UserAgent = Settings.UserAgent; request.Headers.Add(HttpRequestHeader.Authorization, Settings.AuthorizationHeaderValue); request.Headers.Add("X-Api-Version", Settings.RecurlyApiVersion); request.Method = method.ToString().ToUpper(); Debug.WriteLine(String.Format("Recurly: Requesting {0} {1}", request.Method, request.RequestUri)); if ((method == HttpRequestMethod.Post || method == HttpRequestMethod.Put) && (writeXmlDelegate != null)) { // 60 second timeout -- some payment gateways (e.g. PayPal) can take a while to respond request.Timeout = 60000; // Write POST/PUT body using (var requestStream = request.GetRequestStream()) { WritePostParameters(requestStream, writeXmlDelegate); } } else { request.ContentLength = 0; } try { using (var response = (HttpWebResponse)request.GetResponse()) { ReadWebResponse(response, readXmlDelegate, readXmlListDelegate, reseponseDelegate); return response.StatusCode; } } catch (WebException ex) { if (ex.Response == null) throw; var response = (HttpWebResponse)ex.Response; var statusCode = response.StatusCode; Error[] errors; Debug.WriteLine(String.Format("Recurly Library Received: {0} - {1}", (int)statusCode, statusCode)); switch (response.StatusCode) { case HttpStatusCode.OK: case HttpStatusCode.Accepted: case HttpStatusCode.Created: case HttpStatusCode.NoContent: ReadWebResponse(response, readXmlDelegate, readXmlListDelegate, reseponseDelegate); return HttpStatusCode.NoContent; case HttpStatusCode.NotFound: errors = Error.ReadResponseAndParseErrors(response); if (errors.Length > 0) throw new NotFoundException(errors[0].Message, errors); throw new NotFoundException("The requested object was not found.", errors); case HttpStatusCode.Unauthorized: case HttpStatusCode.Forbidden: errors = Error.ReadResponseAndParseErrors(response); throw new InvalidCredentialsException(errors); case HttpStatusCode.PreconditionFailed: errors = Error.ReadResponseAndParseErrors(response); throw new ValidationException(errors); case HttpStatusCode.ServiceUnavailable: throw new TemporarilyUnavailableException(); case HttpStatusCode.InternalServerError: errors = Error.ReadResponseAndParseErrors(response); throw new ServerException(errors); } if ((int)statusCode == ValidationException.HttpStatusCode) // Unprocessable Entity { errors = Error.ReadResponseAndParseErrors(response); if (errors.Length > 0) Debug.WriteLine(errors[0].ToString()); else Debug.WriteLine("Client Error: " + response.ToString()); throw new ValidationException(errors); } throw; } } /// <summary> /// Used for downloading PDFs /// </summary> /// <param name="urlPath"></param> /// <param name="acceptType"></param> /// <param name="acceptLanguage"></param> /// <returns></returns> public virtual byte[] PerformDownloadRequest(string urlPath, string acceptType, string acceptLanguage) { var url = Settings.GetServerUri(urlPath); var request = (HttpWebRequest)WebRequest.Create(url); request.Accept = acceptType; request.ContentType = "application/xml; charset=utf-8"; // The request is an XML document request.SendChunked = false; // Send it all as one request request.UserAgent = Settings.UserAgent; request.Headers.Add(HttpRequestHeader.Authorization, Settings.AuthorizationHeaderValue); request.Method = "GET"; request.Headers.Add("Accept-Language", acceptLanguage); Debug.WriteLine(String.Format("Recurly: Requesting {0} {1}", request.Method, request.RequestUri)); try { var r = (HttpWebResponse)request.GetResponse(); byte[] pdf; var buffer = new byte[2048]; if (!request.HaveResponse || r.StatusCode != HttpStatusCode.OK) return null; using (var ms = new MemoryStream()) { using (var reader = new BinaryReader(r.GetResponseStream(), Encoding.Default)) { int bytesRead; while ((bytesRead = reader.Read(buffer, 0, 2048)) > 0) { ms.Write(buffer, 0, bytesRead); } } pdf = ms.ToArray(); } return pdf; } catch (WebException ex) { if (ex.Response == null) throw; var response = (HttpWebResponse)ex.Response; var statusCode = response.StatusCode; Error[] errors; Debug.WriteLine(String.Format("Recurly Library Received: {0} - {1}", (int)statusCode, statusCode)); switch (response.StatusCode) { case HttpStatusCode.OK: case HttpStatusCode.Accepted: case HttpStatusCode.Created: case HttpStatusCode.NoContent: return null; case HttpStatusCode.NotFound: errors = Error.ReadResponseAndParseErrors(response); if (errors.Length > 0) throw new NotFoundException(errors[0].Message, errors); throw new NotFoundException("The requested object was not found.", errors); case HttpStatusCode.Unauthorized: case HttpStatusCode.Forbidden: errors = Error.ReadResponseAndParseErrors(response); throw new InvalidCredentialsException(errors); case HttpStatusCode.PreconditionFailed: errors = Error.ReadResponseAndParseErrors(response); throw new ValidationException(errors); case HttpStatusCode.ServiceUnavailable: throw new TemporarilyUnavailableException(); case HttpStatusCode.InternalServerError: errors = Error.ReadResponseAndParseErrors(response); throw new ServerException(errors); } if ((int)statusCode == ValidationException.HttpStatusCode) // Unprocessable Entity { errors = Error.ReadResponseAndParseErrors(response); throw new ValidationException(errors); } throw; } } protected virtual void ReadWebResponse(HttpWebResponse response, ReadXmlDelegate readXmlDelegate, ReadXmlListDelegate readXmlListDelegate, ReadResponseDelegate responseDelegate) { if (readXmlDelegate == null && readXmlListDelegate == null && responseDelegate == null) return; #if (DEBUG) Debug.WriteLine("Got Response:"); Debug.WriteLine("Status code: " + response.StatusCode); foreach (var header in response.Headers) { Debug.WriteLine(header + ": " + response.Headers[header.ToString()]); } #endif var responseStream = CopyAndClose(response.GetResponseStream()); var reader = new StreamReader(responseStream); #if (DEBUG) string line; while ((line = reader.ReadLine()) != null) { Debug.WriteLine(line); } #endif if (responseDelegate != null) { responseDelegate(response); return; } responseStream.Position = 0; using (var xmlReader = new XmlTextReader(responseStream)) { // Check for pagination var records = -1; var cursor = string.Empty; string start = null; string next = null; string prev = null; if (null != response.Headers["X-Records"]) { Int32.TryParse(response.Headers["X-Records"], out records); } var link = response.Headers["Link"]; if (!link.IsNullOrEmpty()) { start = link.GetUrlFromLinkHeader("start"); next = link.GetUrlFromLinkHeader("next"); prev = link.GetUrlFromLinkHeader("prev"); } if (records >= 0) { readXmlListDelegate(xmlReader, records, start, next, prev); } else if (response.StatusCode != HttpStatusCode.NoContent) { readXmlDelegate(xmlReader); } } } protected virtual void WritePostParameters(Stream outputStream, WriteXmlDelegate writeXmlDelegate) { using (var xmlWriter = new XmlTextWriter(outputStream, Encoding.UTF8)) { xmlWriter.WriteStartDocument(); xmlWriter.Formatting = Formatting.Indented; writeXmlDelegate(xmlWriter); xmlWriter.WriteEndDocument(); } #if (DEBUG) // Also copy XML to debug output Console.WriteLine("Sending Data:"); var s = new MemoryStream(); using (var xmlWriter = new XmlTextWriter(s, Encoding.UTF8)) { xmlWriter.WriteStartDocument(); xmlWriter.Formatting = Formatting.Indented; writeXmlDelegate(xmlWriter); xmlWriter.WriteEndDocument(); } Console.WriteLine(Encoding.UTF8.GetString(s.ToArray())); #endif } protected virtual MemoryStream CopyAndClose(Stream inputStream) { const int readSize = 256; var buffer = new byte[readSize]; var ms = new MemoryStream(); var count = inputStream.Read(buffer, 0, readSize); while (count > 0) { ms.Write(buffer, 0, count); count = inputStream.Read(buffer, 0, readSize); } ms.Position = 0; inputStream.Close(); return ms; } } }
/* Copyright (c) 2012 DEVSENSE Copyright (c) 2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.ComponentModel; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Diagnostics; using PHP.Core; using PHP.Core.Reflection; namespace PHP.Library.SPL { [ImplementsType] public interface ArrayAccess { [ImplementsMethod] object offsetGet(ScriptContext context, object index); [ImplementsMethod] object offsetSet(ScriptContext context, object index, object value); [ImplementsMethod] object offsetUnset(ScriptContext context, object index); [ImplementsMethod] object offsetExists(ScriptContext context, object index); } [ImplementsType] [Serializable] public class SplFixedArray : PhpObject, ArrayAccess, Iterator, Countable { /// <summary> /// Internal array storage. <c>null</c> reference if the size is <c>0</c>. /// </summary> protected object[] array = null; /// <summary> /// Iterator position in the array. /// </summary> private long position = 0; #region Helper methods protected void ReallocArray(long newsize) { Debug.Assert(newsize >= 0); // empty the array if (newsize == 0) { array = null; return; } // resize the array var newarray = new object[newsize]; // TODO: mark new elements as unsetted if (array == null) { array = newarray; } else { Array.Copy(array, newarray, Math.Min(array.LongLength, newarray.LongLength)); array = newarray; } } protected bool IsValidInternal() { return (position >= 0 && array != null && position < array.LongLength); } protected object SizeInternal() { return (array != null) ? ((array.LongLength <= int.MaxValue) ? array.Length : array.LongLength) : 0; } protected long ToLongHelper(object obj) { // allow only numeric types if (obj is long) return (long)obj; if (obj is int) return (int)obj; if (obj is bool) return (long)((bool)obj ? 1 : 0); if (obj is double) return unchecked((long)(double)obj); return -1; } protected void IndexCheckHelper(ScriptContext/*!*/context, long index) { if (index < 0 || array == null || index >= array.LongLength) { Exception.ThrowSplException( _ctx => new RuntimeException(_ctx, true), context, CoreResources.spl_index_invalid, 0, null); } } #endregion #region SplFixedArray /// <summary> /// Constructs an <see cref="SplFixedArray"/> object. /// </summary> /// <param name="context"></param> /// <param name="size">The initial array size.</param> /// <returns></returns> [ImplementsMethod] public virtual object __construct(ScriptContext/*!*/context, [Optional] object size /*= 0*/) { long nsize = (size == Arg.Default || size == Type.Missing) ? 0 : Core.Convert.ObjectToLongInteger(size); if (nsize < 0) { PhpException.InvalidArgument("size"); return null; } ReallocArray(nsize); return null; } [ImplementsMethod] public virtual object fromArray(ScriptContext/*!*/context, object data, [Optional]object save_indexes) { PhpArray arrdata = data as PhpArray; bool bindexes = (save_indexes == Arg.Default || save_indexes == Type.Missing) ? true : Core.Convert.ObjectToBoolean(save_indexes); if (arrdata == null || arrdata.Count == 0) { ReallocArray(0); } else if (bindexes) { if (arrdata.StringCount > 0) { // TODO: error return null; } //foreach (var pair in arrdata) // if (pair.Key.IsString || pair.Key.Integer < 0) ; // TODO: error ReallocArray(arrdata.MaxIntegerKey + 1); using (var enumerator = arrdata.GetFastEnumerator()) while (enumerator.MoveNext()) this.array[enumerator.CurrentKey.Integer] = enumerator.CurrentValue; } else //if (!bindexes) { ReallocArray(arrdata.Count); int i = 0; using (var enumerator = arrdata.GetFastEnumerator()) while (enumerator.MoveNext()) this.array[i++] = enumerator.CurrentValue; } return null; } [ImplementsMethod] public virtual object toArray(ScriptContext/*!*/context) { if (array == null) return new PhpArray(); Debug.Assert(array.LongLength <= int.MaxValue); PhpArray result = new PhpArray(array.Length, 0); for (int i = 0; i < array.Length; i++) result[i] = array[i]; return result; } [ImplementsMethod] public virtual object getSize(ScriptContext/*!*/context) { return SizeInternal(); } [ImplementsMethod] public virtual object setSize(ScriptContext/*!*/context, object size) { long newsize = Core.Convert.ObjectToLongInteger(size); if (newsize < 0) { // TODO: error } else { ReallocArray(newsize); } return null; } #endregion #region Implementation details internal static void __PopulateTypeDesc(PhpTypeDesc typeDesc) { throw new NotImplementedException(); } #region SplFixedArray /// <summary> /// For internal purposes only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public SplFixedArray(ScriptContext/*!*/context, bool newInstance) : base(context, newInstance) { } /// <summary> /// For internal purposes only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public SplFixedArray(ScriptContext/*!*/context, DTypeDesc caller) : base(context, caller) { } [EditorBrowsable(EditorBrowsableState.Never)] public static object __construct(object instance, PhpStack stack) { object size = stack.PeekValueOptional(1); stack.RemoveFrame(); return ((SplFixedArray)instance).__construct(stack.Context, size); } [EditorBrowsable(EditorBrowsableState.Never)] public static object fromArray(object instance, PhpStack stack) { object data = stack.PeekValue(1); object save_indexes = stack.PeekValueOptional(2); stack.RemoveFrame(); return ((SplFixedArray)instance).fromArray(stack.Context, data, save_indexes); } [EditorBrowsable(EditorBrowsableState.Never)] public static object toArray(object instance, PhpStack stack) { stack.RemoveFrame(); return ((SplFixedArray)instance).toArray(stack.Context); } [EditorBrowsable(EditorBrowsableState.Never)] public static object getSize(object instance, PhpStack stack) { stack.RemoveFrame(); return ((SplFixedArray)instance).getSize(stack.Context); } [EditorBrowsable(EditorBrowsableState.Never)] public static object setSize(object instance, PhpStack stack) { object size = stack.PeekValue(1); stack.RemoveFrame(); return ((SplFixedArray)instance).setSize(stack.Context, size); } #endregion #region interface Iterator [EditorBrowsable(EditorBrowsableState.Never)] public static object rewind(object instance, PhpStack stack) { stack.RemoveFrame(); return ((Iterator)instance).rewind(stack.Context); } [EditorBrowsable(EditorBrowsableState.Never)] public static object next(object instance, PhpStack stack) { stack.RemoveFrame(); return ((Iterator)instance).next(stack.Context); } [EditorBrowsable(EditorBrowsableState.Never)] public static object valid(object instance, PhpStack stack) { stack.RemoveFrame(); return ((Iterator)instance).valid(stack.Context); } [EditorBrowsable(EditorBrowsableState.Never)] public static object key(object instance, PhpStack stack) { stack.RemoveFrame(); return ((Iterator)instance).key(stack.Context); } [EditorBrowsable(EditorBrowsableState.Never)] public static object current(object instance, PhpStack stack) { stack.RemoveFrame(); return ((Iterator)instance).current(stack.Context); } #endregion #region interface ArrayAccess [EditorBrowsable(EditorBrowsableState.Never)] public static object offsetGet(object instance, PhpStack stack) { object index = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayAccess)instance).offsetGet(stack.Context, index); } [EditorBrowsable(EditorBrowsableState.Never)] public static object offsetSet(object instance, PhpStack stack) { object index = stack.PeekValue(1); object value = stack.PeekValue(2); stack.RemoveFrame(); return ((ArrayAccess)instance).offsetSet(stack.Context, index, value); } [EditorBrowsable(EditorBrowsableState.Never)] public static object offsetUnset(object instance, PhpStack stack) { object index = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayAccess)instance).offsetUnset(stack.Context, index); } [EditorBrowsable(EditorBrowsableState.Never)] public static object offsetExists(object instance, PhpStack stack) { object index = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayAccess)instance).offsetExists(stack.Context, index); } #endregion #region interface Countable [EditorBrowsable(EditorBrowsableState.Never)] public static object count(object instance, PhpStack stack) { stack.RemoveFrame(); return ((Countable)instance).count(stack.Context); } #endregion #endregion #region interface Iterator [ImplementsMethod] public object rewind(ScriptContext context) { position = 0; return null; } [ImplementsMethod] public object next(ScriptContext context) { position++; return null; } [ImplementsMethod] public virtual object valid(ScriptContext context) { return IsValidInternal(); } [ImplementsMethod] public virtual object key(ScriptContext context) { return ((position <= int.MaxValue) ? (int)position : position); } [ImplementsMethod] public virtual object current(ScriptContext context) { return IsValidInternal() ? array[position] : null; } #endregion #region interface ArrayAccess [ImplementsMethod] public virtual object offsetGet(ScriptContext context, object index) { long i = ToLongHelper(index); IndexCheckHelper(context, i); // throws if the index is out of range return array[i]; } [ImplementsMethod] public virtual object offsetSet(ScriptContext context, object index, object value) { long i = ToLongHelper(index); IndexCheckHelper(context, i); // throws if the index is out of range array[i] = value; return null; } [ImplementsMethod] public virtual object offsetUnset(ScriptContext context, object index) { return offsetSet(context, index, null); // TODO: mark unsetted element } [ImplementsMethod] public virtual object offsetExists(ScriptContext context, object index) { long i = ToLongHelper(index); return (i < 0 || array == null || i >= array.LongLength) ? false : (array[i] != null); // TODO: null does not correspond to unsetted element } #endregion #region interface Countable [ImplementsMethod] public virtual object count(ScriptContext context) { return SizeInternal(); } #endregion #region Serialization (CLR only) #if !SILVERLIGHT /// <summary> /// Deserializing constructor. /// </summary> protected SplFixedArray(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif #endregion } /// <summary> /// This class allows objects to work as arrays. /// </summary> [ImplementsType] [Serializable] public class ArrayObject : PhpObject, IteratorAggregate, Traversable, ArrayAccess, Serializable, Countable { #region Constants /// <summary> /// Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.). /// </summary> public const int STD_PROP_LIST = 1; /// <summary> /// Entries can be accessed as properties (read and write). /// </summary> public const int ARRAY_AS_PROPS = 2; #endregion #region Implementation details /// <summary> /// For internal purposes only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public ArrayObject(ScriptContext/*!*/context, bool newInstance) : base(context, newInstance) { } /// <summary> /// For internal purposes only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public ArrayObject(ScriptContext/*!*/context, DTypeDesc caller) : base(context, caller) { } internal static void __PopulateTypeDesc(PhpTypeDesc typeDesc) { throw new NotImplementedException(); } #endregion #region ArrayObject /// <summary> /// Construct a new array object. /// </summary> /// <param name="context">Script Context. Cannot be null.</param> /// <param name="input">Optional. The input parameter accepts an array or an Object.</param> /// <param name="flags">Optional. Flags to control the behaviour of the ArrayObject object. See ArrayObject::setFlags().</param> /// <param name="iterator_class">Optional. Specify the class that will be used for iteration of the ArrayObject object.</param> [ImplementsMethod] public virtual object __construct(ScriptContext/*!*/context, [Optional]object input, [Optional]object/*int*/flags/*= 0*/, [Optional]object/*string*/iterator_class/*= "ArrayIterator"*/ ) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object __construct(object instance, PhpStack stack) { var input = stack.PeekValueOptional(1); var flags = stack.PeekValueOptional(2); var iterator_class = stack.PeekValueOptional(3); stack.RemoveFrame(); return ((ArrayObject)instance).__construct(stack.Context, input, flags, iterator_class); } //public void append ( mixed $value ) //public array exchangeArray ( mixed $input ) //public array getArrayCopy ( void ) /// <summary> /// Appends a new value as the last element. /// </summary> /// <param name="context">Script Context. Cannot be null.</param> /// <param name="value">The value being appended.</param> /// <remarks>This method cannot be called when the ArrayObject was constructed from an object. Use ArrayObject::offsetSet() instead.</remarks> [ImplementsMethod] public virtual object append(ScriptContext context, object value) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object append(object instance, PhpStack stack) { var value = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayObject)instance).append(stack.Context, value); } /// <summary> /// Exchange the current array with another array or object. /// </summary> /// <param name="context">Script Context. Cannot be null.</param> /// <param name="input">The new array or object to exchange with the current array.</param> /// <returns>Returns the old array.</returns> [ImplementsMethod] public virtual object exchangeArray(ScriptContext context, object input) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object exchangeArray(object instance, PhpStack stack) { var input = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayObject)instance).exchangeArray(stack.Context, input); } /// <summary> /// Exports the ArrayObject to an array. /// </summary> /// <param name="context">Script Context. Cannot be null.</param> /// <returns>Returns a copy of the array. When the ArrayObject refers to an object an array of the public properties of that object will be returned.</returns> [ImplementsMethod] public virtual object getArrayCopy(ScriptContext context) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object getArrayCopy(object instance, PhpStack stack) { stack.RemoveFrame(); return ((ArrayObject)instance).getArrayCopy(stack.Context); } //public int getFlags ( void ) //public void setFlags ( int $flags ) /// <summary> /// Gets the behavior flags of the ArrayObject. See the ArrayObject::setFlags method for a list of the available flags. /// </summary> /// <param name="context">Script Context. Cannot be null.</param> /// <returns>Returns the behavior flags of the ArrayObject.</returns> [ImplementsMethod] public virtual object getFlags(ScriptContext context) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object getFlags(object instance, PhpStack stack) { stack.RemoveFrame(); return ((ArrayObject)instance).getFlags(stack.Context); } /// <summary> /// Set the flags that change the behavior of the ArrayObject. /// </summary> /// <param name="context">Script Context. Cannot be null.</param> /// <param name="flags">The new ArrayObject behavior. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions.</param> [ImplementsMethod] public virtual object setFlags(ScriptContext context, object/*int*/flags) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object setFlags(object instance, PhpStack stack) { var flags = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayObject)instance).setFlags(stack.Context, flags); } //public string getIteratorClass ( void ) //public void setIteratorClass ( string $iterator_class ) /// <summary> /// Gets the class name of the array iterator that is used by ArrayObject::getIterator(). /// </summary> /// <param name="context">Script Context. Cannot be null.</param> /// <returns>Returns the iterator class name that is used to iterate over this object.</returns> [ImplementsMethod] public virtual object getIteratorClass(ScriptContext context) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object getIteratorClass(object instance, PhpStack stack) { stack.RemoveFrame(); return ((ArrayObject)instance).getIteratorClass(stack.Context); } /// <summary> /// Sets the classname of the array iterator that is used by ArrayObject::getIterator(). /// </summary> /// <param name="context">Script Context. Cannot be null.</param> /// <param name="iterator_class">The classname of the array iterator to use when iterating over this object.</param> [ImplementsMethod] public virtual object setIteratorClass(ScriptContext context, object/*string*/iterator_class) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object setIteratorClass(object instance, PhpStack stack) { var iterator_class = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayObject)instance).setIteratorClass(stack.Context, iterator_class); } //public void asort ( void ) //public void ksort ( void ) //public void natcasesort ( void ) //public void natsort ( void ) /// <summary> /// Sorts the entries such that the keys maintain their correlation with the entries they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. /// </summary> [ImplementsMethod] public virtual object asort(ScriptContext context) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object asort(object instance, PhpStack stack) { stack.RemoveFrame(); return ((ArrayObject)instance).asort(stack.Context); } /// <summary> /// Sorts the entries by key, maintaining key to entry correlations. This is useful mainly for associative arrays. /// </summary> [ImplementsMethod] public virtual object ksort(ScriptContext context) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object ksort(object instance, PhpStack stack) { stack.RemoveFrame(); return ((ArrayObject)instance).ksort(stack.Context); } /// <summary> /// This method is a case insensitive version of ArrayObject::natsort. /// This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". /// </summary> [ImplementsMethod] public virtual object natcasesort(ScriptContext context) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object natcasesort(object instance, PhpStack stack) { stack.RemoveFrame(); return ((ArrayObject)instance).natcasesort(stack.Context); } /// <summary> /// This method implements a sort algorithm that orders alphanumeric strings in /// the way a human being would while maintaining key/value associations. This is /// described as a "natural ordering". An example of the difference between this /// algorithm and the regular computer string sorting algorithms (used in ArrayObject::asort) /// method can be seen in the example below. /// </summary> [ImplementsMethod] public virtual object natsort(ScriptContext context) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object natsort(object instance, PhpStack stack) { stack.RemoveFrame(); return ((ArrayObject)instance).natsort(stack.Context); } //public void uasort ( callable $cmp_function ) //public void uksort ( callable $cmp_function ) /// <summary> /// This function sorts the entries such that keys maintain their correlation with the entry that they are associated with, using a user-defined comparison function. /// This is used mainly when sorting associative arrays where the actual element order is significant. /// </summary> /// <param name="context">Script Context. Cannot be null.</param> /// <param name="cmp_function">Function cmp_function should accept two parameters /// which will be filled by pairs of entries. The comparison function must return /// an integer less than, equal to, or greater than zero if the first argument is /// considered to be respectively less than, equal to, or greater than the second.</param> [ImplementsMethod] public virtual object uasort(ScriptContext context, object/*callable*/cmp_function) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object uasort(object instance, PhpStack stack) { var cmp_function = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayObject)instance).uasort(stack.Context, cmp_function); } /// <summary> /// This function sorts the keys of the entries using a user-supplied comparison function. The key to entry correlations will be maintained. /// </summary> /// <param name="context">Script Context. Cannot be null.</param> /// <param name="cmp_function">The callback comparison function. /// Function cmp_function should accept two parameters which will be filled by /// pairs of entry keys. The comparison function must return an integer less than, /// equal to, or greater than zero if the first argument is considered to be /// respectively less than, equal to, or greater than the second.</param> [ImplementsMethod] public virtual object uksort(ScriptContext context, object/*callable*/cmp_function) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object uksort(object instance, PhpStack stack) { var cmp_function = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayObject)instance).uksort(stack.Context, cmp_function); } #endregion #region Serialization (CLR only) #if !SILVERLIGHT /// <summary> /// Deserializing constructor. /// </summary> protected ArrayObject(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif #endregion #region Serializable Members [ImplementsMethod] public virtual object serialize(ScriptContext context) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object serialize(object instance, PhpStack stack) { stack.RemoveFrame(); return ((ArrayObject)instance).serialize(stack.Context); } [ImplementsMethod] public virtual object unserialize(ScriptContext context, object data) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object unserialize(object instance, PhpStack stack) { var serialized = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayObject)instance).unserialize(stack.Context, serialized); } #endregion #region Countable Members [ImplementsMethod] public virtual object count(ScriptContext context) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object count(object instance, PhpStack stack) { stack.RemoveFrame(); return ((ArrayObject)instance).count(stack.Context); } #endregion #region IteratorAggregate Members [ImplementsMethod] public virtual object getIterator(ScriptContext context) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object getIterator(object instance, PhpStack stack) { stack.RemoveFrame(); return ((ArrayObject)instance).getIterator(stack.Context); } #endregion #region ArrayAccess Members [ImplementsMethod] public virtual object offsetGet(ScriptContext context, object index) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object offsetGet(object instance, PhpStack stack) { var index = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayObject)instance).offsetGet(stack.Context, index); } [ImplementsMethod] public virtual object offsetSet(ScriptContext context, object index, object value) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object offsetSet(object instance, PhpStack stack) { var index = stack.PeekValue(1); var value = stack.PeekValue(2); stack.RemoveFrame(); return ((ArrayObject)instance).offsetSet(stack.Context, index, value); } [ImplementsMethod] public virtual object offsetUnset(ScriptContext context, object index) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object offsetUnset(object instance, PhpStack stack) { var index = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayObject)instance).offsetUnset(stack.Context, index); } [ImplementsMethod] public virtual object offsetExists(ScriptContext context, object index) { throw new NotImplementedException(); } [EditorBrowsable(EditorBrowsableState.Never)] public static object offsetExists(object instance, PhpStack stack) { var index = stack.PeekValue(1); stack.RemoveFrame(); return ((ArrayObject)instance).offsetExists(stack.Context, index); } #endregion } internal class PhpArrayObject : PhpArray { internal DObject ArrayAccess { get { return arrayAccess; } } readonly private DObject arrayAccess/*!*/; internal const string offsetGet = "offsetGet"; internal const string offsetSet = "offsetSet"; internal const string offsetUnset = "offsetUnset"; internal const string offsetExists = "offsetExists"; /// <summary> /// Do not call base class since we don't need to initialize <see cref="PhpArray"/>. /// </summary> internal PhpArrayObject(DObject/*!*/ arrayAccess) { Debug.Assert(arrayAccess != null && arrayAccess.RealObject is ArrayAccess); this.arrayAccess = arrayAccess; } #region Operators protected override object GetArrayItemOverride(object key, bool quiet) { PhpStack stack = ScriptContext.CurrentContext.Stack; stack.AddFrame(key); return PhpVariable.Dereference(arrayAccess.InvokeMethod(offsetGet, null, stack.Context)); } protected override PhpReference GetArrayItemRefOverride() { return GetUserArrayItemRef(arrayAccess, null, ScriptContext.CurrentContext); } protected override PhpReference GetArrayItemRefOverride(object key) { return GetUserArrayItemRef(arrayAccess, key, ScriptContext.CurrentContext); } protected override PhpReference/*!*/ GetArrayItemRefOverride(int key) { return GetUserArrayItemRef(arrayAccess, key, ScriptContext.CurrentContext); } protected override PhpReference/*!*/ GetArrayItemRefOverride(string key) { return GetUserArrayItemRef(arrayAccess, key, ScriptContext.CurrentContext); } protected override void SetArrayItemOverride(object value) { PhpStack stack = ScriptContext.CurrentContext.Stack; stack.AddFrame(null, value); arrayAccess.InvokeMethod(offsetSet, null, stack.Context); } protected override void SetArrayItemOverride(object key, object value) { PhpStack stack = ScriptContext.CurrentContext.Stack; stack.AddFrame(key, value); arrayAccess.InvokeMethod(offsetSet, null, stack.Context); } protected override void SetArrayItemOverride(int key, object value) { SetArrayItemOverride((object)key, value); } protected override void SetArrayItemOverride(string key, object value) { SetArrayItemOverride((object)key, value); } protected override void SetArrayItemRefOverride(object key, PhpReference value) { PhpStack stack = ScriptContext.CurrentContext.Stack; stack.AddFrame(key, value); arrayAccess.InvokeMethod(offsetSet, null, stack.Context); } protected override PhpArray EnsureItemIsArrayOverride() { return EnsureIndexerResultIsRefArray(null); } protected override PhpArray EnsureItemIsArrayOverride(object key) { // an object behaving like an array: return EnsureIndexerResultIsRefArray(key); } protected override DObject EnsureItemIsObjectOverride(ScriptContext/*!*/ context) { return EnsureIndexerResultIsRefObject(null, context); } protected override DObject EnsureItemIsObjectOverride(object key, ScriptContext/*!*/ context) { return EnsureIndexerResultIsRefObject(key, context); } /// <summary> /// Calls the indexer (offsetGet) and ensures that its result is an array or can be converted to an array. /// </summary> /// <param name="key">A key passed to the indexer.</param> /// <returns>The array (either previously existing or a created one) or a <B>null</B> reference on error.</returns> /// <exception cref="PhpException">The indexer doesn't return a reference (Error).</exception> /// <exception cref="PhpException">The return value cannot be converted to an array (Warning).</exception> private PhpArray EnsureIndexerResultIsRefArray(object key) { PhpReference ref_result = GetUserArrayItemRef(arrayAccess, key, ScriptContext.CurrentContext); object new_value; var wrappedwarray = Operators.EnsureObjectIsArray(ref_result.Value, out new_value); if (wrappedwarray != null) { if (new_value != null) ref_result.Value = new_value; return wrappedwarray; } // the result is neither array nor object behaving like array: PhpException.VariableMisusedAsArray(ref_result.Value, false); return null; } /// <summary> /// Calls the indexer (offsetGet) and ensures that its result is an <see cref="DObject"/> or can be /// converted to <see cref="DObject"/>. /// </summary> /// <param name="key">A key passed to the indexer.</param> /// <param name="context">A script context.</param> /// <returns>The <see cref="DObject"/> (either previously existing or a created one) or a <B>null</B> reference on error.</returns> /// <exception cref="PhpException">The indexer doesn't return a reference (Error).</exception> /// <exception cref="PhpException">The return value cannot be converted to a DObject (Warning).</exception> private DObject EnsureIndexerResultIsRefObject(object key, ScriptContext/*!*/ context) { PhpReference ref_result = GetUserArrayItemRef(arrayAccess, key, context); // is the result an array: DObject result = ref_result.Value as DObject; if (result != null) return result; // is result empty => creates a new array and writes it back: if (Operators.IsEmptyForEnsure(ref_result.Value)) { ref_result.Value = result = stdClass.CreateDefaultObject(context); return result; } // the result is neither array nor object behaving like array not empty value: PhpException.VariableMisusedAsObject(ref_result.Value, false); return null; } internal static object GetUserArrayItem(DObject/*!*/ arrayAccess, object index, Operators.GetItemKinds kind) { PhpStack stack = ScriptContext.CurrentContext.Stack; switch (kind) { case Operators.GetItemKinds.Isset: // pass isset() ""/null to say true/false depending on the value returned from "offsetExists": stack.AddFrame(index); return Core.Convert.ObjectToBoolean(arrayAccess.InvokeMethod(offsetExists, null, stack.Context)) ? "" : null; case Operators.GetItemKinds.Empty: // if "offsetExists" returns false, the empty()/isset() returns false (pass null to say true/false): // otherwise, "offsetGet" is called to retrieve the value, which is passed to isset(): stack.AddFrame(index); if (!Core.Convert.ObjectToBoolean(arrayAccess.InvokeMethod(offsetExists, null, stack.Context))) return null; else goto default; default: // regular getter: stack.AddFrame(index); return PhpVariable.Dereference(arrayAccess.InvokeMethod(offsetGet, null, stack.Context)); } } /// <summary> /// Gets an item of a user array by invoking <see cref="Library.SPL.ArrayAccess.offsetGet"/>. /// </summary> /// <param name="arrayAccess">User array object.</param> /// <param name="index">An index.</param> /// <param name="context">The current script context.</param> /// <returns>A reference on item returned by the user getter.</returns> internal static PhpReference GetUserArrayItemRef(DObject/*!*/ arrayAccess, object index, ScriptContext/*!*/ context) { Debug.Assert(arrayAccess.RealObject is Library.SPL.ArrayAccess); Debug.Assert(!(index is PhpReference)); context.Stack.AddFrame(index); object result = arrayAccess.InvokeMethod(Library.SPL.PhpArrayObject.offsetGet, null, context); PhpReference ref_result = result as PhpReference; if (ref_result == null) { // obsolete (?): PhpException.Throw(PhpError.Error,CoreResources.GetString("offsetGet_must_return_byref")); ref_result = new PhpReference(result); } return ref_result; } #endregion } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections; using Common.Logging; using Spring.Context; using Spring.Context.Support; using Spring.Util; namespace Spring.Testing.Microsoft { /// <summary> /// Superclass for NUnit test cases using a Spring context. /// </summary> /// <remarks> /// <p>Maintains a cache of contexts by key. This has significant performance /// benefit if initializing the context would take time. While initializing a /// Spring context itself is very quick, some objects in a context, such as /// a LocalSessionFactoryObject for working with NHibernate, may take time to /// initialize. Hence it often makes sense to do that initializing once.</p> /// <p>Normally you won't extend this class directly but rather extend one /// of its subclasses.</p> /// </remarks> /// <author>Rod Johnson</author> /// <author>Aleksandar Seovic (.NET)</author> public abstract class AbstractSpringContextTests { /// <summary> /// Map of context keys returned by subclasses of this class, to /// Spring contexts. /// </summary> private static readonly IDictionary contextKeyToContextMap; /// <summary> /// Static ctor to avoid "beforeFieldInit" problem. /// </summary> static AbstractSpringContextTests() { contextKeyToContextMap = new Hashtable(); } /// <summary> /// Disposes any cached context instance and removes it from cache. /// </summary> public static void ClearContextCache() { foreach(IApplicationContext ctx in contextKeyToContextMap.Values) { ctx.Dispose(); } contextKeyToContextMap.Clear(); } /// <summary> /// Indicates, whether context instances should be automatically registered with the global <see cref="ContextRegistry"/>. /// </summary> private bool registerContextWithContextRegistry = true; /// <summary> /// Logger available to subclasses. /// </summary> protected readonly ILog logger; /// <summary> /// Default constructor for AbstractSpringContextTests. /// </summary> protected AbstractSpringContextTests() { logger = LogManager.GetLogger(GetType()); } /// <summary> /// Controls, whether application context instances will /// be registered/unregistered with the global <see cref="ContextRegistry"/>. /// Defaults to <c>true</c>. /// </summary> public bool RegisterContextWithContextRegistry { get { return registerContextWithContextRegistry; } set { registerContextWithContextRegistry = value; } } /// <summary> /// Set custom locations dirty. This will cause them to be reloaded /// from the cache before the next test case is executed. /// </summary> /// <remarks> /// Call this method only if you change the state of a singleton /// object, potentially affecting future tests. /// </remarks> /// <param name="locations">Locations </param> protected void SetDirty(string[] locations) { String keyString = ContextKeyString(locations); IConfigurableApplicationContext ctx = (IConfigurableApplicationContext) contextKeyToContextMap[keyString]; contextKeyToContextMap.Remove(keyString); if (ctx != null) { ctx.Dispose(); } } /// <summary> /// Returns <c>true</c> if context for the specified /// <paramref name="contextKey"/> is cached. /// </summary> /// <param name="contextKey">Context key to check.</param> /// <returns> /// <c>true</c> if context for the specified /// <paramref name="contextKey"/> is cached, /// <c>false</c> otherwise. /// </returns> protected bool HasCachedContext(object contextKey) { string keyString = ContextKeyString(contextKey); return contextKeyToContextMap.Contains(keyString); } /// <summary> /// Converts context key to string. /// </summary> /// <remarks> /// Subclasses can override this to return a string representation of /// their contextKey for use in logging. /// </remarks> /// <param name="contextKey">Context key to convert.</param> /// <returns> /// String representation of the specified <paramref name="contextKey"/>. Null if /// contextKey is null. /// </returns> protected virtual string ContextKeyString(object contextKey) { if (contextKey == null) { return null; } if (contextKey is string[]) { return StringUtils.CollectionToCommaDelimitedString((string[])contextKey); } else { return contextKey.ToString(); } } /// <summary> /// Caches application context. /// </summary> /// <param name="key">Key to use.</param> /// <param name="context">Context to cache.</param> public void AddContext(object key, IConfigurableApplicationContext context) { AssertUtils.ArgumentNotNull(context, "context", "ApplicationContext must not be null"); string keyString = ContextKeyString(key); contextKeyToContextMap.Add(keyString, context); if (RegisterContextWithContextRegistry && !ContextRegistry.IsContextRegistered(context.Name)) { ContextRegistry.RegisterContext(context); } } /// <summary> /// Returns cached context if present, or loads it if not. /// </summary> /// <param name="key">Context key.</param> /// <returns>Spring application context associated with the specified key.</returns> protected IConfigurableApplicationContext GetContext(object key) { string keyString = ContextKeyString(key); IConfigurableApplicationContext ctx = (IConfigurableApplicationContext) contextKeyToContextMap[keyString]; if (ctx == null) { if (key is string[]) { ctx = LoadContextLocations((string[]) key); } else { ctx = LoadContext(key); } AddContext(key, ctx); } return ctx; } /// <summary> /// Loads application context from the specified resource locations. /// </summary> /// <param name="locations">Resources to load object definitions from.</param> protected virtual IConfigurableApplicationContext LoadContextLocations(string[] locations) { if (logger.IsInfoEnabled) { logger.Info("Loading config for: " + StringUtils.CollectionToCommaDelimitedString(locations)); } return new XmlApplicationContext(locations); } /// <summary> /// Loads application context based on user-defined key. /// </summary> /// <remarks> /// Unless overriden by the user, this method will alway throw /// a <see cref="NotSupportedException"/>. /// </remarks> /// <param name="key">User-defined key.</param> protected virtual IConfigurableApplicationContext LoadContext(object key) { throw new NotSupportedException("Subclasses may override this"); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using TelerikAcademyForum.Services.Areas.HelpPage.Models; namespace TelerikAcademyForum.Services.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; using System.Text; using System.IO; using System.Reflection; using fyiReporting.RDL; namespace fyiReporting.RdlDesign { /// <summary> /// CustomReportItemCtl provides property values for a CustomReportItem /// </summary> internal class CustomReportItemCtl : System.Windows.Forms.UserControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; private string _Type; private PropertyGrid pgProps; private Button bExpr; private XmlNode _RiNode; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal CustomReportItemCtl(DesignXmlDraw dxDraw, List<XmlNode> reportItems) { _Draw = dxDraw; this._ReportItems = reportItems; _Type = _Draw.GetElementValue(_ReportItems[0], "Type", ""); // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { ICustomReportItem cri=null; try { cri = RdlEngineConfig.CreateCustomReportItem(_Type); _RiNode = _Draw.GetNamedChildNode(_ReportItems[0], "CustomProperties").Clone(); object props = cri.GetPropertiesInstance(_RiNode); pgProps.SelectedObject = props; } catch { return; } finally { if (cri != null) cri.Dispose(); } } /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pgProps = new System.Windows.Forms.PropertyGrid(); this.bExpr = new System.Windows.Forms.Button(); this.SuspendLayout(); // // pgProps // this.pgProps.Location = new System.Drawing.Point(13, 17); this.pgProps.Name = "pgProps"; this.pgProps.Size = new System.Drawing.Size(406, 260); this.pgProps.TabIndex = 3; // // bExpr // this.bExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bExpr.Location = new System.Drawing.Point(422, 57); this.bExpr.Name = "bExpr"; this.bExpr.Size = new System.Drawing.Size(22, 16); this.bExpr.TabIndex = 4; this.bExpr.Tag = "sd"; this.bExpr.Text = "fx"; this.bExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bExpr.Click += new System.EventHandler(this.bExpr_Click); // // CustomReportItemCtl // this.Controls.Add(this.bExpr); this.Controls.Add(this.pgProps); this.Name = "CustomReportItemCtl"; this.Size = new System.Drawing.Size(464, 304); this.ResumeLayout(false); } #endregion public bool IsValid() { return true; } public void Apply() { ICustomReportItem cri = null; try { cri = RdlEngineConfig.CreateCustomReportItem(_Type); foreach (XmlNode node in _ReportItems) { cri.SetPropertiesInstance(_Draw.GetNamedChildNode(node, "CustomProperties"), pgProps.SelectedObject); } } catch { return; } finally { if (cri != null) cri.Dispose(); } return; } private void bExpr_Click(object sender, EventArgs e) { GridItem gi = this.pgProps.SelectedGridItem; XmlNode sNode = _ReportItems[0]; DialogExprEditor ee = new DialogExprEditor(_Draw, gi.Value.ToString(), sNode, false); try { DialogResult dr = ee.ShowDialog(); if (dr == DialogResult.OK) { // There's probably a better way without reflection but this works fine. string nm = gi.Label; object sel = pgProps.SelectedObject; Type t = sel.GetType(); PropertyInfo pi = t.GetProperty(nm); MethodInfo mi = pi.GetSetMethod(); object[] oa = new object[1]; oa[0] = ee.Expression; mi.Invoke(sel, oa); gi.Select(); } } finally { ee.Dispose(); } } } }
using System; using System.Windows; using System.Windows.Forms; using System.Drawing; using Microsoft.Win32; namespace Earlab { /// <summary> /// Summary description for RegistryParameters. /// </summary> public class RegistryParameter { private RegistryKey mRegistryKey = null; private string mParameterName = null; private Object mParameter; private Object mDefault; public RegistryParameter(RegistryKey theKey, string ParameterName) { Initialize(theKey, ParameterName, null); } public RegistryParameter(RegistryKey theKey, string ParameterName, Object DefaultValue) { Initialize(theKey, ParameterName, DefaultValue); } private void Initialize(RegistryKey theKey, string ParameterName, Object DefaultValue) { // Remember parameters mRegistryKey = theKey; mParameterName = ParameterName; mDefault = DefaultValue; // Check parameters if (mRegistryKey == null) throw new ApplicationException("RegistryParameter: RegistryKey cannot be null"); if (mParameterName == null) throw new ApplicationException("RegistryParameter: ParameterName cannot be null"); // Load the value from the registry try { mParameter = mRegistryKey.GetValue(mParameterName, mDefault); } catch (ArgumentException) { mParameter = mDefault; } } public Object Value { set { mParameter = value; mRegistryKey.SetValue(mParameterName, mParameter); } get { return mParameter; } } } public class RegistryString: RegistryParameter { public RegistryString(RegistryKey theKey, string ParameterName, string DefaultValue) : base(theKey, ParameterName, DefaultValue){} public RegistryString(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){} public new string Value { set {base.Value = value;} get {return (string)base.Value;} } } public class RegistryInt: RegistryParameter { public RegistryInt(RegistryKey theKey, string ParameterName, int DefaultValue) : base(theKey, ParameterName, (object)DefaultValue){} public RegistryInt(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){} public new int Value { set {base.Value = (Object)value;} get {return (int)base.Value;} } } public class RegistryBool: RegistryParameter { public RegistryBool(RegistryKey theKey, string ParameterName, bool DefaultValue) : base(theKey, ParameterName, (object)DefaultValue){} public RegistryBool(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){} public new bool Value { set {base.Value = (Object)value;} get {return bool.Parse(base.Value.ToString());} } } public class RegistryFloat: RegistryParameter { public RegistryFloat(RegistryKey theKey, string ParameterName, float DefaultValue) : base(theKey, ParameterName, (object)DefaultValue){} public RegistryFloat(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){} public new float Value { set {base.Value = (Object)value;} get {return (float)base.Value;} } } public class RegistryDouble: RegistryParameter { public RegistryDouble(RegistryKey theKey, string ParameterName, double DefaultValue) : base(theKey, ParameterName, (object)DefaultValue){} public RegistryDouble(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){} public new double Value { set {base.Value = (Object)value;} get {return (double)base.Value;} } } public class RegistryPoint { private RegistryInt X, Y; public RegistryPoint(RegistryKey theKey, string ParameterName, Point DefaultValue) { Init(theKey, ParameterName, DefaultValue); } public RegistryPoint(RegistryKey theKey, string ParameterName) { Init(theKey, ParameterName, new Point(0, 0)); } private void Init(RegistryKey theKey, string ParameterName, Point DefaultValue) { X = new RegistryInt(theKey, ParameterName + "_X", DefaultValue.X); Y = new RegistryInt(theKey, ParameterName + "_Y", DefaultValue.Y); } public Point Value { set { X.Value = value.X; Y.Value = value.Y; } get {return new Point(X.Value, Y.Value);} } } public class RegistrySize { private RegistryInt Width, Height; public RegistrySize(RegistryKey theKey, string ParameterName, Size DefaultValue) { Init(theKey, ParameterName, DefaultValue); } public RegistrySize(RegistryKey theKey, string ParameterName) { Init(theKey, ParameterName, new Size(0, 0)); } private void Init(RegistryKey theKey, string ParameterName, Size DefaultValue) { Width = new RegistryInt(theKey, ParameterName + "_Width", DefaultValue.Width); Height = new RegistryInt(theKey, ParameterName + "_Height", DefaultValue.Height); } public Size Value { set { Width.Value = value.Width; Height.Value = value.Height; } get {return new Size(Width.Value, Height.Value);} } } public class RegistryRectangle { private RegistryPoint Location; private RegistrySize Size; public RegistryRectangle(RegistryKey theKey, string ParameterName, Rectangle DefaultValue) { Init(theKey, ParameterName, DefaultValue); } public RegistryRectangle(RegistryKey theKey, string ParameterName) { Init(theKey, ParameterName, new Rectangle(0, 0, 0, 0)); } private void Init(RegistryKey theKey, string ParameterName, Rectangle DefaultValue) { Location = new RegistryPoint(theKey, ParameterName + "_Location", DefaultValue.Location); Size = new RegistrySize(theKey, ParameterName + "_Size", DefaultValue.Size); } public Rectangle Value { set { Location.Value = value.Location; Size.Value = value.Size; } get {return new Rectangle(Location.Value, Size.Value);} } } public class RegistryFormWindowState: RegistryParameter { public RegistryFormWindowState(RegistryKey theKey, string ParameterName, FormWindowState DefaultValue) : base(theKey, ParameterName, (object)DefaultValue){} public RegistryFormWindowState(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){} public new FormWindowState Value { set {base.Value = (Object)((int)value);} get {return (FormWindowState)base.Value;} } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Collections.Specialized; // DEBUG ON using System.Diagnostics; // DEBUG OFF using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Services.Connectors.SimianGrid { /// <summary> /// Connects avatar appearance data to the SimianGrid backend /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianAvatarServiceConnector")] public class SimianAvatarServiceConnector : IAvatarService, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // private static string ZeroID = UUID.Zero.ToString(); private string m_serverUrl = String.Empty; private bool m_Enabled = false; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void Close() { } public SimianAvatarServiceConnector() { } public string Name { get { return "SimianAvatarServiceConnector"; } } public void AddRegion(Scene scene) { if (m_Enabled) { scene.RegisterModuleInterface<IAvatarService>(this); } } public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IAvatarService>(this); } } #endregion ISharedRegionModule public SimianAvatarServiceConnector(IConfigSource source) { CommonInit(source); } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AvatarServices", ""); if (name == Name) CommonInit(source); } } private void CommonInit(IConfigSource source) { IConfig gridConfig = source.Configs["AvatarService"]; if (gridConfig != null) { string serviceUrl = gridConfig.GetString("AvatarServerURI"); if (!String.IsNullOrEmpty(serviceUrl)) { if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("=")) serviceUrl = serviceUrl + '/'; m_serverUrl = serviceUrl; m_Enabled = true; } } if (String.IsNullOrEmpty(m_serverUrl)) m_log.Info("[SIMIAN AVATAR CONNECTOR]: No AvatarServerURI specified, disabling connector"); } #region IAvatarService // <summary> // Retrieves the LLPackedAppearance field from user data and unpacks // it into an AvatarAppearance structure // </summary> // <param name="userID"></param> public AvatarAppearance GetAppearance(UUID userID) { NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { OSDMap map = null; try { map = OSDParser.DeserializeJson(response["LLPackedAppearance"].AsString()) as OSDMap; } catch { } if (map != null) { AvatarAppearance appearance = new AvatarAppearance(map); // DEBUG ON m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR] retrieved appearance for {0}:\n{1}",userID,appearance.ToString()); // DEBUG OFF return appearance; } m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to decode appearance for {0}",userID); return null; } m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to get appearance for {0}: {1}", userID,response["Message"].AsString()); return null; } // <summary> // </summary> // <param name=""></param> public bool SetAppearance(UUID userID, AvatarAppearance appearance) { OSDMap map = appearance.Pack(); if (map == null) { m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to encode appearance for {0}",userID); return false; } // m_log.DebugFormat("[SIMIAN AVATAR CONNECTOR] save appearance for {0}",userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "LLPackedAppearance", OSDParser.SerializeJsonString(map) } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (! success) m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to save appearance for {0}: {1}", userID,response["Message"].AsString()); return success; } // <summary> // </summary> // <param name=""></param> public AvatarData GetAvatar(UUID userID) { NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { OSDMap map = null; try { map = OSDParser.DeserializeJson(response["LLAppearance"].AsString()) as OSDMap; } catch { } if (map != null) { AvatarWearable[] wearables = new AvatarWearable[13]; wearables[0] = new AvatarWearable(map["ShapeItem"].AsUUID(), map["ShapeAsset"].AsUUID()); wearables[1] = new AvatarWearable(map["SkinItem"].AsUUID(), map["SkinAsset"].AsUUID()); wearables[2] = new AvatarWearable(map["HairItem"].AsUUID(), map["HairAsset"].AsUUID()); wearables[3] = new AvatarWearable(map["EyesItem"].AsUUID(), map["EyesAsset"].AsUUID()); wearables[4] = new AvatarWearable(map["ShirtItem"].AsUUID(), map["ShirtAsset"].AsUUID()); wearables[5] = new AvatarWearable(map["PantsItem"].AsUUID(), map["PantsAsset"].AsUUID()); wearables[6] = new AvatarWearable(map["ShoesItem"].AsUUID(), map["ShoesAsset"].AsUUID()); wearables[7] = new AvatarWearable(map["SocksItem"].AsUUID(), map["SocksAsset"].AsUUID()); wearables[8] = new AvatarWearable(map["JacketItem"].AsUUID(), map["JacketAsset"].AsUUID()); wearables[9] = new AvatarWearable(map["GlovesItem"].AsUUID(), map["GlovesAsset"].AsUUID()); wearables[10] = new AvatarWearable(map["UndershirtItem"].AsUUID(), map["UndershirtAsset"].AsUUID()); wearables[11] = new AvatarWearable(map["UnderpantsItem"].AsUUID(), map["UnderpantsAsset"].AsUUID()); wearables[12] = new AvatarWearable(map["SkirtItem"].AsUUID(), map["SkirtAsset"].AsUUID()); AvatarAppearance appearance = new AvatarAppearance(); appearance.Wearables = wearables; appearance.AvatarHeight = (float)map["Height"].AsReal(); AvatarData avatar = new AvatarData(appearance); // Get attachments map = null; try { map = OSDParser.DeserializeJson(response["LLAttachments"].AsString()) as OSDMap; } catch { } if (map != null) { foreach (KeyValuePair<string, OSD> kvp in map) avatar.Data[kvp.Key] = kvp.Value.AsString(); } return avatar; } else { m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed to get user appearance for " + userID + ", LLAppearance is missing or invalid"); return null; } } else { m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed to get user appearance for " + userID + ": " + response["Message"].AsString()); } return null; } // <summary> // </summary> // <param name=""></param> public bool SetAvatar(UUID userID, AvatarData avatar) { m_log.Debug("[SIMIAN AVATAR CONNECTOR]: SetAvatar called for " + userID); if (avatar.AvatarType == 1) // LLAvatar { AvatarAppearance appearance = avatar.ToAvatarAppearance(); OSDMap map = new OSDMap(); map["Height"] = OSD.FromReal(appearance.AvatarHeight); map["BodyItem"] = appearance.Wearables[AvatarWearable.BODY][0].ItemID.ToString(); map["EyesItem"] = appearance.Wearables[AvatarWearable.EYES][0].ItemID.ToString(); map["GlovesItem"] = appearance.Wearables[AvatarWearable.GLOVES][0].ItemID.ToString(); map["HairItem"] = appearance.Wearables[AvatarWearable.HAIR][0].ItemID.ToString(); map["JacketItem"] = appearance.Wearables[AvatarWearable.JACKET][0].ItemID.ToString(); map["PantsItem"] = appearance.Wearables[AvatarWearable.PANTS][0].ItemID.ToString(); map["ShirtItem"] = appearance.Wearables[AvatarWearable.SHIRT][0].ItemID.ToString(); map["ShoesItem"] = appearance.Wearables[AvatarWearable.SHOES][0].ItemID.ToString(); map["SkinItem"] = appearance.Wearables[AvatarWearable.SKIN][0].ItemID.ToString(); map["SkirtItem"] = appearance.Wearables[AvatarWearable.SKIRT][0].ItemID.ToString(); map["SocksItem"] = appearance.Wearables[AvatarWearable.SOCKS][0].ItemID.ToString(); map["UnderPantsItem"] = appearance.Wearables[AvatarWearable.UNDERPANTS][0].ItemID.ToString(); map["UnderShirtItem"] = appearance.Wearables[AvatarWearable.UNDERSHIRT][0].ItemID.ToString(); map["BodyAsset"] = appearance.Wearables[AvatarWearable.BODY][0].AssetID.ToString(); map["EyesAsset"] = appearance.Wearables[AvatarWearable.EYES][0].AssetID.ToString(); map["GlovesAsset"] = appearance.Wearables[AvatarWearable.GLOVES][0].AssetID.ToString(); map["HairAsset"] = appearance.Wearables[AvatarWearable.HAIR][0].AssetID.ToString(); map["JacketAsset"] = appearance.Wearables[AvatarWearable.JACKET][0].AssetID.ToString(); map["PantsAsset"] = appearance.Wearables[AvatarWearable.PANTS][0].AssetID.ToString(); map["ShirtAsset"] = appearance.Wearables[AvatarWearable.SHIRT][0].AssetID.ToString(); map["ShoesAsset"] = appearance.Wearables[AvatarWearable.SHOES][0].AssetID.ToString(); map["SkinAsset"] = appearance.Wearables[AvatarWearable.SKIN][0].AssetID.ToString(); map["SkirtAsset"] = appearance.Wearables[AvatarWearable.SKIRT][0].AssetID.ToString(); map["SocksAsset"] = appearance.Wearables[AvatarWearable.SOCKS][0].AssetID.ToString(); map["UnderPantsAsset"] = appearance.Wearables[AvatarWearable.UNDERPANTS][0].AssetID.ToString(); map["UnderShirtAsset"] = appearance.Wearables[AvatarWearable.UNDERSHIRT][0].AssetID.ToString(); OSDMap items = new OSDMap(); foreach (KeyValuePair<string, string> kvp in avatar.Data) { if (kvp.Key.StartsWith("_ap_")) items.Add(kvp.Key, OSD.FromString(kvp.Value)); } NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "LLAppearance", OSDParser.SerializeJsonString(map) }, { "LLAttachments", OSDParser.SerializeJsonString(items) } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed saving appearance for " + userID + ": " + response["Message"].AsString()); return success; } else { m_log.Error("[SIMIAN AVATAR CONNECTOR]: Can't save appearance for " + userID + ". Unhandled avatar type " + avatar.AvatarType); return false; } } public bool ResetAvatar(UUID userID) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: ResetAvatar called for " + userID + ", implement this"); return false; } public bool SetItems(UUID userID, string[] names, string[] values) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: SetItems called for " + userID + " with " + names.Length + " names and " + values.Length + " values, implement this"); return false; } public bool RemoveItems(UUID userID, string[] names) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: RemoveItems called for " + userID + " with " + names.Length + " names, implement this"); return false; } #endregion IAvatarService } }
// 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.Threading; using System.Threading.Tasks; using System.Windows.Automation; using EnvDTE; using Microsoft.PythonTools; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Document; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudioTools.VSTestHost; using TestUtilities; using TestUtilities.Python; using TestUtilities.UI; using TestUtilities.UI.Python; namespace PythonToolsUITests { [TestClass] public class FormattingUITests { [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); PythonTestData.Deploy(); } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ToggleableOptionTest() { using (var app = new PythonVisualStudioApp()) { var pyService = app.ServiceProvider.GetPythonToolsService(); pyService.SetFormattingOption("SpaceBeforeClassDeclarationParen", true); foreach (var expectedResult in new bool?[] { false, null, true }) { using (var dialog = ToolsOptionsDialog.FromDte(app)) { dialog.SelectedView = "Text Editor/Python/Formatting/Spacing"; var spacingView = FormattingOptionsTreeView.FromDialog(dialog); var value = spacingView.WaitForItem( "Class Definitions", "Insert space between a class declaration's name and bases list" ); Assert.IsNotNull(value, "Did not find item"); value.SetFocus(); Mouse.MoveTo(value.GetClickablePoint()); Mouse.Click(System.Windows.Input.MouseButton.Left); dialog.OK(); Assert.AreEqual( expectedResult, pyService.GetFormattingOption("SpaceBeforeClassDeclarationParen") ); } } } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void FormatDocument() { FormattingTest("document.py", null, @"# the quick brown fox jumped over the slow lazy dog the quick brown fox jumped # over the slow lazy dog def f(): pass # short comment def g(): pass", new[] { Span.FromBounds(0, 78), Span.FromBounds(80, 186) }); } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void FormatSelection() { FormattingTest("selection.py", new Span(0, 121), @"# the quick brown fox jumped over the slow lazy dog the quick brown fox jumped # over the slow lazy dog def f(): pass # short comment def g(): pass", new[] { Span.FromBounds(0, 78), Span.FromBounds(80, 186) }); } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void FormatSelectionNoSelection() { FormattingTest("selection2.py", new Span(5, 0), @"x=1 y=2 z=3", new Span[0]); } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void FormatReduceLines() { var pyService = VSTestContext.ServiceProvider.GetPythonToolsService(); pyService.SetFormattingOption("SpacesAroundBinaryOperators", true); FormattingTest("linereduction.py", null, "(a + b + c + d + e + f)\r\n", new[] { new Span(0, 23), Span.FromBounds(25, 50) }); } /// <summary> /// Runs a single formatting test /// </summary> /// <param name="filename">The filename of the document to perform formatting in (lives in FormattingTests.sln)</param> /// <param name="selection">The selection to format, or null if formatting the entire document</param> /// <param name="expectedText">The expected source code after the formatting</param> /// <param name="changedSpans">The spans which should be marked as changed in the buffer after formatting</param> private static void FormattingTest(string filename, Span? selection, string expectedText, Span[] changedSpans) { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\FormattingTests\FormattingTests.sln"); var item = project.ProjectItems.Item(filename); var window = item.Open(); window.Activate(); var doc = app.GetDocument(item.Document.FullName); var aggFact = app.ComponentModel.GetService<IViewTagAggregatorFactoryService>(); var changeTags = aggFact.CreateTagAggregator<ChangeTag>(doc.TextView); // format the selection or document if (selection == null) { DoFormatDocument(); } else { doc.Invoke(() => doc.TextView.Selection.Select(new SnapshotSpan(doc.TextView.TextBuffer.CurrentSnapshot, selection.Value), false)); DoFormatSelection(); } // verify the contents are correct string actual = null; for (int i = 0; i < 100; i++) { actual = doc.TextView.TextBuffer.CurrentSnapshot.GetText(); if (expectedText == actual) { break; } System.Threading.Thread.Sleep(100); } Assert.AreEqual(expectedText, actual); // verify the change tags are correct var snapshot = doc.TextView.TextBuffer.CurrentSnapshot; var tags = changeTags.GetTags( new SnapshotSpan( doc.TextView.TextBuffer.CurrentSnapshot, new Span(0, doc.TextView.TextBuffer.CurrentSnapshot.Length) ) ); List<Span> result = new List<Span>(); foreach (var tag in tags) { result.Add( new Span( tag.Span.Start.GetPoint(doc.TextView.TextBuffer.CurrentSnapshot, PositionAffinity.Successor).Value.Position, tag.Span.End.GetPoint(doc.TextView.TextBuffer.CurrentSnapshot, PositionAffinity.Successor).Value.Position ) ); } // dump the spans for creating tests easier foreach (var span in result) { Console.WriteLine(span); } Assert.AreEqual(result.Count, changedSpans.Length); for (int i = 0; i < result.Count; i++) { Assert.AreEqual(result[i], changedSpans[i]); } } } private static void DoFormatSelection() { try { Task.Factory.StartNew(() => { for (int i = 0; i < 3; i++) { try { // wait for the command to become available if it's not already VSTestContext.DTE.ExecuteCommand("Edit.FormatSelection"); return; } catch { System.Threading.Thread.Sleep(1000); } } throw new Exception(); }).Wait(); } catch { Assert.Fail("Failed to format selection"); } } private static void DoFormatDocument() { try { Task.Factory.StartNew(() => { for (int i = 0; i < 3; i++) { try { // wait for the command to become available if it's not already VSTestContext.DTE.ExecuteCommand("Edit.FormatDocument"); return; } catch { System.Threading.Thread.Sleep(1000); } } throw new Exception(); }).Wait(); } catch { Assert.Fail("Failed to format document"); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; namespace Prism.Regions { /// <summary> /// Implementation of <see cref="IViewsCollection"/> that takes an <see cref="ObservableCollection{T}"/> of <see cref="ItemMetadata"/> /// and filters it to display an <see cref="INotifyCollectionChanged"/> collection of /// <see cref="object"/> elements (the items which the <see cref="ItemMetadata"/> wraps). /// </summary> public class ViewsCollection : IViewsCollection { private readonly ObservableCollection<ItemMetadata> subjectCollection; private readonly Dictionary<ItemMetadata, MonitorInfo> monitoredItems = new Dictionary<ItemMetadata, MonitorInfo>(); private readonly Predicate<ItemMetadata> filter; private Comparison<object> sort; private List<object> filteredItems = new List<object>(); /// <summary> /// Initializes a new instance of the <see cref="ViewsCollection"/> class. /// </summary> /// <param name="list">The list to wrap and filter.</param> /// <param name="filter">A predicate to filter the <paramref name="list"/> collection.</param> public ViewsCollection(ObservableCollection<ItemMetadata> list, Predicate<ItemMetadata> filter) { this.subjectCollection = list; this.filter = filter; this.MonitorAllMetadataItems(); this.subjectCollection.CollectionChanged += this.SourceCollectionChanged; this.UpdateFilteredItemsList(); } /// <summary> /// Occurs when the collection changes. /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged; /// <summary> /// Gets or sets the comparison used to sort the views. /// </summary> /// <value>The comparison to use.</value> public Comparison<object> SortComparison { get { return this.sort; } set { if (this.sort != value) { this.sort = value; this.UpdateFilteredItemsList(); this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } } /// <summary> /// Determines whether the collection contains a specific value. /// </summary> /// <param name="value">The object to locate in the collection.</param> /// <returns><see langword="true" /> if <paramref name="value"/> is found in the collection; otherwise, <see langword="false" />.</returns> public bool Contains(object value) { return this.filteredItems.Contains(value); } ///<summary> ///Returns an enumerator that iterates through the collection. ///</summary> ///<returns> ///A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. ///</returns> public IEnumerator<object> GetEnumerator() { return this.filteredItems.GetEnumerator(); } ///<summary> ///Returns an enumerator that iterates through a collection. ///</summary> ///<returns> ///An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. ///</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Used to invoked the <see cref="CollectionChanged"/> event. /// </summary> /// <param name="e"></param> private void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { NotifyCollectionChangedEventHandler handler = this.CollectionChanged; if (handler != null) handler(this, e); } private void NotifyReset() { this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } /// <summary> /// Removes all monitoring of underlying MetadataItems and re-adds them. /// </summary> private void ResetAllMonitors() { this.RemoveAllMetadataMonitors(); this.MonitorAllMetadataItems(); } /// <summary> /// Adds all underlying MetadataItems to the list from the subjectCollection /// </summary> private void MonitorAllMetadataItems() { foreach (var item in this.subjectCollection) { this.AddMetadataMonitor(item, this.filter(item)); } } /// <summary> /// Removes all monitored items from our monitoring list. /// </summary> private void RemoveAllMetadataMonitors() { foreach (var item in this.monitoredItems) { item.Key.MetadataChanged -= this.OnItemMetadataChanged; } this.monitoredItems.Clear(); } /// <summary> /// Adds handler to monitor the MetadatItem and adds it to our monitoring list. /// </summary> /// <param name="itemMetadata"></param> /// <param name="isInList"></param> private void AddMetadataMonitor(ItemMetadata itemMetadata, bool isInList) { itemMetadata.MetadataChanged += this.OnItemMetadataChanged; this.monitoredItems.Add( itemMetadata, new MonitorInfo { IsInList = isInList }); } /// <summary> /// Unhooks from the MetadataItem change event and removes from our monitoring list. /// </summary> /// <param name="itemMetadata"></param> private void RemoveMetadataMonitor(ItemMetadata itemMetadata) { itemMetadata.MetadataChanged -= this.OnItemMetadataChanged; this.monitoredItems.Remove(itemMetadata); } /// <summary> /// Invoked when any of the underlying ItemMetadata items we're monitoring changes. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnItemMetadataChanged(object sender, EventArgs e) { ItemMetadata itemMetadata = (ItemMetadata) sender; // Our monitored item may have been removed during another event before // our OnItemMetadataChanged got called back, so it's not unexpected // that we may not have it in our list. MonitorInfo monitorInfo; bool foundInfo = this.monitoredItems.TryGetValue(itemMetadata, out monitorInfo); if (!foundInfo) return; if (this.filter(itemMetadata)) { if (!monitorInfo.IsInList) { // This passes our filter and wasn't marked // as in our list so we can consider this // an Add. monitorInfo.IsInList = true; this.UpdateFilteredItemsList(); NotifyAdd(itemMetadata.Item); } } else { // This doesn't fit our filter, we remove from our // tracking list, but should not remove any monitoring in // case it fits our filter in the future. monitorInfo.IsInList = false; this.RemoveFromFilteredList(itemMetadata.Item); } } /// <summary> /// The event handler due to changes in the underlying collection. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: this.UpdateFilteredItemsList(); foreach (ItemMetadata itemMetadata in e.NewItems) { bool isInFilter = this.filter(itemMetadata); this.AddMetadataMonitor(itemMetadata, isInFilter); if (isInFilter) { NotifyAdd(itemMetadata.Item); } } // If we're sorting we can't predict how // the collection has changed on an add so we // resort to a reset notification. if (this.sort != null) { this.NotifyReset(); } break; case NotifyCollectionChangedAction.Remove: foreach (ItemMetadata itemMetadata in e.OldItems) { this.RemoveMetadataMonitor(itemMetadata); if (this.filter(itemMetadata)) { this.RemoveFromFilteredList(itemMetadata.Item); } } break; default: this.ResetAllMonitors(); this.UpdateFilteredItemsList(); this.NotifyReset(); break; } } private void NotifyAdd(object item) { int newIndex = this.filteredItems.IndexOf(item); this.NotifyAdd(new[] { item }, newIndex); } private void RemoveFromFilteredList(object item) { int index = this.filteredItems.IndexOf(item); this.UpdateFilteredItemsList(); this.NotifyRemove(new[] { item }, index); } private void UpdateFilteredItemsList() { this.filteredItems = this.subjectCollection.Where(i => this.filter(i)).Select(i => i.Item) .OrderBy<object, object>(o => o, new RegionItemComparer(this.SortComparison)).ToList(); } private class MonitorInfo { public bool IsInList { get; set; } } private class RegionItemComparer : Comparer<object> { private readonly Comparison<object> comparer; public RegionItemComparer(Comparison<object> comparer) { this.comparer = comparer; } public override int Compare(object x, object y) { if (this.comparer == null) { return 0; } return this.comparer(x, y); } } private void NotifyAdd(IList items, int newStartingIndex) { if (items.Count > 0) { OnCollectionChanged(new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, items, newStartingIndex)); } } private void NotifyRemove(IList items, int originalIndex) { if (items.Count > 0) { OnCollectionChanged(new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, items, originalIndex)); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace ProvisionAPI.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// // MessageView.cs // // Author: // Prashant Cholachagudda <[email protected]> // // Copyright (c) 2013 Prashant Cholachagudda // // 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.Drawing; using CoreGraphics; using Foundation; using UIKit; namespace Toasts { public class MessageView : UIView { private static readonly UIFont TitleFont; private static readonly UIFont DescriptionFont; private static readonly UIColor TitleColor; private static readonly UIColor DescriptionColor; private const float Padding = 12.0f; private const float IconSize = 36.0f; private const float TextOffset = 2.0f; private float _height; private float _width; static MessageView() { TitleFont = UIFont.BoldSystemFontOfSize(16.0f); DescriptionFont = UIFont.SystemFontOfSize(14.0f); TitleColor = UIColor.FromWhiteAlpha(1.0f, 1.0f); DescriptionColor = UIColor.FromWhiteAlpha(1.0f, 1.0f); } internal MessageView(string title, string description, ToastNotificationType type, Action<bool> onDismiss, TimeSpan duration) : this((NSString)title, (NSString)description, type) { OnDismiss = onDismiss; DisplayDelay = duration.TotalSeconds; } private MessageView(NSString title, NSString description, ToastNotificationType type) : base(RectangleF.Empty) { BackgroundColor = UIColor.Clear; ClipsToBounds = false; UserInteractionEnabled = true; Title = title; Description = description; MessageType = type; Height = 0.0f; Width = 0.0f; Hit = false; NSNotificationCenter.DefaultCenter.AddObserver(UIDevice.OrientationDidChangeNotification, OrientationChanged); } public Action<bool> OnDismiss { get; set; } public bool Hit { get; set; } public float Height { get { if (Math.Abs(_height) < 0.0001) { CGSize titleLabelSize = TitleSize(); CGSize descriptionLabelSize = DescriptionSize(); _height = (float) Math.Max((Padding*2) + titleLabelSize.Height + descriptionLabelSize.Height, (Padding*2) + IconSize); } return _height; } private set { _height = value; } } public float Width { get { if (Math.Abs(_width) < 0.0001) _width = GetStatusBarFrame().Width; return _width; } private set { _width = value; } } public double DisplayDelay { get; set; } internal MessageBarStyleSheet StylesheetProvider { get; set; } private NSString Title { get; set; } private new NSString Description { get; set; } private ToastNotificationType MessageType { get; set; } private float AvailableWidth { get { float maxWidth = (Width - (Padding*3) - IconSize); return maxWidth; } } private void OrientationChanged(NSNotification notification) { Frame = new RectangleF((float) Frame.X, (float) Frame.Y, GetStatusBarFrame().Width, (float) Frame.Height); SetNeedsDisplay(); } private RectangleF GetStatusBarFrame() { var windowFrame = OrientFrame(UIApplication.SharedApplication.KeyWindow.Frame); var statusFrame = OrientFrame(UIApplication.SharedApplication.StatusBarFrame); return new RectangleF((float) windowFrame.X, (float) windowFrame.Y, (float) windowFrame.Width, (float) statusFrame.Height); } private CGRect OrientFrame(CGRect frame) { if ((IsDeviceLandscape(UIDevice.CurrentDevice.Orientation) || IsStatusBarLandscape(UIApplication.SharedApplication.StatusBarOrientation)) && !IsRunningOnIOSVersionOrLater(8) /*http://stackoverflow.com/questions/24150359/is-uiscreen-mainscreen-bounds-size-becoming-orientation-dependent-in-ios8*/) { frame = new RectangleF((float) frame.X, (float) frame.Y, (float) frame.Height, (float) frame.Width); } return frame; } private bool IsDeviceLandscape(UIDeviceOrientation orientation) { return orientation == UIDeviceOrientation.LandscapeLeft || orientation == UIDeviceOrientation.LandscapeRight; } private bool IsStatusBarLandscape(UIInterfaceOrientation orientation) { return orientation == UIInterfaceOrientation.LandscapeLeft || orientation == UIInterfaceOrientation.LandscapeRight; } public override void Draw(CGRect rect) { var context = UIGraphics.GetCurrentContext (); MessageBarStyleSheet styleSheet = StylesheetProvider; context.SaveState (); styleSheet.BackgroundColorForMessageType (MessageType).SetColor (); context.FillRect (rect); context.RestoreState (); context.SaveState (); context.BeginPath (); context.MoveTo (0, rect.Size.Height); context.SetStrokeColor(styleSheet.StrokeColorForMessageType (MessageType).CGColor); context.SetLineWidth (1); context.AddLineToPoint (rect.Size.Width, rect.Size.Height); context.StrokePath (); context.RestoreState (); context.SaveState (); float xOffset = Padding; float yOffset = Padding; var icon = styleSheet.IconImageForMessageType(MessageType); if (icon != null) { icon.Draw(new RectangleF(xOffset, yOffset, IconSize, IconSize)); } context.SaveState (); yOffset -= TextOffset; xOffset += (icon == null ? 0 : IconSize) + Padding; CGSize titleLabelSize = TitleSize(); if (string.IsNullOrEmpty (Title) && !string.IsNullOrEmpty (Description)) { yOffset = (float)(Math.Ceiling ((double)rect.Size.Height * 0.5) - Math.Ceiling ((double)titleLabelSize.Height * 0.5) - TextOffset); } TitleColor.SetColor (); var titleRectangle = new RectangleF (xOffset, yOffset, (float) titleLabelSize.Width + 5, (float) titleLabelSize.Height + 5); Title.DrawString(titleRectangle, TitleFont, UILineBreakMode.TailTruncation, UITextAlignment.Left); yOffset += (float)titleLabelSize.Height; CGSize descriptionLabelSize = DescriptionSize(); DescriptionColor.SetColor(); var descriptionRectangle = new RectangleF(xOffset, yOffset, (float)descriptionLabelSize.Width + Padding, (float)descriptionLabelSize.Height+Padding); Description.DrawString(descriptionRectangle, DescriptionFont, UILineBreakMode.TailTruncation, UITextAlignment.Left); } private CGSize TitleSize() { var boundedSize = new SizeF(AvailableWidth, float.MaxValue); CGSize titleLabelSize; if (!IsRunningOnIOSVersionOrLater(7)) { var attr = new UIStringAttributes(NSDictionary.FromObjectAndKey(TitleFont, (NSString) TitleFont.Name)); titleLabelSize = Title.GetBoundingRect(boundedSize, NSStringDrawingOptions.TruncatesLastVisibleLine, attr, null).Size; } else { titleLabelSize = Title.StringSize(TitleFont, boundedSize, UILineBreakMode.TailTruncation); } return titleLabelSize; } private CGSize DescriptionSize() { var boundedSize = new SizeF(AvailableWidth, float.MaxValue); CGSize descriptionLabelSize; if (!IsRunningOnIOSVersionOrLater(7)) { var attr = new UIStringAttributes(NSDictionary.FromObjectAndKey(TitleFont, (NSString) TitleFont.Name)); descriptionLabelSize = Description.GetBoundingRect(boundedSize, NSStringDrawingOptions.TruncatesLastVisibleLine, attr, null).Size; } else { descriptionLabelSize = Description.StringSize(DescriptionFont, boundedSize, UILineBreakMode.TailTruncation); } return descriptionLabelSize; } private bool IsRunningOnIOSVersionOrLater(int majorVersion) { Version version = new Version(UIDevice.CurrentDevice.SystemVersion); return version.Major >= majorVersion; } } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using Lucene.Net.Search; using Lucene.Net.Spatial.Util; using Lucene.Net.Util; using NUnit.Framework; namespace Lucene.Net.Contrib.Spatial.Test.Compatibility { public static class BitArrayExtensions { public static int NextSetBit(this BitArray arr, int fromIndex) { if (fromIndex >= arr.Length) throw new ArgumentException("Invalid fromIndex", "fromIndex"); for (var i = fromIndex; i < arr.Length; i++) { if (arr[i]) return i; } return -1; } } public class TestFixedBitSet : LuceneTestCase { private static readonly Random rnd = new Random((int)DateTimeOffset.Now.Ticks); void doGet(BitArray a, FixedBitSet b) { int max = b.Length(); for (int i = 0; i < max; i++) { if (a.Get(i) != b.Get(i)) { Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.Get(i)); } } } void doNextSetBit(BitArray a, FixedBitSet b) { int aa = -1, bb = -1; do { aa = a.NextSetBit(aa + 1); bb = bb < b.Length() - 1 ? b.NextSetBit(bb + 1) : -1; Assert.AreEqual(aa, bb); } while (aa >= 0); } void doPrevSetBit(BitArray a, FixedBitSet b) { int aa = a.Length + rnd.Next(100); int bb = aa; do { // aa = a.prevSetBit(aa-1); aa--; while ((aa >= 0) && (!a.Get(aa))) { aa--; } if (b.Length() == 0) { bb = -1; } else if (bb > b.Length() - 1) { bb = b.PrevSetBit(b.Length() - 1); } else if (bb < 1) { bb = -1; } else { bb = bb >= 1 ? b.PrevSetBit(bb - 1) : -1; } Assert.AreEqual(aa, bb); } while (aa >= 0); } // test interleaving different FixedBitSetIterator.next()/skipTo() //void doIterate(BitArray a, FixedBitSet b, int mode) //{ // if (mode == 1) doIterate1(a, b); // if (mode == 2) doIterate2(a, b); //} //void doIterate1(BitArray a, FixedBitSet b) //{ // int aa = -1, bb = -1; // DocIdSetIterator iterator = b.iterator(); // do // { // aa = a.NextSetBit(aa + 1); // bb = (bb < b.Length() && random().nextBoolean()) ? iterator.NextDoc() : iterator.Advance(bb + 1); // Assert.AreEqual(aa == -1 ? DocIdSetIterator.NO_MORE_DOCS : aa, bb); // } while (aa >= 0); //} //void doIterate2(BitArray a, FixedBitSet b) //{ // int aa = -1, bb = -1; // DocIdSetIterator iterator = b.iterator(); // do // { // aa = a.NextSetBit(aa + 1); // bb = random().nextBoolean() ? iterator.NextDoc() : iterator.Advance(bb + 1); // Assert.AreEqual(aa == -1 ? DocIdSetIterator.NO_MORE_DOCS : aa, bb); // } while (aa >= 0); //} //void doRandomSets(int maxSize, int iter, int mode) //{ // BitArray a0 = null; // FixedBitSet b0 = null; // for (int i = 0; i < iter; i++) // { // int sz = _TestUtil.nextInt(random(), 2, maxSize); // BitSet a = new BitSet(sz); // FixedBitSet b = new FixedBitSet(sz); // // test the various ways of setting bits // if (sz > 0) // { // int nOper = random().nextInt(sz); // for (int j = 0; j < nOper; j++) // { // int idx; // idx = random().nextInt(sz); // a.set(idx); // b.set(idx); // idx = random().nextInt(sz); // a.clear(idx); // b.clear(idx); // idx = random().nextInt(sz); // a.flip(idx); // b.flip(idx, idx + 1); // idx = random().nextInt(sz); // a.flip(idx); // b.flip(idx, idx + 1); // boolean val2 = b.get(idx); // boolean val = b.getAndSet(idx); // assertTrue(val2 == val); // assertTrue(b.get(idx)); // if (!val) b.clear(idx); // assertTrue(b.get(idx) == val); // } // } // // test that the various ways of accessing the bits are equivalent // doGet(a, b); // // test ranges, including possible extension // int fromIndex, toIndex; // fromIndex = random().nextInt(sz / 2); // toIndex = fromIndex + random().nextInt(sz - fromIndex); // BitSet aa = (BitSet)a.clone(); aa.flip(fromIndex, toIndex); // FixedBitSet bb = b.clone(); bb.flip(fromIndex, toIndex); // doIterate(aa, bb, mode); // a problem here is from flip or doIterate // fromIndex = random().nextInt(sz / 2); // toIndex = fromIndex + random().nextInt(sz - fromIndex); // aa = (BitSet)a.clone(); aa.clear(fromIndex, toIndex); // bb = b.clone(); bb.clear(fromIndex, toIndex); // doNextSetBit(aa, bb); // a problem here is from clear() or nextSetBit // doPrevSetBit(aa, bb); // fromIndex = random().nextInt(sz / 2); // toIndex = fromIndex + random().nextInt(sz - fromIndex); // aa = (BitSet)a.clone(); aa.set(fromIndex, toIndex); // bb = b.clone(); bb.set(fromIndex, toIndex); // doNextSetBit(aa, bb); // a problem here is from set() or nextSetBit // doPrevSetBit(aa, bb); // if (b0 != null && b0.length() <= b.length()) // { // assertEquals(a.cardinality(), b.cardinality()); // BitSet a_and = (BitSet)a.clone(); a_and.and(a0); // BitSet a_or = (BitSet)a.clone(); a_or.or(a0); // BitSet a_andn = (BitSet)a.clone(); a_andn.andNot(a0); // FixedBitSet b_and = b.clone(); assertEquals(b, b_and); b_and.and(b0); // FixedBitSet b_or = b.clone(); b_or.or(b0); // FixedBitSet b_andn = b.clone(); b_andn.andNot(b0); // assertEquals(a0.cardinality(), b0.cardinality()); // assertEquals(a_or.cardinality(), b_or.cardinality()); // doIterate(a_and, b_and, mode); // doIterate(a_or, b_or, mode); // doIterate(a_andn, b_andn, mode); // assertEquals(a_and.cardinality(), b_and.cardinality()); // assertEquals(a_or.cardinality(), b_or.cardinality()); // assertEquals(a_andn.cardinality(), b_andn.cardinality()); // } // a0 = a; // b0 = b; // } //} // large enough to flush obvious bugs, small enough to run in <.5 sec as part of a // larger testsuite. //public void testSmall() //{ // doRandomSets(atLeast(1200), atLeast(1000), 1); // doRandomSets(atLeast(1200), atLeast(1000), 2); //} // uncomment to run a bigger test (~2 minutes). /* public void testBig() { doRandomSets(2000,200000, 1); doRandomSets(2000,200000, 2); } */ [Test] public void testEquals() { // This test can't handle numBits==0: int numBits = rnd.Next(2000) + 1; FixedBitSet b1 = new FixedBitSet(numBits); FixedBitSet b2 = new FixedBitSet(numBits); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); for (int iter = 0; iter < 10 * rnd.Next(500); iter++) { int idx = rnd.Next(numBits); if (!b1.Get(idx)) { b1.Set(idx); Assert.IsFalse(b1.Equals(b2)); Assert.IsFalse(b2.Equals(b1)); b2.Set(idx); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); } } // try different type of object Assert.IsFalse(b1.Equals(new Object())); } [Test] public void testHashCodeEquals() { // This test can't handle numBits==0: int numBits = rnd.Next(2000) + 1; FixedBitSet b1 = new FixedBitSet(numBits); FixedBitSet b2 = new FixedBitSet(numBits); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); for (int iter = 0; iter < 10 * rnd.Next(500); iter++) { int idx = rnd.Next(numBits); if (!b1.Get(idx)) { b1.Set(idx); Assert.IsFalse(b1.Equals(b2)); Assert.AreNotEqual(b1.GetHashCode(), b2.GetHashCode()); b2.Set(idx); Assert.AreEqual(b1, b2); Assert.AreEqual(b1.GetHashCode(), b2.GetHashCode()); } } } [Test] public void testSmallBitSets() { // Make sure size 0-10 bit sets are OK: for (int numBits = 0; numBits < 10; numBits++) { FixedBitSet b1 = new FixedBitSet(numBits); FixedBitSet b2 = new FixedBitSet(numBits); Assert.IsTrue(b1.Equals(b2)); Assert.AreEqual(b1.GetHashCode(), b2.GetHashCode()); Assert.AreEqual(0, b1.Cardinality()); if (numBits > 0) { b1.Set(0, numBits); Assert.AreEqual(numBits, b1.Cardinality()); //b1.Flip(0, numBits); //Assert.AreEqual(0, b1.Cardinality()); } } } private FixedBitSet makeFixedBitSet(int[] a, int numBits) { FixedBitSet bs = new FixedBitSet(numBits); foreach (int e in a) { bs.Set(e); } return bs; } private BitArray makeBitSet(int[] a) { var bs = new BitArray(a.Length); foreach (int e in a) { bs.Set(e, true); } return bs; } private void checkPrevSetBitArray(int[] a, int numBits) { FixedBitSet obs = makeFixedBitSet(a, numBits); BitArray bs = makeBitSet(a); doPrevSetBit(bs, obs); } [Test] public void testPrevSetBit() { checkPrevSetBitArray(new int[] { }, 0); checkPrevSetBitArray(new int[] { 0 }, 1); checkPrevSetBitArray(new int[] { 0, 2 }, 3); } } }
// 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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class ParameterTests : ParameterExpressionTests { [Theory] [MemberData(nameof(ValidTypeData))] public void CreateParameterForValidTypeNoName(Type type) { ParameterExpression param = Expression.Parameter(type); Assert.Equal(type, param.Type); Assert.False(param.IsByRef); Assert.Null(param.Name); } [Theory] [MemberData(nameof(ValidTypeData))] public void CrateParamForValidTypeWithName(Type type) { ParameterExpression param = Expression.Parameter(type, "name"); Assert.Equal(type, param.Type); Assert.False(param.IsByRef); Assert.Equal("name", param.Name); } [Fact] public void NameNeedNotBeCSharpValid() { ParameterExpression param = Expression.Parameter(typeof(int), "a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c."); Assert.Equal("a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c.", param.Name); } [Fact] public void ParameterCannotBeTypeVoid() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(void))); AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(void), "var")); } [Theory] [ClassData(typeof(InvalidTypesData))] public void OpenGenericType_ThrowsArgumentException(Type type) { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(type)); AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(type, "name")); } [Fact] public void NullType() { AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Parameter(null)); AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Parameter(null, "var")); } [Theory] [MemberData(nameof(ByRefTypeData))] public void ParameterCanBeByRef(Type type) { ParameterExpression param = Expression.Parameter(type); Assert.Equal(type.GetElementType(), param.Type); Assert.True(param.IsByRef); Assert.Null(param.Name); } [Theory] [MemberData(nameof(ByRefTypeData))] public void NamedParameterCanBeByRef(Type type) { ParameterExpression param = Expression.Parameter(type, "name"); Assert.Equal(type.GetElementType(), param.Type); Assert.True(param.IsByRef); Assert.Equal("name", param.Name); } [Theory] [PerCompilationType(nameof(ValueData))] public void CanWriteAndReadBack(object value, bool useInterpreter) { Type type = value.GetType(); ParameterExpression param = Expression.Parameter(type); Assert.True( Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(value), Expression.Block( type, new[] { param }, Expression.Assign(param, Expression.Constant(value)), param ) ) ).Compile(useInterpreter)() ); } [Theory] [ClassData(typeof(CompilationTypes))] public void CanUseAsLambdaParameter(bool useInterpreter) { ParameterExpression param = Expression.Parameter(typeof(int)); Func<int, int> addOne = Expression.Lambda<Func<int, int>>( Expression.Add(param, Expression.Constant(1)), param ).Compile(useInterpreter); Assert.Equal(3, addOne(2)); } public delegate void ByRefFunc<T>(ref T arg); [Theory] [ClassData(typeof(CompilationTypes))] public void CanUseAsLambdaByRefParameter(bool useInterpreter) { ParameterExpression param = Expression.Parameter(typeof(int).MakeByRefType()); ByRefFunc<int> addOneInPlace = Expression.Lambda<ByRefFunc<int>>( Expression.PreIncrementAssign(param), param ).Compile(useInterpreter); int argument = 5; addOneInPlace(ref argument); Assert.Equal(6, argument); } [Theory] [ClassData(typeof(CompilationTypes))] public void CanUseAsLambdaByRefParameter_String(bool useInterpreter) { ParameterExpression param = Expression.Parameter(typeof(string).MakeByRefType()); ByRefFunc<string> f = Expression.Lambda<ByRefFunc<string>>( Expression.Assign(param, Expression.Call(param, typeof(string).GetMethod(nameof(string.ToUpper), Type.EmptyTypes))), param ).Compile(useInterpreter); string argument = "bar"; f(ref argument); Assert.Equal("BAR", argument); } [Theory] [ClassData(typeof(CompilationTypes))] public void CanUseAsLambdaByRefParameter_Char(bool useInterpreter) { ParameterExpression param = Expression.Parameter(typeof(char).MakeByRefType()); ByRefFunc<char> f = Expression.Lambda<ByRefFunc<char>>( Expression.Assign(param, Expression.Call(typeof(char).GetMethod(nameof(char.ToUpper), new[] { typeof(char) }), param)), param ).Compile(useInterpreter); char argument = 'a'; f(ref argument); Assert.Equal('A', argument); } [Theory] [ClassData(typeof(CompilationTypes))] public void CanUseAsLambdaByRefParameter_Bool(bool useInterpreter) { ParameterExpression param = Expression.Parameter(typeof(bool).MakeByRefType()); ByRefFunc<bool> f = Expression.Lambda<ByRefFunc<bool>>( Expression.ExclusiveOrAssign(param, Expression.Constant(true)), param ).Compile(useInterpreter); bool b1 = false; f(ref b1); Assert.Equal(false ^ true, b1); bool b2 = true; f(ref b2); Assert.Equal(true ^ true, b2); } [Theory] [ClassData(typeof(CompilationTypes))] public void CanReadFromRefParameter(bool useInterpreter) { AssertCanReadFromRefParameter<byte>(byte.MaxValue, useInterpreter); AssertCanReadFromRefParameter<sbyte>(sbyte.MaxValue, useInterpreter); AssertCanReadFromRefParameter<short>(short.MaxValue, useInterpreter); AssertCanReadFromRefParameter<ushort>(ushort.MaxValue, useInterpreter); AssertCanReadFromRefParameter<int>(int.MaxValue, useInterpreter); AssertCanReadFromRefParameter<uint>(uint.MaxValue, useInterpreter); AssertCanReadFromRefParameter<long>(long.MaxValue, useInterpreter); AssertCanReadFromRefParameter<ulong>(ulong.MaxValue, useInterpreter); AssertCanReadFromRefParameter<decimal>(49.94m, useInterpreter); AssertCanReadFromRefParameter<float>(3.1415926535897931f, useInterpreter); AssertCanReadFromRefParameter<double>(2.7182818284590451, useInterpreter); AssertCanReadFromRefParameter('a', useInterpreter); AssertCanReadFromRefParameter(ByteEnum.A, useInterpreter); AssertCanReadFromRefParameter(SByteEnum.A, useInterpreter); AssertCanReadFromRefParameter(Int16Enum.A, useInterpreter); AssertCanReadFromRefParameter(UInt16Enum.A, useInterpreter); AssertCanReadFromRefParameter(Int32Enum.A, useInterpreter); AssertCanReadFromRefParameter(UInt32Enum.A, useInterpreter); AssertCanReadFromRefParameter(Int64Enum.A, useInterpreter); AssertCanReadFromRefParameter(UInt64Enum.A, useInterpreter); AssertCanReadFromRefParameter(new DateTime(1983, 2, 11), useInterpreter); AssertCanReadFromRefParameter<object>(null, useInterpreter); AssertCanReadFromRefParameter<object>(new object(), useInterpreter); AssertCanReadFromRefParameter<string>("bar", useInterpreter); AssertCanReadFromRefParameter<int?>(null, useInterpreter); AssertCanReadFromRefParameter<int?>(int.MaxValue, useInterpreter); AssertCanReadFromRefParameter<Int64Enum?>(null, useInterpreter); AssertCanReadFromRefParameter<Int64Enum?>(Int64Enum.A, useInterpreter); AssertCanReadFromRefParameter<DateTime?>(null, useInterpreter); AssertCanReadFromRefParameter<DateTime?>(new DateTime(1983, 2, 11), useInterpreter); } public delegate T ByRefReadFunc<T>(ref T arg); private void AssertCanReadFromRefParameter<T>(T value, bool useInterpreter) { ParameterExpression @ref = Expression.Parameter(typeof(T).MakeByRefType()); ByRefReadFunc<T> f = Expression.Lambda<ByRefReadFunc<T>>( @ref, @ref ).Compile(useInterpreter); Assert.Equal(value, f(ref value)); } public delegate void ByRefWriteAction<T>(ref T arg, T value); [Theory] [ClassData(typeof(CompilationTypes))] public void CanWriteToRefParameter(bool useInterpreter) { AssertCanWriteToRefParameter<byte>(byte.MaxValue, useInterpreter); AssertCanWriteToRefParameter<sbyte>(sbyte.MaxValue, useInterpreter); AssertCanWriteToRefParameter<short>(short.MaxValue, useInterpreter); AssertCanWriteToRefParameter<ushort>(ushort.MaxValue, useInterpreter); AssertCanWriteToRefParameter<int>(int.MaxValue, useInterpreter); AssertCanWriteToRefParameter<uint>(uint.MaxValue, useInterpreter); AssertCanWriteToRefParameter<long>(long.MaxValue, useInterpreter); AssertCanWriteToRefParameter<ulong>(ulong.MaxValue, useInterpreter); AssertCanWriteToRefParameter<decimal>(49.94m, useInterpreter); AssertCanWriteToRefParameter<float>(3.1415926535897931f, useInterpreter); AssertCanWriteToRefParameter<double>(2.7182818284590451, useInterpreter); AssertCanWriteToRefParameter('a', useInterpreter); AssertCanWriteToRefParameter(ByteEnum.A, useInterpreter); AssertCanWriteToRefParameter(SByteEnum.A, useInterpreter); AssertCanWriteToRefParameter(Int16Enum.A, useInterpreter); AssertCanWriteToRefParameter(UInt16Enum.A, useInterpreter); AssertCanWriteToRefParameter(Int32Enum.A, useInterpreter); AssertCanWriteToRefParameter(UInt32Enum.A, useInterpreter); AssertCanWriteToRefParameter(Int64Enum.A, useInterpreter); AssertCanWriteToRefParameter(UInt64Enum.A, useInterpreter); AssertCanWriteToRefParameter(new DateTime(1983, 2, 11), useInterpreter); AssertCanWriteToRefParameter<object>(null, useInterpreter); AssertCanWriteToRefParameter<object>(new object(), useInterpreter); AssertCanWriteToRefParameter<string>("bar", useInterpreter); AssertCanWriteToRefParameter<int?>(null, useInterpreter, original: 42); AssertCanWriteToRefParameter<int?>(int.MaxValue, useInterpreter); AssertCanWriteToRefParameter<Int64Enum?>(null, useInterpreter, original: Int64Enum.A); AssertCanWriteToRefParameter<Int64Enum?>(Int64Enum.A, useInterpreter); AssertCanWriteToRefParameter<DateTime?>(null, useInterpreter, original: new DateTime(1983, 2, 11)); AssertCanWriteToRefParameter<DateTime?>(new DateTime(1983, 2, 11), useInterpreter); } private void AssertCanWriteToRefParameter<T>(T value, bool useInterpreter, T original = default(T)) { ParameterExpression @ref = Expression.Parameter(typeof(T).MakeByRefType()); ParameterExpression val = Expression.Parameter(typeof(T)); ByRefWriteAction<T> f = Expression.Lambda<ByRefWriteAction<T>>( Expression.Assign(@ref, val), @ref, val ).Compile(useInterpreter); T res = original; f(ref res, value); Assert.Equal(res, value); } [Fact] public void CannotReduce() { ParameterExpression param = Expression.Parameter(typeof(int)); Assert.False(param.CanReduce); Assert.Same(param, param.Reduce()); Assert.Throws<ArgumentException>(null, () => param.ReduceAndCheck()); } [Fact] public void CannotBePointerType() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(int*))); AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(int*), "pointer")); } [Theory] [MemberData(nameof(ReadAndWriteRefCases))] public void ReadAndWriteRefParameters(bool useInterpreter, object value, object increment, object result) { Type type = value.GetType(); MethodInfo method = typeof(ParameterTests).GetMethod(nameof(AssertReadAndWriteRefParameters), BindingFlags.NonPublic | BindingFlags.Static); method.MakeGenericMethod(type).Invoke(null, new object[] { useInterpreter, value, increment, result }); } private static void AssertReadAndWriteRefParameters<T>(bool useInterpreter, T value, T increment, T result) { ParameterExpression param = Expression.Parameter(typeof(T).MakeByRefType()); ByRefFunc<T> addOneInPlace = Expression.Lambda<ByRefFunc<T>>( Expression.AddAssign(param, Expression.Constant(increment, typeof(T))), param ).Compile(useInterpreter); T argument = value; addOneInPlace(ref argument); Assert.Equal(result, argument); } public static IEnumerable<object[]> ReadAndWriteRefCases() { foreach (var useInterpreter in new[] { true, false }) { yield return new object[] { useInterpreter, (short)41, (short)1, (short)42 }; yield return new object[] { useInterpreter, (ushort)41, (ushort)1, (ushort)42 }; yield return new object[] { useInterpreter, 41, 1, 42 }; yield return new object[] { useInterpreter, 41U, 1U, 42U }; yield return new object[] { useInterpreter, 41L, 1L, 42L }; yield return new object[] { useInterpreter, 41UL, 1UL, 42UL }; yield return new object[] { useInterpreter, 41.0F, 1.0F, Apply((x, y) => x + y, 41.0F, 1.0F) }; yield return new object[] { useInterpreter, 41.0D, 1.0D, Apply((x, y) => x + y, 41.0D, 1.0D) }; yield return new object[] { useInterpreter, TimeSpan.FromSeconds(41), TimeSpan.FromSeconds(1), Apply((x, y) => x + y, TimeSpan.FromSeconds(41), TimeSpan.FromSeconds(1)) }; } } private static T Apply<T>(Func<T, T, T> f, T x, T y) => f(x, y); } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // PrincipalPermission.cs // // <OWNER>[....]</OWNER> // namespace System.Security.Permissions { using System; using SecurityElement = System.Security.SecurityElement; using System.Security.Util; using System.IO; using System.Collections; using System.Collections.Generic; using System.Security.Principal; using System.Text; using System.Threading; using System.Globalization; using System.Reflection; using System.Diagnostics.Contracts; [Serializable] internal class IDRole { internal bool m_authenticated; internal String m_id; internal String m_role; #if !FEATURE_PAL // cache the translation from name to Sid for the case of WindowsPrincipal. [NonSerialized] private SecurityIdentifier m_sid = null; internal SecurityIdentifier Sid { [System.Security.SecurityCritical] // auto-generated get { if (String.IsNullOrEmpty(m_role)) return null; if (m_sid == null) { NTAccount ntAccount = new NTAccount(m_role); IdentityReferenceCollection source = new IdentityReferenceCollection(1); source.Add(ntAccount); IdentityReferenceCollection target = NTAccount.Translate(source, typeof(SecurityIdentifier), false); m_sid = target[0] as SecurityIdentifier; } return m_sid; } } #endif // !FEATURE_PAL #if FEATURE_CAS_POLICY internal SecurityElement ToXml() { SecurityElement root = new SecurityElement( "Identity" ); if (m_authenticated) root.AddAttribute( "Authenticated", "true" ); if (m_id != null) { root.AddAttribute( "ID", SecurityElement.Escape( m_id ) ); } if (m_role != null) { root.AddAttribute( "Role", SecurityElement.Escape( m_role ) ); } return root; } internal void FromXml( SecurityElement e ) { String elAuth = e.Attribute( "Authenticated" ); if (elAuth != null) { m_authenticated = String.Compare( elAuth, "true", StringComparison.OrdinalIgnoreCase) == 0; } else { m_authenticated = false; } String elID = e.Attribute( "ID" ); if (elID != null) { m_id = elID; } else { m_id = null; } String elRole = e.Attribute( "Role" ); if (elRole != null) { m_role = elRole; } else { m_role = null; } } #endif // FEATURE_CAS_POLICY public override int GetHashCode() { return ((m_authenticated ? 0 : 101) + (m_id == null ? 0 : m_id.GetHashCode()) + (m_role == null? 0 : m_role.GetHashCode())); } } [System.Runtime.InteropServices.ComVisible(true)] [Serializable] sealed public class PrincipalPermission : IPermission, IUnrestrictedPermission, ISecurityEncodable, IBuiltInPermission { private IDRole[] m_array; public PrincipalPermission( PermissionState state ) { if (state == PermissionState.Unrestricted) { m_array = new IDRole[1]; m_array[0] = new IDRole(); m_array[0].m_authenticated = true; m_array[0].m_id = null; m_array[0].m_role = null; } else if (state == PermissionState.None) { m_array = new IDRole[1]; m_array[0] = new IDRole(); m_array[0].m_authenticated = false; m_array[0].m_id = ""; m_array[0].m_role = ""; } else throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } public PrincipalPermission( String name, String role ) { m_array = new IDRole[1]; m_array[0] = new IDRole(); m_array[0].m_authenticated = true; m_array[0].m_id = name; m_array[0].m_role = role; } public PrincipalPermission( String name, String role, bool isAuthenticated ) { m_array = new IDRole[1]; m_array[0] = new IDRole(); m_array[0].m_authenticated = isAuthenticated; m_array[0].m_id = name; m_array[0].m_role = role; } private PrincipalPermission( IDRole[] array ) { m_array = array; } private bool IsEmpty() { for (int i = 0; i < m_array.Length; ++i) { if ((m_array[i].m_id == null || !m_array[i].m_id.Equals( "" )) || (m_array[i].m_role == null || !m_array[i].m_role.Equals( "" )) || m_array[i].m_authenticated) { return false; } } return true; } private bool VerifyType(IPermission perm) { // if perm is null, then obviously not of the same type if ((perm == null) || (perm.GetType() != this.GetType())) { return(false); } else { return(true); } } public bool IsUnrestricted() { for (int i = 0; i < m_array.Length; ++i) { if (m_array[i].m_id != null || m_array[i].m_role != null || !m_array[i].m_authenticated) { return false; } } return true; } //------------------------------------------------------ // // IPERMISSION IMPLEMENTATION // //------------------------------------------------------ public bool IsSubsetOf(IPermission target) { if (target == null) { return this.IsEmpty(); } try { PrincipalPermission operand = (PrincipalPermission)target; if (operand.IsUnrestricted()) return true; else if (this.IsUnrestricted()) return false; else { for (int i = 0; i < this.m_array.Length; ++i) { bool foundMatch = false; for (int j = 0; j < operand.m_array.Length; ++j) { if (operand.m_array[j].m_authenticated == this.m_array[i].m_authenticated && (operand.m_array[j].m_id == null || (this.m_array[i].m_id != null && this.m_array[i].m_id.Equals( operand.m_array[j].m_id ))) && (operand.m_array[j].m_role == null || (this.m_array[i].m_role != null && this.m_array[i].m_role.Equals( operand.m_array[j].m_role )))) { foundMatch = true; break; } } if (!foundMatch) return false; } return true; } } catch (InvalidCastException) { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } } public IPermission Intersect(IPermission target) { if (target == null) { return null; } else if (!VerifyType(target)) { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } else if (this.IsUnrestricted()) { return target.Copy(); } PrincipalPermission operand = (PrincipalPermission)target; if (operand.IsUnrestricted()) { return this.Copy(); } List<IDRole> idroles = null; for (int i = 0; i < this.m_array.Length; ++i) { for (int j = 0; j < operand.m_array.Length; ++j) { if (operand.m_array[j].m_authenticated == this.m_array[i].m_authenticated) { if (operand.m_array[j].m_id == null || this.m_array[i].m_id == null || this.m_array[i].m_id.Equals( operand.m_array[j].m_id )) { if (idroles == null) { idroles = new List<IDRole>(); } IDRole idrole = new IDRole(); idrole.m_id = operand.m_array[j].m_id == null ? this.m_array[i].m_id : operand.m_array[j].m_id; if (operand.m_array[j].m_role == null || this.m_array[i].m_role == null || this.m_array[i].m_role.Equals( operand.m_array[j].m_role)) { idrole.m_role = operand.m_array[j].m_role == null ? this.m_array[i].m_role : operand.m_array[j].m_role; } else { idrole.m_role = ""; } idrole.m_authenticated = operand.m_array[j].m_authenticated; idroles.Add( idrole ); } else if (operand.m_array[j].m_role == null || this.m_array[i].m_role == null || this.m_array[i].m_role.Equals( operand.m_array[j].m_role)) { if (idroles == null) { idroles = new List<IDRole>(); } IDRole idrole = new IDRole(); idrole.m_id = ""; idrole.m_role = operand.m_array[j].m_role == null ? this.m_array[i].m_role : operand.m_array[j].m_role; idrole.m_authenticated = operand.m_array[j].m_authenticated; idroles.Add( idrole ); } } } } if (idroles == null) { return null; } else { IDRole[] idrolesArray = new IDRole[idroles.Count]; IEnumerator idrolesEnumerator = idroles.GetEnumerator(); int index = 0; while (idrolesEnumerator.MoveNext()) { idrolesArray[index++] = (IDRole)idrolesEnumerator.Current; } return new PrincipalPermission( idrolesArray ); } } public IPermission Union(IPermission other) { if (other == null) { return this.Copy(); } else if (!VerifyType(other)) { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } PrincipalPermission operand = (PrincipalPermission)other; if (this.IsUnrestricted() || operand.IsUnrestricted()) { return new PrincipalPermission( PermissionState.Unrestricted ); } // Now we have to do a real union int combinedLength = this.m_array.Length + operand.m_array.Length; IDRole[] idrolesArray = new IDRole[combinedLength]; int i, j; for (i = 0; i < this.m_array.Length; ++i) { idrolesArray[i] = this.m_array[i]; } for (j = 0; j < operand.m_array.Length; ++j) { idrolesArray[i+j] = operand.m_array[j]; } return new PrincipalPermission( idrolesArray ); } [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals(Object obj) { IPermission perm = obj as IPermission; if(obj != null && perm == null) return false; if(!this.IsSubsetOf(perm)) return false; if(perm != null && !perm.IsSubsetOf(this)) return false; return true; } [System.Runtime.InteropServices.ComVisible(false)] public override int GetHashCode() { int hash = 0; int i; for(i = 0; i < m_array.Length; i++) hash += m_array[i].GetHashCode(); return hash; } public IPermission Copy() { return new PrincipalPermission( m_array ); } [System.Security.SecurityCritical] // auto-generated private void ThrowSecurityException() { System.Reflection.AssemblyName name = null; System.Security.Policy.Evidence evid = null; PermissionSet.s_fullTrust.Assert(); try { System.Reflection.Assembly asm = Reflection.Assembly.GetCallingAssembly(); name = asm.GetName(); #if FEATURE_CAS_POLICY if(asm != Assembly.GetExecutingAssembly()) // this condition is to avoid having to marshal mscorlib's evidence (which is always in teh default domain) to the current domain evid = asm.Evidence; #endif // FEATURE_CAS_POLICY } catch { } PermissionSet.RevertAssert(); throw new SecurityException(Environment.GetResourceString("Security_PrincipalPermission"), name, null, null, null, SecurityAction.Demand, this, this, evid); } [System.Security.SecuritySafeCritical] // auto-generated public void Demand() { IPrincipal principal = null; #if FEATURE_IMPERSONATION new SecurityPermission(SecurityPermissionFlag.ControlPrincipal).Assert(); principal = Thread.CurrentPrincipal; #endif // FEATURE_IMPERSONATION if (principal == null) ThrowSecurityException(); if (m_array == null) return; // A demand passes when the grant satisfies all entries. int count = this.m_array.Length; bool foundMatch = false; for (int i = 0; i < count; ++i) { // If the demand is authenticated, we need to check the identity and role if (m_array[i].m_authenticated) { IIdentity identity = principal.Identity; if ((identity.IsAuthenticated && (m_array[i].m_id == null || String.Compare( identity.Name, m_array[i].m_id, StringComparison.OrdinalIgnoreCase) == 0))) { if (m_array[i].m_role == null) { foundMatch = true; } else { #if !FEATURE_PAL && FEATURE_IMPERSONATION WindowsPrincipal wp = principal as WindowsPrincipal; if (wp != null && m_array[i].Sid != null) foundMatch = wp.IsInRole(m_array[i].Sid); else #endif // !FEATURE_PAL && FEATURE_IMPERSONATION foundMatch = principal.IsInRole(m_array[i].m_role); } if (foundMatch) break; } } else { foundMatch = true; break; } } if (!foundMatch) ThrowSecurityException(); } #if FEATURE_CAS_POLICY public SecurityElement ToXml() { SecurityElement root = new SecurityElement( "IPermission" ); XMLUtil.AddClassAttribute( root, this.GetType(), "System.Security.Permissions.PrincipalPermission" ); // If you hit this assert then most likely you are trying to change the name of this class. // This is ok as long as you change the hard coded string above and change the assert below. Contract.Assert( this.GetType().FullName.Equals( "System.Security.Permissions.PrincipalPermission" ), "Class name changed!" ); root.AddAttribute( "version", "1" ); int count = m_array.Length; for (int i = 0; i < count; ++i) { root.AddChild( m_array[i].ToXml() ); } return root; } public void FromXml(SecurityElement elem) { CodeAccessPermission.ValidateElement( elem, this ); if (elem.InternalChildren != null && elem.InternalChildren.Count != 0) { int numChildren = elem.InternalChildren.Count; int count = 0; m_array = new IDRole[numChildren]; IEnumerator enumerator = elem.Children.GetEnumerator(); while (enumerator.MoveNext()) { IDRole idrole = new IDRole(); idrole.FromXml( (SecurityElement)enumerator.Current ); m_array[count++] = idrole; } } else m_array = new IDRole[0]; } public override String ToString() { return ToXml().ToString(); } #endif // FEATURE_CAS_POLICY /// <internalonly/> int IBuiltInPermission.GetTokenIndex() { return PrincipalPermission.GetTokenIndex(); } internal static int GetTokenIndex() { return BuiltInPermissionIndex.PrincipalPermissionIndex; } } }
// 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.Buffers; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace System.IO.Compression { public partial class DeflateStream : Stream { internal const int DefaultBufferSize = 8192; private Stream _stream; private CompressionMode _mode; private bool _leaveOpen; private Inflater _inflater; private Deflater _deflater; private byte[] _buffer; private int _asyncOperations; private bool _wroteBytes; #region Public Constructors public DeflateStream(Stream stream, CompressionMode mode): this(stream, mode, false) { } public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, leaveOpen, ZLibNative.Deflate_DefaultWindowBits) { } // Implies mode = Compress public DeflateStream(Stream stream, CompressionLevel compressionLevel) : this(stream, compressionLevel, false) { } // Implies mode = Compress public DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) : this(stream, compressionLevel, leaveOpen, ZLibNative.Deflate_DefaultWindowBits) { } #endregion #region Private Constructors and Initializers /// <summary> /// Internal constructor to check stream validity and call the correct initalization function depending on /// the value of the CompressionMode given. /// </summary> internal DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen, int windowBits) { if (stream == null) throw new ArgumentNullException(nameof(stream)); switch (mode) { case CompressionMode.Decompress: InitializeInflater(stream, leaveOpen, windowBits); break; case CompressionMode.Compress: InitializeDeflater(stream, leaveOpen, windowBits, CompressionLevel.Optimal); break; default: throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(mode)); } } /// <summary> /// Internal constructor to specify the compressionlevel as well as the windowbits /// </summary> internal DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen, int windowBits) { if (stream == null) throw new ArgumentNullException(nameof(stream)); InitializeDeflater(stream, leaveOpen, windowBits, compressionLevel); } /// <summary> /// Sets up this DeflateStream to be used for Zlib Inflation/Decompression /// </summary> internal void InitializeInflater(Stream stream, bool leaveOpen, int windowBits) { Debug.Assert(stream != null); if (!stream.CanRead) throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream)); _inflater = new Inflater(windowBits); _stream = stream; _mode = CompressionMode.Decompress; _leaveOpen = leaveOpen; _buffer = ArrayPool<byte>.Shared.Rent(DefaultBufferSize); } /// <summary> /// Sets up this DeflateStream to be used for Zlib Deflation/Compression /// </summary> internal void InitializeDeflater(Stream stream, bool leaveOpen, int windowBits, CompressionLevel compressionLevel) { Debug.Assert(stream != null); if (!stream.CanWrite) throw new ArgumentException(SR.NotSupported_UnwritableStream, nameof(stream)); _deflater = new Deflater(compressionLevel, windowBits); _stream = stream; _mode = CompressionMode.Compress; _leaveOpen = leaveOpen; _buffer = ArrayPool<byte>.Shared.Rent(DefaultBufferSize); } #endregion public Stream BaseStream { get { return _stream; } } public override bool CanRead { get { if (_stream == null) { return false; } return (_mode == CompressionMode.Decompress && _stream.CanRead); } } public override bool CanWrite { get { if (_stream == null) { return false; } return (_mode == CompressionMode.Compress && _stream.CanWrite); } } public override bool CanSeek { get { return false; } } public override long Length { get { throw new NotSupportedException(SR.NotSupported); } } public override long Position { get { throw new NotSupportedException(SR.NotSupported); } set { throw new NotSupportedException(SR.NotSupported); } } public override void Flush() { EnsureNotDisposed(); if (_mode == CompressionMode.Compress) FlushBuffers(); } public override Task FlushAsync(CancellationToken cancellationToken) { if (_asyncOperations != 0) throw new InvalidOperationException(SR.InvalidBeginCall); EnsureNotDisposed(); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return _mode != CompressionMode.Compress || !_wroteBytes ? Task.CompletedTask : FlushAsyncCore(cancellationToken); } private async Task FlushAsyncCore(CancellationToken cancellationToken) { Interlocked.Increment(ref _asyncOperations); try { // Compress any bytes left: await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); // Pull out any bytes left inside deflater: bool flushSuccessful; do { int compressedBytes; flushSuccessful = _deflater.Flush(_buffer, out compressedBytes); if (flushSuccessful) { await _stream.WriteAsync(_buffer, 0, compressedBytes, cancellationToken).ConfigureAwait(false); } Debug.Assert(flushSuccessful == (compressedBytes > 0)); } while (flushSuccessful); } finally { Interlocked.Decrement(ref _asyncOperations); } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.NotSupported); } public override void SetLength(long value) { throw new NotSupportedException(SR.NotSupported); } public override int ReadByte() { EnsureDecompressionMode(); EnsureNotDisposed(); // Try to read a single byte from zlib without allocating an array, pinning an array, etc. // If zlib doesn't have any data, fall back to the base stream implementation, which will do that. byte b; return _inflater.Inflate(out b) ? b : base.ReadByte(); } public override int Read(byte[] array, int offset, int count) { EnsureDecompressionMode(); ValidateParameters(array, offset, count); EnsureNotDisposed(); int bytesRead; int currentOffset = offset; int remainingCount = count; while (true) { bytesRead = _inflater.Inflate(array, currentOffset, remainingCount); currentOffset += bytesRead; remainingCount -= bytesRead; if (remainingCount == 0) { break; } if (_inflater.Finished()) { // if we finished decompressing, we can't have anything left in the outputwindow. Debug.Assert(_inflater.AvailableOutput == 0, "We should have copied all stuff out!"); break; } int bytes = _stream.Read(_buffer, 0, _buffer.Length); if (bytes <= 0) { break; } else if (bytes > _buffer.Length) { // The stream is either malicious or poorly implemented and returned a number of // bytes larger than the buffer supplied to it. throw new InvalidDataException(SR.GenericInvalidData); } _inflater.SetInput(_buffer, 0, bytes); } return count - remainingCount; } private void ValidateParameters(byte[] array, int offset, int count) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (array.Length - offset < count) throw new ArgumentException(SR.InvalidArgumentOffsetCount); } private void EnsureNotDisposed() { if (_stream == null) ThrowStreamClosedException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowStreamClosedException() { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } private void EnsureDecompressionMode() { if (_mode != CompressionMode.Decompress) ThrowCannotReadFromDeflateStreamException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowCannotReadFromDeflateStreamException() { throw new InvalidOperationException(SR.CannotReadFromDeflateStream); } private void EnsureCompressionMode() { if (_mode != CompressionMode.Compress) ThrowCannotWriteToDeflateStreamException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowCannotWriteToDeflateStreamException() { throw new InvalidOperationException(SR.CannotWriteToDeflateStream); } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { return StreamHelpers.ArrayPoolCopyToAsync(this, destination, bufferSize, cancellationToken); } public override Task<int> ReadAsync(Byte[] array, int offset, int count, CancellationToken cancellationToken) { EnsureDecompressionMode(); // We use this checking order for compat to earlier versions: if (_asyncOperations != 0) throw new InvalidOperationException(SR.InvalidBeginCall); ValidateParameters(array, offset, count); EnsureNotDisposed(); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } Interlocked.Increment(ref _asyncOperations); Task<int> readTask = null; try { // Try to read decompressed data in output buffer int bytesRead = _inflater.Inflate(array, offset, count); if (bytesRead != 0) { // If decompression output buffer is not empty, return immediately. return Task.FromResult(bytesRead); } if (_inflater.Finished()) { // end of compression stream return Task.FromResult(0); } // If there is no data on the output buffer and we are not at // the end of the stream, we need to get more data from the base stream readTask = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken); if (readTask == null) { throw new InvalidOperationException(SR.NotSupported_UnreadableStream); } return ReadAsyncCore(readTask, array, offset, count, cancellationToken); } finally { // if we haven't started any async work, decrement the counter to end the transaction if (readTask == null) { Interlocked.Decrement(ref _asyncOperations); } } } private async Task<int> ReadAsyncCore(Task<int> readTask, byte[] array, int offset, int count, CancellationToken cancellationToken) { try { while (true) { int bytesRead = await readTask.ConfigureAwait(false); EnsureNotDisposed(); if (bytesRead <= 0) { // This indicates the base stream has received EOF return 0; } else if (bytesRead > _buffer.Length) { // The stream is either malicious or poorly implemented and returned a number of // bytes larger than the buffer supplied to it. throw new InvalidDataException(SR.GenericInvalidData); } cancellationToken.ThrowIfCancellationRequested(); // Feed the data from base stream into decompression engine _inflater.SetInput(_buffer, 0, bytesRead); bytesRead = _inflater.Inflate(array, offset, count); if (bytesRead == 0 && !_inflater.Finished()) { // We could have read in head information and didn't get any data. // Read from the base stream again. readTask = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken); if (readTask == null) { throw new InvalidOperationException(SR.NotSupported_UnreadableStream); } } else { return bytesRead; } } } finally { Interlocked.Decrement(ref _asyncOperations); } } public override void Write(byte[] array, int offset, int count) { // Validate the state and the parameters EnsureCompressionMode(); ValidateParameters(array, offset, count); EnsureNotDisposed(); // Write compressed the bytes we already passed to the deflater: WriteDeflaterOutput(); // Pass new bytes through deflater and write them too: _deflater.SetInput(array, offset, count); WriteDeflaterOutput(); _wroteBytes = true; } private void WriteDeflaterOutput() { while (!_deflater.NeedsInput()) { int compressedBytes = _deflater.GetDeflateOutput(_buffer); if (compressedBytes > 0) { _stream.Write(_buffer, 0, compressedBytes); } } } // This is called by Flush: private void FlushBuffers() { // Make sure to only "flush" when we actually had some input: if (_wroteBytes) { // Compress any bytes left: WriteDeflaterOutput(); // Pull out any bytes left inside deflater: bool flushSuccessful; do { int compressedBytes; flushSuccessful = _deflater.Flush(_buffer, out compressedBytes); if (flushSuccessful) { _stream.Write(_buffer, 0, compressedBytes); } Debug.Assert(flushSuccessful == (compressedBytes > 0)); } while (flushSuccessful); } } // This is called by Dispose: private void PurgeBuffers(bool disposing) { if (!disposing) return; if (_stream == null) return; if (_mode != CompressionMode.Compress) return; // Some deflaters (e.g. ZLib) write more than zero bytes for zero byte inputs. // This round-trips and we should be ok with this, but our legacy managed deflater // always wrote zero output for zero input and upstack code (e.g. ZipArchiveEntry) // took dependencies on it. Thus, make sure to only "flush" when we actually had // some input: if (_wroteBytes) { // Compress any bytes left WriteDeflaterOutput(); // Pull out any bytes left inside deflater: bool finished; do { int compressedBytes; finished = _deflater.Finish(_buffer, out compressedBytes); if (compressedBytes > 0) _stream.Write(_buffer, 0, compressedBytes); } while (!finished); } else { // In case of zero length buffer, we still need to clean up the native created stream before // the object get disposed because eventually ZLibNative.ReleaseHandle will get called during // the dispose operation and although it frees the stream but it return error code because the // stream state was still marked as in use. The symptoms of this problem will not be seen except // if running any diagnostic tools which check for disposing safe handle objects bool finished; do { int compressedBytes; finished = _deflater.Finish(_buffer, out compressedBytes); } while (!finished); } } protected override void Dispose(bool disposing) { try { PurgeBuffers(disposing); } finally { // Close the underlying stream even if PurgeBuffers threw. // Stream.Close() may throw here (may or may not be due to the same error). // In this case, we still need to clean up internal resources, hence the inner finally blocks. try { if (disposing && !_leaveOpen && _stream != null) _stream.Dispose(); } finally { _stream = null; try { if (_deflater != null) _deflater.Dispose(); if (_inflater != null) _inflater.Dispose(); } finally { if (_buffer != null) ArrayPool<byte>.Shared.Return(_buffer, clearArray: true); _buffer = null; _deflater = null; _inflater = null; base.Dispose(disposing); } } } } public override Task WriteAsync(Byte[] array, int offset, int count, CancellationToken cancellationToken) { EnsureCompressionMode(); // We use this checking order for compat to earlier versions: if (_asyncOperations != 0) throw new InvalidOperationException(SR.InvalidBeginCall); ValidateParameters(array, offset, count); EnsureNotDisposed(); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); return WriteAsyncCore(array, offset, count, cancellationToken); } private async Task WriteAsyncCore(Byte[] array, int offset, int count, CancellationToken cancellationToken) { Interlocked.Increment(ref _asyncOperations); try { await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); // Pass new bytes through deflater _deflater.SetInput(array, offset, count); await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); _wroteBytes = true; } finally { Interlocked.Decrement(ref _asyncOperations); } } /// <summary> /// Writes the bytes that have already been deflated /// </summary> private async Task WriteDeflaterOutputAsync(CancellationToken cancellationToken) { while (!_deflater.NeedsInput()) { int compressedBytes = _deflater.GetDeflateOutput(_buffer); if (compressedBytes > 0) { await _stream.WriteAsync(_buffer, 0, compressedBytes, cancellationToken).ConfigureAwait(false); } } } } }
using Core.IO; using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; #if WINRT using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Streams; #elif WINDOWS_PHONE || SILVERLIGHT using System.IO.IsolatedStorage; #endif namespace Core { public class WinVSystem : VSystem { #region Preamble #if TEST || DEBUG static bool OsTrace = false; protected static void OSTRACE(string x, params object[] args) { if (OsTrace) Console.WriteLine("b:" + string.Format(x, args)); } #else protected static void OSTRACE(string x, params object[] args) { } #endif #if TEST static int io_error_hit = 0; // Total number of I/O Errors static int io_error_hardhit = 0; // Number of non-benign errors static int io_error_pending = 0; // Count down to first I/O error static bool io_error_persist = false; // True if I/O errors persist static bool io_error_benign = false; // True if errors are benign static int diskfull_pending = 0; public static bool diskfull = false; protected static void SimulateIOErrorBenign(bool X) { io_error_benign = X; } protected static bool SimulateIOError() { if ((io_error_persist && io_error_hit > 0) || io_error_pending-- == 1) { local_ioerr(); return true; } return false; } protected static void local_ioerr() { OSTRACE("IOERR\n"); io_error_hit++; if (!io_error_benign) io_error_hardhit++; } protected static bool SimulateDiskfullError() { if (diskfull_pending > 0) { if (diskfull_pending == 1) { local_ioerr(); diskfull = true; io_error_hit = 1; return true; } else diskfull_pending--; } return false; } #else protected static void SimulateIOErrorBenign(bool X) { } protected static bool SimulateIOError() { return false; } protected static bool SimulateDiskfullError() { return false; } #endif // When testing, keep a count of the number of open files. #if TEST static int open_file_count = 0; protected static void OpenCounter(int X) { open_file_count += X; } #else protected static void OpenCounter(int X) { } #endif #endregion #region Polyfill const int INVALID_FILE_ATTRIBUTES = -1; const int INVALID_SET_FILE_POINTER = -1; #if OS_WINCE #elif WINRT static bool isNT() { return true; } #else static bool isNT() { return Environment.OSVersion.Platform >= PlatformID.Win32NT; } #endif const long ERROR_FILE_NOT_FOUND = 2L; const long ERROR_HANDLE_DISK_FULL = 39L; const long ERROR_NOT_SUPPORTED = 50L; const long ERROR_DISK_FULL = 112L; #if WINRT public static bool FileExists(string path) { bool exists = true; try { Task<StorageFile> fileTask = StorageFile.GetFileFromPathAsync(path).AsTask<StorageFile>(); fileTask.Wait(); } catch (Exception) { var ae = (e as AggregateException); if (ae != null && ae.InnerException is FileNotFoundException) exists = false; } return exists; } #endif #endregion #region WinVFile public class WinShm { } public partial class WinVFile : VFile { public VSystem Vfs; // The VFS used to open this file #if WINRT public IRandomAccessStream H; // Filestream access to this file #else public FileStream H; // Filestream access to this file #endif public LOCK Lock_; // Type of lock currently held on this file public int SharedLockByte; // Randomly chosen byte used as a shared lock public uint LastErrno; // The Windows errno from the last I/O error public uint SectorSize; // Sector size of the device file is on #if !OMIT_WAL public WinShm Shm; // Instance of shared memory on this file #else public object Shm; // DUMMY Instance of shared memory on this file #endif public string Path; // Full pathname of this file public int SizeChunk; // Chunk size configured by FCNTL_CHUNK_SIZE public void memset() { H = null; Lock_ = 0; SharedLockByte = 0; LastErrno = 0; SectorSize = 0; } }; #endregion #region OS Errors static RC getLastErrorMsg(ref string buf) { #if SILVERLIGHT || WINRT buf = "Unknown error"; #else buf = Marshal.GetLastWin32Error().ToString(); #endif return RC.OK; } static RC winLogError(RC a, string b, string c) { #if !WINRT var st = new StackTrace(new StackFrame(true)); var sf = st.GetFrame(0); return winLogErrorAtLine(a, b, c, sf.GetFileLineNumber()); #else return winLogErrorAtLine(a, b, c, 0); #endif } static RC winLogErrorAtLine(RC errcode, string func, string path, int line) { #if SILVERLIGHT || WINRT uint errno = (uint)ERROR_NOT_SUPPORTED; // Error code #else uint errno = (uint)Marshal.GetLastWin32Error(); // Error code #endif string msg = null; // Human readable error text getLastErrorMsg(ref msg); Debug.Assert(errcode != RC.OK); if (path == null) path = string.Empty; int i; for (i = 0; i < msg.Length && msg[i] != '\r' && msg[i] != '\n'; i++) { } msg = msg.Substring(0, i); SysEx.LOG(errcode, "os_win.c:%d: (%d) %s(%s) - %s", line, errno, func, path, msg); return errcode; } #endregion #region Locking public static bool IsRunningMediumTrust() { // this is where it needs to check if it's running in an ASP.Net MediumTrust or lower environment // in order to pick the appropriate locking strategy #if SILVERLIGHT || WINRT return true; #else return false; #endif } private static LockingStrategy _lockingStrategy = (IsRunningMediumTrust() ? new MediumTrustLockingStrategy() : new LockingStrategy()); /// <summary> /// Basic locking strategy for Console/Winform applications /// </summary> private class LockingStrategy { #if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT) [DllImport("kernel32.dll")] static extern bool LockFileEx(IntPtr hFile, uint dwFlags, uint dwReserved, uint nNumberOfBytesToLockLow, uint nNumberOfBytesToLockHigh, [In] ref System.Threading.NativeOverlapped lpOverlapped); const int LOCKFILE_FAIL_IMMEDIATELY = 1; #endif public virtual void LockFile(WinVFile file, long offset, long length) { #if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT) file.H.Lock(offset, length); #endif } public virtual int SharedLockFile(WinVFile file, long offset, long length) { #if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT) Debug.Assert(length == VFile.SHARED_SIZE); Debug.Assert(offset == VFile.SHARED_FIRST); var ovlp = new NativeOverlapped(); ovlp.OffsetLow = (int)offset; ovlp.OffsetHigh = 0; ovlp.EventHandle = IntPtr.Zero; //SafeFileHandle.DangerousGetHandle().ToInt32() return (LockFileEx(file.H.Handle, LOCKFILE_FAIL_IMMEDIATELY, 0, (uint)length, 0, ref ovlp) ? 1 : 0); #else return 1; #endif } public virtual void UnlockFile(WinVFile file, long offset, long length) { #if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT) file.H.Unlock(offset, length); #endif } } /// <summary> /// Locking strategy for Medium Trust. It uses the same trick used in the native code for WIN_CE /// which doesn't support LockFileEx as well. /// </summary> private class MediumTrustLockingStrategy : LockingStrategy { public override int SharedLockFile(WinVFile file, long offset, long length) { #if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT) Debug.Assert(length == VFile.SHARED_SIZE); Debug.Assert(offset == VFile.SHARED_FIRST); try { file.H.Lock(offset + file.SharedLockByte, 1); } catch (IOException) { return 0; } #endif return 1; } } #endregion #region WinVFile public partial class WinVFile : VFile { static int seekWinFile(WinVFile file, long offset) { try { #if WINRT file.H.Seek((ulong)offset); #else file.H.Seek(offset, SeekOrigin.Begin); #endif } catch (Exception) { #if SILVERLIGHT || WINRT file.LastErrno = 1; #else file.LastErrno = (uint)Marshal.GetLastWin32Error(); #endif winLogError(RC.IOERR_SEEK, "seekWinFile", file.Path); return 1; } return 0; } public static int MX_CLOSE_ATTEMPT = 3; public override RC Close() { #if !OMIT_WAL Debug.Assert(Shm == null); #endif OSTRACE("CLOSE %d (%s)\n", H.GetHashCode(), H.Name); bool rc; int cnt = 0; do { #if WINRT H.Dispose(); #else H.Close(); #endif rc = true; } while (!rc && ++cnt < MX_CLOSE_ATTEMPT); OSTRACE("CLOSE %d %s\n", H.GetHashCode(), rc ? "ok" : "failed"); if (rc) H = null; OpenCounter(-1); return (rc ? RC.OK : winLogError(RC.IOERR_CLOSE, "winClose", Path)); } public override RC Read(byte[] buffer, int amount, long offset) { //if (buffer == null) // buffer = new byte[amount]; if (SimulateIOError()) return RC.IOERR_READ; OSTRACE("READ %d lock=%d\n", H.GetHashCode(), Lock_); if (!H.CanRead) return RC.IOERR_READ; if (seekWinFile(this, offset) != 0) return RC.FULL; int read; // Number of bytes actually read from file try { #if WINRT var stream = H.AsStreamForRead(); read = stream.Read(buffer, 0, amount); #else read = H.Read(buffer, 0, amount); #endif } catch (Exception) { #if SILVERLIGHT || WINRT LastErrno = 1; #else LastErrno = (uint)Marshal.GetLastWin32Error(); #endif return winLogError(RC.IOERR_READ, "winRead", Path); } if (read < amount) { // Unread parts of the buffer must be zero-filled Array.Clear(buffer, (int)read, (int)(amount - read)); return RC.IOERR_SHORT_READ; } return RC.OK; } public override RC Write(byte[] buffer, int amount, long offset) { Debug.Assert(amount > 0); if (SimulateIOError()) return RC.IOERR_WRITE; if (SimulateDiskfullError()) return RC.FULL; OSTRACE("WRITE %d lock=%d\n", H.GetHashCode(), Lock_); int rc = seekWinFile(this, offset); // True if error has occured, else false #if WINRT ulong wrote = H.Position; #else long wrote = H.Position; #endif try { Debug.Assert(buffer.Length >= amount); #if WINRT var stream = H.AsStreamForWrite(); stream.Write(buffer, 0, amount); #else H.Write(buffer, 0, amount); #endif rc = 1; wrote = H.Position - wrote; } catch (IOException) { return RC.READONLY; } if (rc == 0 || amount > (int)wrote) { #if SILVERLIGHT || WINRT LastErrno = 1; #else LastErrno = (uint)Marshal.GetLastWin32Error(); #endif if (LastErrno == ERROR_HANDLE_DISK_FULL || LastErrno == ERROR_DISK_FULL) return RC.FULL; else return winLogError(RC.IOERR_WRITE, "winWrite", Path); } return RC.OK; } public override RC Truncate(long size) { RC rc = RC.OK; OSTRACE("TRUNCATE %d %lld\n", H.Name, size); if (SimulateIOError()) return RC.IOERR_TRUNCATE; // If the user has configured a chunk-size for this file, truncate the file so that it consists of an integer number of chunks (i.e. the // actual file size after the operation may be larger than the requested size). if (SizeChunk > 0) size = ((size + SizeChunk - 1) / SizeChunk) * SizeChunk; try { #if WINRT H.Size = (ulong)size; #else H.SetLength(size); #endif rc = RC.OK; } catch (IOException) { #if SILVERLIGHT || WINRT LastErrno = 1; #else LastErrno = (uint)Marshal.GetLastWin32Error(); #endif rc = winLogError(RC.IOERR_TRUNCATE, "winTruncate2", Path); } OSTRACE("TRUNCATE %d %lld %s\n", H.GetHashCode(), size, rc == RC.OK ? "ok" : "failed"); return rc; } #if TEST // Count the number of fullsyncs and normal syncs. This is used to test that syncs and fullsyncs are occuring at the right times. #if !TCLSH static int sync_count = 0; static int fullsync_count = 0; #else static tcl.lang.Var.SQLITE3_GETSET sync_count = new tcl.lang.Var.SQLITE3_GETSET("sync_count"); static tcl.lang.Var.SQLITE3_GETSET fullsync_count = new tcl.lang.Var.SQLITE3_GETSET("fullsync_count"); #endif #endif public override RC Sync(SYNC flags) { // Check that one of SQLITE_SYNC_NORMAL or FULL was passed Debug.Assert(((int)flags & 0x0F) == (int)SYNC.NORMAL || ((int)flags & 0x0F) == (int)SYNC.FULL); OSTRACE("SYNC %d lock=%d\n", H.GetHashCode(), Lock_); // Unix cannot, but some systems may return SQLITE_FULL from here. This line is to test that doing so does not cause any problems. if (SimulateDiskfullError()) return RC.FULL; #if TEST if (((int)flags & 0x0F) == (int)SYNC.FULL) #if !TCLSH fullsync_count++; sync_count++; #else fullsync_count.iValue++; sync_count.iValue++; #endif #endif #if NO_SYNC // If we compiled with the SQLITE_NO_SYNC flag, then syncing is a no-op return RC_OK; #elif WINRT var stream = H.AsStreamForWrite(); stream.Flush(); return RC.OK; #else H.Flush(); return RC.OK; #endif } public override RC get_FileSize(out long size) { if (SimulateIOError()) { size = 0; return RC.IOERR_FSTAT; } #if WINRT size = (H.CanRead ? (long)H.Size : 0); #else size = (H.CanRead ? H.Length : 0); #endif return RC.OK; } static int getReadLock(WinVFile file) { int res = 0; if (isNT()) res = _lockingStrategy.SharedLockFile(file, SHARED_FIRST, SHARED_SIZE); // isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. #if !OS_WINCE else { Debugger.Break(); // int lk; // sqlite3_randomness(lk.Length, lk); // pFile.sharedLockByte = (u16)((lk & 0x7fffffff)%(SHARED_SIZE - 1)); // res = pFile.fs.Lock( SHARED_FIRST + pFile.sharedLockByte, 0, 1, 0); } #endif if (res == 0) #if SILVERLIGHT || WINRT file.LastErrno = 1; #else file.LastErrno = (uint)Marshal.GetLastWin32Error(); #endif // No need to log a failure to lock return res; } static int unlockReadLock(WinVFile file) { int res = 1; if (isNT()) try { _lockingStrategy.UnlockFile(file, SHARED_FIRST, SHARED_SIZE); } catch (Exception) { res = 0; } // isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. #if !OS_WINCE else Debugger.Break(); #endif if (res == 0) { #if SILVERLIGHT || WINRT file.LastErrno = 1; #else file.LastErrno = (uint)Marshal.GetLastWin32Error(); #endif winLogError(RC.IOERR_UNLOCK, "unlockReadLock", file.Path); } return res; } public override RC Lock(LOCK lock_) { OSTRACE("LOCK %d %d was %d(%d)\n", H.GetHashCode(), lock_, Lock_, SharedLockByte); // If there is already a lock of this type or more restrictive on the OsFile, do nothing. Don't use the end_lock: exit path, as // sqlite3OsEnterMutex() hasn't been called yet. if (Lock_ >= lock_) return RC.OK; // Make sure the locking sequence is correct Debug.Assert(lock_ != LOCK.NO || lock_ == LOCK.SHARED); Debug.Assert(lock_ != LOCK.PENDING); Debug.Assert(lock_ != LOCK.RESERVED || Lock_ == LOCK.SHARED); // Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or a SHARED lock. If we are acquiring a SHARED lock, the acquisition of // the PENDING_LOCK byte is temporary. LOCK newLock = Lock_; // Set pFile.locktype to this value before exiting int res = 1; // Result of a windows lock call bool gotPendingLock = false;// True if we acquired a PENDING lock this time uint lastErrno = 0; if (Lock_ == LOCK.NO || (lock_ == LOCK.EXCLUSIVE && Lock_ == LOCK.RESERVED)) { res = 0; int cnt = 3; while (cnt-- > 0 && res == 0) { try { _lockingStrategy.LockFile(this, PENDING_BYTE, 1); res = 1; } catch (Exception) { // Try 3 times to get the pending lock. The pending lock might be held by another reader process who will release it momentarily. OSTRACE("could not get a PENDING lock. cnt=%d\n", cnt); #if WINRT System.Threading.Tasks.Task.Delay(1).Wait(); #else Thread.Sleep(1); #endif } } gotPendingLock = (res != 0); if (res == 0) #if SILVERLIGHT || WINRT lastErrno = 1; #else lastErrno = (uint)Marshal.GetLastWin32Error(); #endif } // Acquire a SHARED lock if (lock_ == LOCK.SHARED && res != 0) { Debug.Assert(Lock_ == LOCK.NO); res = getReadLock(this); if (res != 0) newLock = LOCK.SHARED; else #if SILVERLIGHT || WINRT lastErrno = 1; #else lastErrno = (uint)Marshal.GetLastWin32Error(); #endif } // Acquire a RESERVED lock if (lock_ == LOCK.RESERVED && res != 0) { Debug.Assert(Lock_ == LOCK.SHARED); try { _lockingStrategy.LockFile(this, RESERVED_BYTE, 1); newLock = LOCK.RESERVED; res = 1; } catch (Exception) { res = 0; } if (res != 0) newLock = LOCK.RESERVED; else #if SILVERLIGHT lastErrno = 1; #else lastErrno = (uint)Marshal.GetLastWin32Error(); #endif } // Acquire a PENDING lock if (lock_ == LOCK.EXCLUSIVE && res != 0) { newLock = LOCK.PENDING; gotPendingLock = false; } // Acquire an EXCLUSIVE lock if (lock_ == LOCK.EXCLUSIVE && res != 0) { Debug.Assert(Lock_ >= LOCK.SHARED); res = unlockReadLock(this); OSTRACE("unreadlock = %d\n", res); try { _lockingStrategy.LockFile(this, SHARED_FIRST, SHARED_SIZE); newLock = LOCK.EXCLUSIVE; res = 1; } catch (Exception) { res = 0; } if (res != 0) newLock = LOCK.EXCLUSIVE; else { #if SILVERLIGHT || WINRT lastErrno = 1; #else lastErrno = (uint)Marshal.GetLastWin32Error(); #endif OSTRACE("error-code = %d\n", lastErrno); getReadLock(this); } } // If we are holding a PENDING lock that ought to be released, then release it now. if (gotPendingLock && lock_ == LOCK.SHARED) _lockingStrategy.UnlockFile(this, PENDING_BYTE, 1); // Update the state of the lock has held in the file descriptor then return the appropriate result code. RC rc; if (res != 0) rc = RC.OK; else { OSTRACE("LOCK FAILED %d trying for %d but got %d\n", H.GetHashCode(), lock_, newLock); LastErrno = lastErrno; rc = RC.BUSY; } Lock_ = newLock; return rc; } public override RC CheckReservedLock(ref int resOut) { if (SimulateIOError()) return RC.IOERR_CHECKRESERVEDLOCK; int rc; if (Lock_ >= LOCK.RESERVED) { rc = 1; OSTRACE("TEST WR-LOCK %d %d (local)\n", H.Name, rc); } else { try { _lockingStrategy.LockFile(this, RESERVED_BYTE, 1); _lockingStrategy.UnlockFile(this, RESERVED_BYTE, 1); rc = 1; } catch (IOException) { rc = 0; } rc = 1 - rc; OSTRACE("TEST WR-LOCK %d %d (remote)\n", H.GetHashCode(), rc); } resOut = rc; return RC.OK; } public override RC Unlock(LOCK lock_) { Debug.Assert(lock_ <= LOCK.SHARED); OSTRACE("UNLOCK %d to %d was %d(%d)\n", H.GetHashCode(), lock_, Lock_, SharedLockByte); var rc = RC.OK; LOCK type = Lock_; if (type >= LOCK.EXCLUSIVE) { _lockingStrategy.UnlockFile(this, SHARED_FIRST, SHARED_SIZE); if (lock_ == LOCK.SHARED && getReadLock(this) == 0) // This should never happen. We should always be able to reacquire the read lock rc = winLogError(RC.IOERR_UNLOCK, "winUnlock", Path); } if (type >= LOCK.RESERVED) try { _lockingStrategy.UnlockFile(this, RESERVED_BYTE, 1); } catch (Exception) { } if (lock_ == LOCK.NO && type >= LOCK.SHARED) unlockReadLock(this); if (type >= LOCK.PENDING) try { _lockingStrategy.UnlockFile(this, PENDING_BYTE, 1); } catch (Exception) { } Lock_ = lock_; return rc; } //static void winModeBit(WinVFile file, char mask, ref long arg) //{ // if (arg < 0) // arg = ((file.CtrlFlags & mask) != 0); // else if (arg == 0) // file.CtrlFlags &= ~mask; // else // file.CtrlFlags |= mask; //} public override RC FileControl(FCNTL op, ref long arg) { switch (op) { case FCNTL.LOCKSTATE: arg = (int)Lock_; return RC.OK; case FCNTL.LAST_ERRNO: arg = (int)LastErrno; return RC.OK; case FCNTL.CHUNK_SIZE: SizeChunk = (int)arg; return RC.OK; case FCNTL.SIZE_HINT: if (SizeChunk > 0) { long oldSize; var rc = get_FileSize(out oldSize); if (rc == RC.OK) { var newSize = (long)arg; if (newSize > oldSize) { SimulateIOErrorBenign(true); Truncate(newSize); SimulateIOErrorBenign(false); } } return rc; } return RC.OK; case FCNTL.PERSIST_WAL: //winModeBit(this, WINFILE_PERSIST_WAL, ref arg); return RC.OK; case FCNTL.POWERSAFE_OVERWRITE: //winModeBit(this, WINFILE_PSOW, ref arg); return RC.OK; //case FCNTL.VFSNAME: // arg = "win32"; // return RC.OK; //case FCNTL.WIN32_AV_RETRY: // int *a = (int*)arg; // if (a[0] > 0) // win32IoerrRetry = a[0]; // else // a[0] = win32IoerrRetry; // if (a[1] > 0) // win32IoerrRetryDelay = a[1]; // else // a[1] = win32IoerrRetryDelay; // return RC.OK; //case FCNTL.TEMPFILENAME: // var tfile = _alloc(Vfs->MaxPathname, true); // if (tfile) // { // getTempname(Vfs->MaxPathname, tfile); // *(char**)arg = tfile; // } // return RC.OK; } return RC.NOTFOUND; } public override uint get_SectorSize() { //return DEFAULT_SECTOR_SIZE; return SectorSize; } //public override IOCAP get_DeviceCharacteristics() { return 0; } #if !OMIT_WAL public override RC ShmMap(int region, int sizeRegion, bool isWrite, out object pp) { pp = null; return RC.OK; } public override RC ShmLock(int offset, int count, SHM flags) { return RC.OK; } public override void ShmBarrier() { } public override RC ShmUnmap(bool deleteFlag) { return RC.OK; } #endif } #endregion #region WinVSystem //static string ConvertUtf8Filename(string filename) //{ // return filename; //} // static RC getTempname(int bufLength, StringBuilder buf) // { // const string chars = "abcdefghijklmnopqrstuvwxyz0123456789"; // var random = new StringBuilder(20); // long randomValue = 0; // for (int i = 0; i < 15; i++) // { // sqlite3_randomness(1, ref randomValue); // random.Append((char)chars[(int)(randomValue % (chars.Length - 1))]); // } //#if WINRT // buf.Append(Path.Combine(ApplicationData.Current.LocalFolder.Path, TEMP_FILE_PREFIX + random.ToString())); //#else // buf.Append(Path.GetTempPath() + TEMP_FILE_PREFIX + random.ToString()); //#endif // OSTRACE("TEMP FILENAME: %s\n", buf.ToString()); // return RC.OK; // } public override RC Open(string name, VFile id, OPEN flags, out OPEN outFlags) { // 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed down into the VFS layer. Some SQLITE_OPEN_ flags (for example, // SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before reaching the VFS. flags = (OPEN)((uint)flags & 0x87f7f); outFlags = 0; var rc = RC.OK; var type = (OPEN)(int)((int)flags & 0xFFFFFF00); // Type of file to open var isExclusive = (flags & OPEN.EXCLUSIVE) != 0; var isDelete = (flags & OPEN.DELETEONCLOSE) != 0; var isCreate = (flags & OPEN.CREATE) != 0; var isReadonly = (flags & OPEN.READONLY) != 0; var isReadWrite = (flags & OPEN.READWRITE) != 0; var isOpenJournal = (isCreate && (type == OPEN.MASTER_JOURNAL || type == OPEN.MAIN_JOURNAL || type == OPEN.WAL)); // Check the following statements are true: // // (a) Exactly one of the READWRITE and READONLY flags must be set, and // (b) if CREATE is set, then READWRITE must also be set, and // (c) if EXCLUSIVE is set, then CREATE must also be set. // (d) if DELETEONCLOSE is set, then CREATE must also be set. Debug.Assert((!isReadonly || !isReadWrite) && (isReadWrite || isReadonly)); Debug.Assert(!isCreate || isReadWrite); Debug.Assert(!isExclusive || isCreate); Debug.Assert(!isDelete || isCreate); // The main DB, main journal, WAL file and master journal are never automatically deleted. Nor are they ever temporary files. //Debug.Assert((!isDelete && !string.IsNullOrEmpty(name)) || type != OPEN.MAIN_DB); Debug.Assert((!isDelete && !string.IsNullOrEmpty(name)) || type != OPEN.MAIN_JOURNAL); Debug.Assert((!isDelete && !string.IsNullOrEmpty(name)) || type != OPEN.MASTER_JOURNAL); Debug.Assert((!isDelete && !string.IsNullOrEmpty(name)) || type != OPEN.WAL); // Assert that the upper layer has set one of the "file-type" flags. Debug.Assert(type == OPEN.MAIN_DB || type == OPEN.TEMP_DB || type == OPEN.MAIN_JOURNAL || type == OPEN.TEMP_JOURNAL || type == OPEN.SUBJOURNAL || type == OPEN.MASTER_JOURNAL || type == OPEN.TRANSIENT_DB || type == OPEN.WAL); var file = (WinVFile)id; Debug.Assert(file != null); file.H = null; // If the second argument to this function is NULL, generate a temporary file name to use if (string.IsNullOrEmpty(name)) { Debug.Assert(isDelete && !isOpenJournal); name = Path.GetRandomFileName(); } // Convert the filename to the system encoding. if (name.StartsWith("/") && !name.StartsWith("//")) name = name.Substring(1); #if !WINRT FileAccess dwDesiredAccess; if (isReadWrite) dwDesiredAccess = FileAccess.Read | FileAccess.Write; else dwDesiredAccess = FileAccess.Read; // SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is created. SQLite doesn't use it to indicate "exclusive access" // as it is usually understood. FileMode dwCreationDisposition; if (isExclusive) // Creates a new file, only if it does not already exist. If the file exists, it fails. dwCreationDisposition = FileMode.CreateNew; else if (isCreate) // Open existing file, or create if it doesn't exist dwCreationDisposition = FileMode.OpenOrCreate; else // Opens a file, only if it exists. dwCreationDisposition = FileMode.Open; FileShare dwShareMode = FileShare.Read | FileShare.Write; #endif #if OS_WINCE uint dwDesiredAccess = 0; int isTemp = 0; #else #if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT) FileOptions dwFlagsAndAttributes; #endif #endif if (isDelete) { #if OS_WINCE dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; isTemp = 1; #else #if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT) dwFlagsAndAttributes = FileOptions.DeleteOnClose; #endif #endif } else { #if !(SILVERLIGHT || WINDOWS_MOBILE || SQLITE_WINRT) dwFlagsAndAttributes = FileOptions.None; #endif } // Reports from the internet are that performance is always better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. #if OS_WINCE dwFlagsAndAttributes |= FileOptions.RandomAccess; #endif #if WINRT IRandomAccessStream fs = null; DWORD dwDesiredAccess = 0; #else FileStream fs = null; #endif if (isNT()) { // retry opening the file a few times; this is because of a racing condition between a delete and open call to the FS int retries = 3; while (fs == null && retries > 0) try { retries--; #if WINRT Task<StorageFile> fileTask = null; if (isExclusive) { if (HelperMethods.FileExists(name)) // Error throw new IOException("file already exists"); else { Task<StorageFolder> folderTask = StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(name)).AsTask<StorageFolder>(); folderTask.Wait(); fileTask = folderTask.Result.CreateFileAsync(Path.GetFileName(name)).AsTask<StorageFile>(); } } else if (isCreate) { if (HelperMethods.FileExists(name)) fileTask = StorageFile.GetFileFromPathAsync(name).AsTask<StorageFile>(); else { Task<StorageFolder> folderTask = StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(name)).AsTask<StorageFolder>(); folderTask.Wait(); fileTask = folderTask.Result.CreateFileAsync(Path.GetFileName(name)).AsTask<StorageFile>(); } } else fileTask = StorageFile.GetFileFromPathAsync(name).AsTask<StorageFile>(); fileTask.Wait(); Task<IRandomAccessStream> streamTask = fileTask.Result.OpenAsync(FileAccessMode.ReadWriteUnsafe).AsTask<IRandomAccessStream>(); streamTask.Wait(); fs = streamTask.Result; #elif WINDOWS_PHONE || SILVERLIGHT fs = new IsolatedStorageFileStream(name, dwCreationDisposition, dwDesiredAccess, dwShareMode, IsolatedStorageFile.GetUserStoreForApplication()); #elif !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) fs = new FileStream(name, dwCreationDisposition, dwDesiredAccess, dwShareMode, 4096, dwFlagsAndAttributes); #else fs = new FileStream(name, dwCreationDisposition, dwDesiredAccess, dwShareMode, 4096); #endif OSTRACE("OPEN %d (%s)\n", fs.GetHashCode(), fs.Name); } catch (Exception) { #if WINRT System.Threading.Tasks.Task.Delay(100).Wait(); #else Thread.Sleep(100); #endif } // isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. Since the ASCII version of these Windows API do not exist for WINCE, // it's important to not reference them for WINCE builds. #if !OS_WINCE } else { Debugger.Break(); #endif } OSTRACE("OPEN {0} {1} 0x{2:x} {3}\n", file.GetHashCode(), name, dwDesiredAccess, fs == null ? "failed" : "ok"); if (fs == null || #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE || SQLITE_WINRT) fs.SafeFileHandle.IsInvalid #else !fs.CanRead #endif ) { #if SILVERLIGHT || WINRT file.LastErrno = 1; #else file.LastErrno = (uint)Marshal.GetLastWin32Error(); #endif winLogError(RC.CANTOPEN, "winOpen", name); if (isReadWrite) return Open(name, file, ((flags | OPEN.READONLY) & ~(OPEN.CREATE | OPEN.READWRITE)), out outFlags); else return SysEx.CANTOPEN_BKPT(); } outFlags = (isReadWrite ? OPEN.READWRITE : OPEN.READONLY); file.memset(); file.Opened = true; file.H = fs; file.LastErrno = 0; file.Vfs = this; file.Shm = null; file.Path = name; file.SectorSize = (uint)getSectorSize(this, name); #if OS_WINCE if (isReadWrite && type == OPEN.MAIN_DB && !winceCreateLock(name, file)) { CloseHandle(h); return SysEx.CANTOPEN_BKPT(); } if (isTemp) file.DeleteOnClose = name; #endif OpenCounter(+1); return rc; } static int MX_DELETION_ATTEMPTS = 5; public override RC Delete(string filename, bool syncDir) { if (SimulateIOError()) return RC.IOERR_DELETE; int cnt = 0; RC rc = RC.ERROR; if (isNT()) do { #if WINRT if(!HelperMethods.FileExists(filename)) #elif WINDOWS_PHONE if (!System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().FileExists(filename)) #elif SILVERLIGHT if (!IsolatedStorageFile.GetUserStoreForApplication().FileExists(filename)) #else if (!File.Exists(filename)) #endif { rc = RC.IOERR; break; } try { #if WINRT Task<StorageFile> fileTask = StorageFile.GetFileFromPathAsync(filename).AsTask<StorageFile>(); fileTask.Wait(); fileTask.Result.DeleteAsync().AsTask().Wait(); #elif WINDOWS_PHONE System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().DeleteFile(filename); #elif SILVERLIGHT IsolatedStorageFile.GetUserStoreForApplication().DeleteFile(filename); #else File.Delete(filename); #endif rc = RC.OK; } catch (IOException) { rc = RC.IOERR; #if WINRT System.Threading.Tasks.Task.Delay(100).Wait(); #else Thread.Sleep(100); #endif } } while (rc != RC.OK && ++cnt < MX_DELETION_ATTEMPTS); // isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. Since the ASCII version of these Windows API do not exist for WINCE, // it's important to not reference them for WINCE builds. #if !OS_WINCE && !WINRT else do { if (!File.Exists(filename)) { rc = RC.IOERR; break; } try { File.Delete(filename); rc = RC.OK; } catch (IOException) { rc = RC.IOERR; Thread.Sleep(100); } } while (rc != RC.OK && cnt++ < MX_DELETION_ATTEMPTS); #endif OSTRACE("DELETE \"%s\"\n", filename); if (rc == RC.OK) return rc; int lastErrno; #if SILVERLIGHT || WINRT lastErrno = (int)ERROR_NOT_SUPPORTED; #else lastErrno = Marshal.GetLastWin32Error(); #endif return (lastErrno == ERROR_FILE_NOT_FOUND ? RC.OK : winLogError(RC.IOERR_DELETE, "winDelete", filename)); } public override RC Access(string filename, ACCESS flags, out int resOut) { if (SimulateIOError()) { resOut = -1; return RC.IOERR_ACCESS; } // Do a quick test to prevent the try/catch block if (flags == ACCESS.EXISTS) { #if WINRT resOut = HelperMethods.FileExists(zFilename) ? 1 : 0; #elif WINDOWS_PHONE resOut = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().FileExists(zFilename) ? 1 : 0; #elif SILVERLIGHT resOut = IsolatedStorageFile.GetUserStoreForApplication().FileExists(zFilename) ? 1 : 0; #else resOut = File.Exists(filename) ? 1 : 0; #endif return RC.OK; } FileAttributes attr = 0; try { #if WINRT attr = FileAttributes.Normal; } #else #if WINDOWS_PHONE || WINDOWS_MOBILE || SILVERLIGHT if (new DirectoryInfo(filename).Exists) #else attr = File.GetAttributes(filename); if (attr == FileAttributes.Directory) #endif { try { var name = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); var fs = File.Create(name); fs.Close(); File.Delete(name); attr = FileAttributes.Normal; } catch (IOException) { attr = FileAttributes.ReadOnly; } } } // isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. Since the ASCII version of these Windows API do not exist for WINCE, // it's important to not reference them for WINCE builds. #if !OS_WINCE #endif #endif catch (IOException) { winLogError(RC.IOERR_ACCESS, "winAccess", filename); } int rc = 0; switch (flags) { case ACCESS.READ: case ACCESS.EXISTS: rc = attr != 0 ? 1 : 0; break; case ACCESS.READWRITE: rc = attr == 0 ? 0 : (int)(attr & FileAttributes.ReadOnly) != 0 ? 0 : 1; break; default: Debug.Assert("Invalid flags argument" == ""); rc = 0; break; } resOut = rc; return RC.OK; } public override RC FullPathname(string relative, out string full) { #if OS_WINCE if (SimulateIOError()) return RC.ERROR; // WinCE has no concept of a relative pathname, or so I am told. snprintf(MaxPathname, full, "%s", relative); return RC.OK; #endif #if !OS_WINCE full = null; // If this path name begins with "/X:", where "X" is any alphabetic character, discard the initial "/" from the pathname. if (relative[0] == '/' && Char.IsLetter(relative[1]) && relative[2] == ':') relative = relative.Substring(1); if (SimulateIOError()) return RC.ERROR; if (isNT()) { try { #if WINDOWS_PHONE || SILVERLIGHT || WINRT full = relative; #else full = Path.GetFullPath(relative); #endif } catch (Exception) { full = relative; } #if !SQLITE_OS_WINCE } else { Debugger.Break(); #endif } if (full.Length > MaxPathname) full = full.Substring(0, MaxPathname); return RC.OK; #endif } const int DEFAULT_SECTOR_SIZE = 512; static int getSectorSize(VSystem vfs, string relative) { return DEFAULT_SECTOR_SIZE; } #if !OMIT_LOAD_EXTENSION public override object DlOpen(string filename) { throw new NotSupportedException(); } public override void DlError(int bufLength, string buf) { throw new NotSupportedException(); } public override object DlSym(object handle, string symbol) { throw new NotSupportedException(); } public override void DlClose(object handle) { throw new NotSupportedException(); } #else public override object DlOpen(string filename) { return null; } public override void DlError(int byteLength, string errMsg) { return 0; } public override object DlSym(object data, string symbol) { return null; } public override void DlClose(object data) { return 0; } #endif public override int Randomness(int bufLength, byte[] buf) { int n = 0; #if TEST n = bufLength; Array.Clear(buf, 0, n); #else var sBuf = BitConverter.GetBytes(DateTime.Now.Ticks); buf[0] = sBuf[0]; buf[1] = sBuf[1]; buf[2] = sBuf[2]; buf[3] = sBuf[3]; n += 16; if (sizeof(uint) <= bufLength - n) { uint processId; #if !(SILVERLIGHT || WINRT) processId = (uint)Process.GetCurrentProcess().Id; #else processId = 28376023; #endif ConvertEx.Put4(buf, n, processId); n += 4; } if (sizeof(uint) <= bufLength - n) { var dt = new DateTime(); ConvertEx.Put4(buf, n, (uint)dt.Ticks);// memcpy(&zBuf[n], cnt, sizeof(cnt)); n += 4; } if (sizeof(long) <= bufLength - n) { long i; i = DateTime.UtcNow.Millisecond; ConvertEx.Put4(buf, n, (uint)(i & 0xFFFFFFFF)); ConvertEx.Put4(buf, n, (uint)(i >> 32)); n += sizeof(long); } #endif return n; } public override int Sleep(int microsec) { #if WINRT System.Threading.Tasks.Task.Delay(((microsec + 999) / 1000)).Wait(); #else Thread.Sleep(((microsec + 999) / 1000)); #endif return ((microsec + 999) / 1000) * 1000; } #if TEST #if !TCLSH static int current_time = 0; // Fake system time in seconds since 1970. #else static tcl.lang.Var.SQLITE3_GETSET current_time = new tcl.lang.Var.SQLITE3_GETSET("current_time"); #endif #endif public override RC CurrentTimeInt64(ref long now) { // FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). #if WINRT const long winRtEpoc = 17214255 * (long)8640000; #else const long winFiletimeEpoch = 23058135 * (long)8640000; #endif #if TEST const long unixEpoch = 24405875 * (long)8640000; #endif #if WINRT now = winRtEpoc + DateTime.UtcNow.Ticks / (long)10000; #else now = winFiletimeEpoch + DateTime.UtcNow.ToFileTimeUtc() / (long)10000; #endif #if TEST #if !TCLSH if (current_time != 0) now = 1000 * (long)current_time + unixEpoch; #else if (current_time.iValue != 0) now = 1000 * (long)current_time.iValue + unixEpoch; #endif #endif return RC.OK; } public override RC CurrentTime(ref double now) { long i = 0; var rc = CurrentTimeInt64(ref i); if (rc == RC.OK) now = i / 86400000.0; return rc; } public override RC GetLastError(int bufLength, ref string buf) { return getLastErrorMsg(ref buf); } #endregion } #region Bootstrap VSystem public abstract partial class VSystem { public static RC Initialize() { RegisterVfs(new WinVSystem(), true, () => new WinVSystem.WinVFile()); return RC.OK; } public static void Shutdown() { } } #endregion }
using IKVM.Attributes; using java.lang; using java.util; using System; using System.Runtime.CompilerServices; namespace lanterna.gui2.dialogs { //[Signature("<T:Ljava/lang/Object;>Lcom/googlecode/lanterna/gui2/dialogs/DialogWindow;")] public class ListSelectDialog : DialogWindow { //[Signature("TT;")] private object result; //[MethodImpl(MethodImplOptions.NoInlining)] public static void __<clinit>() { } //[LineNumberTable(15), Modifiers] //[MethodImpl(MethodImplOptions.NoInlining)] internal static void access_000(ListSelectDialog x0, object x1) { x0.onSelect(x1); } //[LineNumberTable(15), Modifiers] //[MethodImpl(MethodImplOptions.NoInlining)] internal static void access_100(ListSelectDialog x0) { x0.onCancel(); } //[LineNumberTable(new byte[] { 159, 121, 98, 105 })] //[MethodImpl(MethodImplOptions.NoInlining)] private void onCancel() { this.close(); } //[LineNumberTable(new byte[] { 159, 122, 66, 104, 105 }), Signature("(TT;)V")] //[MethodImpl(MethodImplOptions.NoInlining)] private void onSelect(object item) { this.result = item; this.close(); } //[LineNumberTable(new byte[] { 159, 106, 66, 103, 108, 108, 104, 102, 108 }), Signature("<T:Ljava/lang/Object;>(Lcom/googlecode/lanterna/gui2/WindowBasedTextGUI;Ljava/lang/String;Ljava/lang/String;Lcom/googlecode/lanterna/TerminalSize;[TT;)TT;")] //[MethodImpl(MethodImplOptions.NoInlining)] public static object showDialog(WindowBasedTextGUI textGUI, string title, string description, TerminalSize listBoxSize, params object[] items) { ListSelectDialog listSelectDialog = (ListSelectDialog)((ListSelectDialogBuilder)((ListSelectDialogBuilder)new ListSelectDialogBuilder().setTitle(title)).setDescription(description)).setListBoxSize(listBoxSize).addListItems(items).build(); return listSelectDialog.showDialog(textGUI); } //[LineNumberTable(new byte[] { 159, 118, 66, 104, 105 }), Signature("(Lcom/googlecode/lanterna/gui2/WindowBasedTextGUI;)TT;")] //[MethodImpl(MethodImplOptions.NoInlining)] public override object showDialog(WindowBasedTextGUI textGUI) { this.result = null; base.showDialog(textGUI); return this.result; } //[LineNumberTable(new byte[] { 159, 136, 97, 68, 106, 104, 106, 177, 104, 121, 247, 70, 131, 104, 138, 103, 230, 61, 199, 100, 111, 147, 110, 38, 237, 70, 103, 147, 103, 104, 117, 255, 5, 69, 235, 59, 231, 70, 111, 38, 237, 70, 135, 107 }), Signature("(Ljava/lang/String;Ljava/lang/String;Lcom/googlecode/lanterna/TerminalSize;ZLjava/util/List<TT;>;)V")] //[MethodImpl(MethodImplOptions.NoInlining)] internal ListSelectDialog(string title, string description, TerminalSize listBoxPreferredSize, bool canCancel, List content) : base(title) { this.result = null; if (content.isEmpty()) { string arg_2B_0 = "ListSelectDialog needs at least one item"; //Throwable.__<suppressFillInStackTrace>(); throw new IllegalStateException(arg_2B_0); } ActionListBox listBox = new ActionListBox(listBoxPreferredSize); Iterator iterator = content.iterator(); while (iterator.hasNext()) { object item = iterator.next(); listBox.addItem(java.lang.Object.instancehelper_toString(item), new ListSelectDialog_1(this, item)); } Panel mainPanel = new Panel(); mainPanel.setLayoutManager(new GridLayout(1).setLeftMarginSize(1).setRightMarginSize(1)); if (description != null) { mainPanel.addComponent(new Label(description)); mainPanel.addComponent(new EmptySpace(TerminalSize._ONE)); } ((ActionListBox)listBox.setLayoutData(GridLayout.createLayoutData(GridLayout.Alignment._FILL, GridLayout.Alignment._CENTER, true, false))).addTo(mainPanel); mainPanel.addComponent(new EmptySpace(TerminalSize._ONE)); if (canCancel) { Panel buttonPanel = new Panel(); buttonPanel.setLayoutManager(new GridLayout(2).setHorizontalSpacing(1)); buttonPanel.addComponent(new Button(LocalizedString._Cancel.toString(), new ListSelectDialog_2(this)).setLayoutData(GridLayout.createLayoutData(GridLayout.Alignment._CENTER, GridLayout.Alignment._CENTER, true, false))); ((Panel)buttonPanel.setLayoutData(GridLayout.createLayoutData(GridLayout.Alignment._END, GridLayout.Alignment._CENTER, false, false))).addTo(mainPanel); } this.setComponent(mainPanel); } //[LineNumberTable(111), Signature("<T:Ljava/lang/Object;>(Lcom/googlecode/lanterna/gui2/WindowBasedTextGUI;Ljava/lang/String;Ljava/lang/String;[TT;)TT;")] //[MethodImpl(MethodImplOptions.NoInlining)] public static object showDialog(WindowBasedTextGUI textGUI, string title, string description, params object[] items) { return ListSelectDialog.showDialog(textGUI, title, description, null, items); } //[LineNumberTable(new byte[] { 159, 111, 98, 99, 114, 52, 167, 101 }), Signature("<T:Ljava/lang/Object;>(Lcom/googlecode/lanterna/gui2/WindowBasedTextGUI;Ljava/lang/String;Ljava/lang/String;I[TT;)TT;")] //[MethodImpl(MethodImplOptions.NoInlining)] public static object showDialog(WindowBasedTextGUI textGUI, string title, string description, int listBoxHeight, params object[] items) { int width = 0; int num = items.Length; for (int i = 0; i < num; i++) { object item = items[i]; width = java.lang.Math.max(width, TerminalTextUtils.getColumnWidth(java.lang.Object.instancehelper_toString(item))); } width += 2; return ListSelectDialog.showDialog(textGUI, title, description, new TerminalSize(width, listBoxHeight), items); } //[HideFromJava] static ListSelectDialog() { DialogWindow.__<clinit>(); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; namespace Avalonia.Collections { /// <summary> /// A notifying dictionary. /// </summary> /// <typeparam name="TKey">The type of the dictionary key.</typeparam> /// <typeparam name="TValue">The type of the dictionary value.</typeparam> public class AvaloniaDictionary<TKey, TValue> : IDictionary<TKey, TValue>, INotifyCollectionChanged, INotifyPropertyChanged { private Dictionary<TKey, TValue> _inner; /// <summary> /// Initializes a new instance of the <see cref="AvaloniaDictionary{TKey, TValue}"/> class. /// </summary> public AvaloniaDictionary() { _inner = new Dictionary<TKey, TValue>(); } /// <summary> /// Occurs when the collection changes. /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged; /// <summary> /// Raised when a property on the collection changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <inheritdoc/> public int Count => _inner.Count; /// <inheritdoc/> public bool IsReadOnly => false; /// <inheritdoc/> public ICollection<TKey> Keys => _inner.Keys; /// <inheritdoc/> public ICollection<TValue> Values => _inner.Values; /// <summary> /// Gets or sets the named resource. /// </summary> /// <param name="key">The resource key.</param> /// <returns>The resource, or null if not found.</returns> public TValue this[TKey key] { get { return _inner[key]; } set { TValue old; bool replace = _inner.TryGetValue(key, out old); _inner[key] = value; if (replace) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs($"Item[{key}]")); if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, new KeyValuePair<TKey, TValue>(key, value), new KeyValuePair<TKey, TValue>(key, old)); CollectionChanged(this, e); } } else { NotifyAdd(key, value); } } } /// <inheritdoc/> public void Add(TKey key, TValue value) { _inner.Add(key, value); NotifyAdd(key, value); } /// <inheritdoc/> public void Clear() { var old = _inner; _inner = new Dictionary<TKey, TValue>(); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Count")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs($"Item[]")); if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, old.ToList(), -1); CollectionChanged(this, e); } } /// <inheritdoc/> public bool ContainsKey(TKey key) { return _inner.ContainsKey(key); } /// <inheritdoc/> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { ((IDictionary<TKey, TValue>)_inner).CopyTo(array, arrayIndex); } /// <inheritdoc/> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _inner.GetEnumerator(); } /// <inheritdoc/> public bool Remove(TKey key) { TValue value; if (_inner.TryGetValue(key, out value)) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Count")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs($"Item[{key}]")); if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, new[] { new KeyValuePair<TKey, TValue>(key, value) }, -1); CollectionChanged(this, e); } return true; } else { return false; } } /// <inheritdoc/> public bool TryGetValue(TKey key, out TValue value) { return _inner.TryGetValue(key, out value); } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { return _inner.GetEnumerator(); } /// <inheritdoc/> void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } /// <inheritdoc/> bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return _inner.Contains(item); } /// <inheritdoc/> bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { return Remove(item.Key); } private void NotifyAdd(TKey key, TValue value) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Count")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs($"Item[{key}]")); if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, new[] { new KeyValuePair<TKey, TValue>(key, value) }, -1); CollectionChanged(this, e); } } } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; //using System.Data; using System.Diagnostics; using SwinGameSDK; /// <summary> /// The DeploymentController controls the players actions /// during the deployment phase. /// </summary> static class DeploymentController { private const int SHIPS_TOP = 98; private const int SHIPS_LEFT = 20; private const int SHIPS_HEIGHT = 90; private const int SHIPS_WIDTH = 300; private const int TOP_BUTTONS_TOP = 72; private const int TOP_BUTTONS_HEIGHT = 46; private const int PLAY_BUTTON_LEFT = 693; private const int PLAY_BUTTON_WIDTH = 80; private const int UP_DOWN_BUTTON_LEFT = 410; private const int LEFT_RIGHT_BUTTON_LEFT = 350; private const int RANDOM_BUTTON_LEFT = 547; private const int RANDOM_BUTTON_WIDTH = 51; private const int DIR_BUTTONS_WIDTH = 47; private const int TEXT_OFFSET = 5; private static Direction _currentDirection = Direction.UpDown; private static ShipName _selectedShip = ShipName.Tug; /// <summary> /// Handles user input for the Deployment phase of the game. /// </summary> /// <remarks> /// Involves selecting the ships, deloying ships, changing the direction /// of the ships to add, randomising deployment, end then ending /// deployment /// </remarks> public static void HandleDeploymentInput() { if (SwinGame.KeyTyped(KeyCode.vk_ESCAPE)) { GameController.AddNewState(GameState.ViewingGameMenu); } if (SwinGame.KeyTyped(KeyCode.vk_UP)) { _currentDirection = Direction.UpDown; } if (SwinGame.KeyTyped(KeyCode.vk_LEFT) | SwinGame.KeyTyped(KeyCode.vk_RIGHT)) { _currentDirection = Direction.LeftRight; } if (SwinGame.KeyTyped(KeyCode.vk_r)) { GameController.HumanPlayer.RandomizeDeployment(); } if (SwinGame.MouseClicked(MouseButton.LeftButton)) { UtilityFunctions.Message = ""; ShipName selected = default(ShipName); selected = GetShipMouseIsOver(); if (selected != ShipName.None) { _selectedShip = selected; } else { Ship moving = GameController.HumanPlayer.PlayerGrid.GetShipNamed(_selectedShip); try { DoDeployClick(); } catch (Exception ex) { Audio.PlaySoundEffect(GameResources.GameSound("Error")); UtilityFunctions.Message = ex.Message; Direction currentDir = _currentDirection; _currentDirection = moving.Direction; DeployShip(moving.Row,moving.Column); _currentDirection = currentDir; } } if (GameController.HumanPlayer.ReadyToDeploy & UtilityFunctions.IsMouseInRectangle(PLAY_BUTTON_LEFT,TOP_BUTTONS_TOP,PLAY_BUTTON_WIDTH,TOP_BUTTONS_HEIGHT)) { GameController.EndDeployment(); } else if (UtilityFunctions.IsMouseInRectangle(UP_DOWN_BUTTON_LEFT,TOP_BUTTONS_TOP,DIR_BUTTONS_WIDTH,TOP_BUTTONS_HEIGHT)) { _currentDirection = Direction.UpDown; } else if (UtilityFunctions.IsMouseInRectangle(LEFT_RIGHT_BUTTON_LEFT,TOP_BUTTONS_TOP,DIR_BUTTONS_WIDTH,TOP_BUTTONS_HEIGHT)) { _currentDirection = Direction.LeftRight; } else if (UtilityFunctions.IsMouseInRectangle(RANDOM_BUTTON_LEFT,TOP_BUTTONS_TOP,RANDOM_BUTTON_WIDTH,TOP_BUTTONS_HEIGHT)) { GameController.HumanPlayer.RandomizeDeployment(); } } if (SwinGame.MouseClicked(MouseButton.RightButton)) { Tile clickedCell = GetClickedCell(true); bool valid = clickedCell.Ship != null; if (clickedCell.Ship != null) { RotateClickedShip(clickedCell); } } } private static void RotateClickedShip(Tile clickedCell) { int oldRow = clickedCell.Ship.Row; int oldCol = clickedCell.Ship.Column; Direction oldDirection = clickedCell.Ship.Direction; Direction oldCurrentDir = _currentDirection; bool horizontal = clickedCell.Ship.Direction == Direction.LeftRight; int cellPosition = horizontal ? clickedCell.Column : clickedCell.Row; int shipPosition = horizontal ? clickedCell.Ship.Column : clickedCell.Ship.Row; int relativePosition = cellPosition - shipPosition; _selectedShip = clickedCell.Ship.Type; _currentDirection = horizontal ? Direction.UpDown : Direction.LeftRight; // Ship at relative position (-3, 0) should go to relative position (0, -3) and invert the direction try { if (horizontal) { DeployShip(clickedCell.Row - relativePosition,clickedCell.Column,false,true); } else { DeployShip(clickedCell.Row,clickedCell.Column - relativePosition,false,true); } } catch (Exception ex) { _currentDirection = oldDirection; DeployShip(oldRow,oldCol); _currentDirection = oldCurrentDir; Audio.PlaySoundEffect(GameResources.GameSound("Error")); UtilityFunctions.Message = ex.Message; } } private static Tile GetClickedCell(bool getShip) { Point2D mouse = default(Point2D); mouse = SwinGame.MousePosition(); //Calculate the row/col clicked int row = 0; int col = 0; row = Convert.ToInt32(Math.Floor((mouse.Y - UtilityFunctions.FIELD_TOP)/(UtilityFunctions.CELL_HEIGHT + UtilityFunctions.CELL_GAP))); col = Convert.ToInt32(Math.Floor((mouse.X - UtilityFunctions.FIELD_LEFT)/(UtilityFunctions.CELL_WIDTH + UtilityFunctions.CELL_GAP))); Tile res = new Tile(row,col,null); if (getShip) { res.Ship = GameController.HumanPlayer.PlayerGrid.GetShipAtTile(res); } return res; } private static Tile GetClickedCell() { return GetClickedCell(false); } /// <summary> /// The user has clicked somewhere on the screen, check if its is a deployment and deploy /// the current ship if that is the case. /// </summary> /// <remarks> /// If the click is in the grid it deploys to the selected location /// with the indicated direction /// </remarks> private static void DoDeployClick() { Tile clickedCell = GetClickedCell(); DeployShip(clickedCell.Row, clickedCell.Column, false, false); } private static void DeployShip(int row,int col,bool supressExceptions,bool throwIfOutOfRange) { bool inRange = row >= 0 && row < GameController.HumanPlayer.PlayerGrid.Height; if (inRange) { inRange = col >= 0 && col < GameController.HumanPlayer.PlayerGrid.Width; if (inRange) { //if in the area try to deploy try { GameController.HumanPlayer.PlayerGrid.MoveShip(row,col,_selectedShip,_currentDirection); } catch (Exception ex) { if (supressExceptions) { Audio.PlaySoundEffect(GameResources.GameSound("Error")); UtilityFunctions.Message = ex.Message; } else { throw ex; } } } } if (throwIfOutOfRange && !inRange) { throw new ArgumentOutOfRangeException("Ship can't fit on the board"); } } private static void DeployShip(int row,int col) { DeployShip(row,col,true,false); } /// <summary> /// Draws the deployment screen showing the field and the ships /// that the player can deploy. /// </summary> public static void DrawDeployment() { UtilityFunctions.DrawField(GameController.HumanPlayer.PlayerGrid, GameController.HumanPlayer, true); //Draw the Left/Right and Up/Down buttons if (_currentDirection == Direction.LeftRight) { SwinGame.DrawBitmap(GameResources.GameImage("LeftRightButton"), LEFT_RIGHT_BUTTON_LEFT, TOP_BUTTONS_TOP); } else { SwinGame.DrawBitmap(GameResources.GameImage("UpDownButton"), LEFT_RIGHT_BUTTON_LEFT, TOP_BUTTONS_TOP); } //DrawShips foreach (ShipName sn in Enum.GetValues(typeof(ShipName))) { int i = 0; i = ((int)sn) - 1; if (i >= 0) { if (sn == _selectedShip) { SwinGame.DrawBitmap(GameResources.GameImage("SelectedShip"), SHIPS_LEFT, SHIPS_TOP + i * SHIPS_HEIGHT); } } } if (GameController.HumanPlayer.ReadyToDeploy) { SwinGame.DrawBitmap(GameResources.GameImage("PlayButton"), PLAY_BUTTON_LEFT, TOP_BUTTONS_TOP); } SwinGame.DrawBitmap(GameResources.GameImage("RandomButton"), RANDOM_BUTTON_LEFT, TOP_BUTTONS_TOP); UtilityFunctions.DrawMessage(); } /// <summary> /// Gets the ship that the mouse is currently over in the selection panel. /// </summary> /// <returns>The ship selected or none</returns> private static ShipName GetShipMouseIsOver() { foreach (ShipName sn in Enum.GetValues(typeof(ShipName))) { int i = 0; i =((int)sn) - 1; if (UtilityFunctions.IsMouseInRectangle(SHIPS_LEFT, SHIPS_TOP + i * SHIPS_HEIGHT, SHIPS_WIDTH, SHIPS_HEIGHT)) { return sn; } } return ShipName.None; } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
#if UNITY_EDITOR using System; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; using UMA.CharacterSystem; namespace UMA.Editors { public partial class RecipeEditor { //if we move to having different types for the different kinds of UMATextRecipe (UMAWardrobeRecipe, UMAWardrobeCollection etc) then we will stop displaying this UI element (and just use the value when saving txt recipes) public List<string> recipeTypeOpts = new List<string>(new string[] { "Standard", "Wardrobe" }); protected bool hideToolBar = false; protected bool hideRaceField = true;//if true hides the extra race field that we draw *above* the toolbar int compatibleRacePickerID = -1; int selectedWardrobeThumb = 0; List<string> generatedWardrobeSlotOptions = new List<string>(); List<string> generatedWardrobeSlotOptionsLabels = new List<string>(); protected List<string> generatedBaseSlotOptions = new List<string>(); protected List<string> generatedBaseSlotOptionsLabels = new List<string>(); FieldInfo ActiveWardrobeSetField = null; List<WardrobeSettings> activeWardrobeSet = null; protected override bool PreInspectorGUI() { return TextRecipeGUI(); } protected override bool ToolbarGUI() { //hide the toolbar when its a recipe type that doesn't use DNA (like wardrobe or wardrobeCollection) if (hideToolBar) { return slotEditor.OnGUI(target.name, ref _dnaDirty, ref _textureDirty, ref _meshDirty); } bool changed = false; //the raceData field should really be ABOVE the toolbar, since it defines what the dna will be GUILayout.Space(10); if (!hideRaceField) { RaceData newRace = (RaceData)EditorGUILayout.ObjectField("RaceData", _recipe.raceData, typeof(RaceData), false); if (_recipe.raceData != newRace) { _recipe.SetRace(newRace); changed = true; } } _toolbarIndex = GUILayout.Toolbar(_toolbarIndex, toolbar); _LastToolBar = _toolbarIndex; if (dnaEditor != null && slotEditor != null) switch (_toolbarIndex) { case 0: if (!dnaEditor.IsValid) return false; else if (dnaEditor.OnGUI(ref _dnaDirty, ref _textureDirty, ref _meshDirty)) return true; else return changed; case 1: if (slotEditor.OnGUI(target.name, ref _dnaDirty, ref _textureDirty, ref _meshDirty)) return true; else return changed; } return changed; } protected bool AreListsEqual<T>(List<T> x, List<T> y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.Count != y.Count) { return false; } for (int i = 0; i < x.Count; i++) { if (!x[i].Equals(y[i])) { return false; } } return true; } /// <summary> /// Adds a button for adding dna to a newly created UMATextRecipe /// </summary> /// <returns></returns> protected virtual bool AddDNAButtonUI() { RaceData standardRaceData = null; if (_recipe != null) { standardRaceData = _recipe.raceData; } if (standardRaceData == null) return false; //This enables us to create a new recipe using the Editor menu command but also add DNA to it based on the set race's converters var currentDNA = _recipe.GetAllDna(); //we also need current slots because GetAllDna returns a zero length array if _recipe.slotdatalist == null SlotData[] currentSlots = _recipe.GetAllSlots(); bool couldAddDNA = false; bool DNAConvertersAdded = false; if (currentDNA.Length == 0 && currentSlots != null) { var thisDNAConverterList = standardRaceData.dnaConverterList; foreach (DnaConverterBehaviour DnaConverter in thisDNAConverterList) { if (DnaConverter != null) { if(DnaConverter.DNATypeHash != 0) couldAddDNA = true; } } if (couldAddDNA) { if (GUILayout.Button("Add DNA")) { foreach (DnaConverterBehaviour DnaConverter in thisDNAConverterList) { if (DnaConverter != null) { DNAConvertersAdded = true; //the recipe already has the DNAConverter, it just doesn't have the values it requires to show the output in the DNA tab of the recipe //_recipe.AddDNAUpdater(DnaConverter); Type thisType = DnaConverter.DNAType; if (DnaConverter is DynamicDNAConverterBehaviourBase) { var dna = _recipe.GetOrCreateDna(thisType, DnaConverter.DNATypeHash); if (((DynamicDNAConverterBehaviourBase)DnaConverter).dnaAsset != null) { ((DynamicUMADnaBase)dna).dnaAsset = ((DynamicDNAConverterBehaviourBase)DnaConverter).dnaAsset; } } else { _recipe.GetOrCreateDna(thisType, DnaConverter.DNATypeHash); } } } } } } return DNAConvertersAdded; } protected virtual bool FixDNAConverters() { RaceData standardRaceData = null; if (_recipe != null) { standardRaceData = _recipe.raceData; } if (standardRaceData == null) return false; var currentDNA = _recipe.GetAllDna(); //we also need current slots because GetAllDna returns a zero length array if _recipe.slotdatalist == null SlotData[] currentSlots = _recipe.GetAllSlots(); bool DNAConvertersModified = false; if (currentDNA.Length > 0 && currentSlots != null) { //check if any DynamicDNA needs its DynamicDNAAsset updating var thisDNAConverterList = standardRaceData.dnaConverterList; for(int i = 0; i < thisDNAConverterList.Length; i++) /*DnaConverterBehaviour DnaConverter in thisDNAConverterList)*/ { if(thisDNAConverterList[i] == null) { Debug.LogWarning(standardRaceData.raceName + " RaceData has a missing DNA Converter"); continue; } //'Old' UMA DNA will have a typehash based on its type name (never 0) //DynamicDNA will only be zero if the converter does not have a DNA asset assigned (and will show a warning) //so if the typeHash is 0 bail if (thisDNAConverterList[i].DNATypeHash == 0) { Debug.LogWarning("Dynamic DNA Converter "+ thisDNAConverterList[i].name+" needs a DNA Asset assigned to it"); continue; } var dna = _recipe.GetOrCreateDna(thisDNAConverterList[i].DNAType, thisDNAConverterList[i].DNATypeHash); if (thisDNAConverterList[i] is DynamicDNAConverterBehaviourBase) { var thisDnaAsset = ((DynamicDNAConverterBehaviourBase)thisDNAConverterList[i]).dnaAsset; if (((DynamicUMADnaBase)dna).dnaAsset != thisDnaAsset || ((DynamicUMADnaBase)dna).didDnaAssetUpdate) { if (((DynamicUMADnaBase)dna).didDnaAssetUpdate) { Debug.Log("DynamicDNA found a missing asset"); ((DynamicUMADnaBase)dna).didDnaAssetUpdate = false; DNAConvertersModified = true; } else { //When this happens the values get lost ((DynamicUMADnaBase)dna).dnaAsset = thisDnaAsset; //so we need to try to add any existing dna values to this dna int imported = 0; for (int j = 0; j < currentDNA.Length; j++) { if (currentDNA[j].DNATypeHash != dna.DNATypeHash) { imported += ((DynamicUMADnaBase)dna).ImportUMADnaValues(currentDNA[j]); } } Debug.Log("Updated DNA to match DnaConverter " + thisDNAConverterList[i].name + "'s dna asset and imported "+imported+" values from previous dna"); DNAConvertersModified = true; } } } } for (int i = 0; i < currentDNA.Length; i++) { if (_recipe.raceData.GetConverter(currentDNA[i]) == null) { int dnaToImport = currentDNA[i].Count; int dnaImported = 0; for (int j = 0; j < currentDNA.Length; j++) { if (currentDNA[j] is DynamicUMADnaBase) { // Keep trying to find a new home for DNA values until they have all been set dnaImported += ((DynamicUMADnaBase)currentDNA[j]).ImportUMADnaValues(currentDNA[i]); if (dnaImported >= dnaToImport) break; } } if (dnaImported > 0) { if(_recipe.GetDna(currentDNA[i].DNATypeHash) != null) _recipe.RemoveDna(currentDNA[i].DNATypeHash); DNAConvertersModified = true; } } } currentDNA = _recipe.GetAllDna(); //Finally if there are more DNA sets than there are converters we need to remove the dna that should not be there if (currentDNA.Length > thisDNAConverterList.Length) { Debug.Log("There were more dna sets in the recipe than converters. Removing unused Dna..."); List<UMADnaBase> newCurrentDna = new List<UMADnaBase>(); for (int i = 0; i < currentDNA.Length; i++) { bool foundMatch = false; for (int ii = 0; ii < thisDNAConverterList.Length; ii++) { if (thisDNAConverterList[ii].DNATypeHash == currentDNA[i].DNATypeHash) { newCurrentDna.Add(currentDNA[i]); foundMatch = true; } } if (!foundMatch) { if (_recipe.dnaValues.Contains(currentDNA[i])) _recipe.RemoveDna(currentDNA[i].DNATypeHash); } } currentDNA = newCurrentDna.ToArray(); DNAConvertersModified = true; } } return DNAConvertersModified; } private bool TextRecipeGUI() { Type TargetType = target.GetType();//used to get the UMATextRecipe type taher than UMARecipeBase bool doUpdate = false; if (TargetType.ToString() == "UMA.UMATextRecipe") { EditorGUI.BeginDisabledGroup(true); EditorGUILayout.Popup("Recipe Type", 0, new string[] { "Standard" });//other types (WardrobeRecipe, DynamicCharacterAvatarRecipe) have their own editors now so this is just for UI consistancy EditorGUI.EndDisabledGroup(); if (ActiveWardrobeSetField == null) ActiveWardrobeSetField = TargetType.GetField("activeWardrobeSet", BindingFlags.Public | BindingFlags.Instance); activeWardrobeSet = (List<WardrobeSettings>)ActiveWardrobeSetField.GetValue(target); //draws a button to 'Add DNA' when a new 'standard' recipe is created if (AddDNAButtonUI()) { hideToolBar = false; return true; } //fixes dna when the recipes race has updated from UMADnaHumanoid/Tutorial to DynamicDna if (FixDNAConverters()) { hideToolBar = false; return true; } //When recipes are saved from a DynamicCharacterAvatar as a 'Standard' rather than 'Optimized' recipe they are saved as 'BackwardsCompatible' //This means they have slots/overlay data AND a wardrobeSet. In this case we need to draw the "DynamicCharacterAvatarRecipe' slot editor //and this will show an editable Wardrobe set which will update and a slot/overlay list if ((activeWardrobeSet.Count > 0)) { hideRaceField = false; slotEditor = new WardrobeSetMasterEditor(_recipe, activeWardrobeSet); } } return doUpdate; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using Xunit; namespace System.ComponentModel.Tests { public class MyTypeDescriptorContext : ITypeDescriptorContext { public IContainer Container => null; public object Instance { get { return null; } } public PropertyDescriptor PropertyDescriptor { get { return null; } } public bool OnComponentChanging() { return true; } public void OnComponentChanged() { } public object GetService(Type serviceType) { return null; } } public struct SomeValueType { public int a; } public enum SomeEnum { Add, Sub, Mul } [Flags] public enum SomeFlagsEnum { Option1 = 1, Option2 = 2, Option3 = 4 } public class FormattableClass : IFormattable { public string ToString(string format, IFormatProvider formatProvider) { return FormattableClass.Token; } public const string Token = "Formatted class."; } public class Collection1 : ICollection { public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get { throw new NotImplementedException(); } } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } public class MyTypeListConverter : TypeListConverter { public MyTypeListConverter(Type[] types) : base(types) { } } #if FUNCTIONAL_TESTS [TypeConverter("System.ComponentModel.Tests.BaseClassConverter, System.ComponentModel.TypeConverter.Tests, Version=9.9.9.9, Culture=neutral, PublicKeyToken=9d77cc7ad39b68eb")] #elif PERFORMANCE_TESTS [TypeConverter("System.ComponentModel.Tests.BaseClassConverter, System.ComponentModel.TypeConverter.Performance.Tests, Version=9.9.9.9, Culture=neutral, PublicKeyToken=9d77cc7ad39b68eb")] #else #error Define FUNCTIONAL_TESTS or PERFORMANCE_TESTS #endif public class BaseClass { public BaseClass() { BaseProperty = 1; } public override bool Equals(object other) { BaseClass otherBaseClass = other as BaseClass; if (otherBaseClass == null) { return false; } if (otherBaseClass.BaseProperty == BaseProperty) { return true; } return base.Equals(other); } public override int GetHashCode() { return base.GetHashCode(); } public int BaseProperty; } public class BaseClassConverter : TypeConverter { public BaseClassConverter(string someString) { throw new InvalidOperationException("This constructor should not be invoked by TypeDescriptor.GetConverter."); } public BaseClassConverter() { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(int)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(int)) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is int) { BaseClass baseClass = new BaseClass(); baseClass.BaseProperty = (int)value; return baseClass; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(int)) { BaseClass baseClass = value as BaseClass; if (baseClass != null) { return baseClass.BaseProperty; } } return base.ConvertTo(context, culture, value, destinationType); } } [TypeConverter("System.ComponentModel.Tests.DerivedClassConverter")] internal class DerivedClass : BaseClass { public DerivedClass() : base() { DerivedProperty = 2; } public DerivedClass(int i) : base() { DerivedProperty = i; } public override bool Equals(object other) { DerivedClass otherDerivedClass = other as DerivedClass; if (otherDerivedClass == null) { return false; } if (otherDerivedClass.DerivedProperty != DerivedProperty) { return false; } return base.Equals(other); } public override int GetHashCode() { return base.GetHashCode(); } public int DerivedProperty; } internal class DerivedClassConverter : TypeConverter { public DerivedClassConverter() { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(int)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(int)) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is int) { DerivedClass derived = new DerivedClass(); derived.BaseProperty = (int)value; derived.DerivedProperty = (int)value; return derived; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(int)) { DerivedClass derived = value as DerivedClass; if (derived != null) { return derived.BaseProperty + derived.DerivedProperty; } } return base.ConvertTo(context, culture, value, destinationType); } } [TypeConverter(typeof(IBaseConverter))] public interface IBase { int InterfaceProperty { get; set; } } public interface IDerived : IBase { int DerivedInterfaceProperty { get; set; } } public class ClassIBase : IBase { public ClassIBase() { InterfaceProperty = 10; } public int InterfaceProperty { get; set; } } public class ClassIDerived : IDerived { public ClassIDerived() { InterfaceProperty = 20; DerivedInterfaceProperty = InterfaceProperty / 2; } public int InterfaceProperty { get; set; } public int DerivedInterfaceProperty { get; set; } } public class IBaseConverter : TypeConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string) || destinationType == typeof(int)) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { IBase baseInterface = (IBase)value; return "InterfaceProperty = " + baseInterface.InterfaceProperty.ToString(); } if (destinationType == typeof(int)) { IBase baseInterface = (IBase)value; return baseInterface.InterfaceProperty; } return base.ConvertTo(context, culture, value, destinationType); } } [TypeConverter("System.ComponentModel.Tests.InvalidConverter")] internal class ClassWithInvalidConverter : BaseClass { } public class InvalidConverter : TypeConverter { public InvalidConverter(string someString) { throw new InvalidOperationException("This constructor should not be invoked by TypeDescriptor.GetConverter."); } // Default constructor is missing, we expect the following exception when getting a converter: // System.MissingMethodException: No parameterless constructor defined for this object. } // TypeDescriptor should default to the TypeConverter in this case. public class ClassWithNoConverter { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Metadata; using System.Runtime.InteropServices; namespace Internal.TypeSystem.Ecma { public static class MetadataExtensions { public static CustomAttributeValue<TypeDesc>? GetDecodedCustomAttribute(this EcmaType This, string attributeNamespace, string attributeName) { var metadataReader = This.MetadataReader; var attributeHandle = metadataReader.GetCustomAttributeHandle(metadataReader.GetTypeDefinition(This.Handle).GetCustomAttributes(), attributeNamespace, attributeName); if (attributeHandle.IsNil) return null; return metadataReader.GetCustomAttribute(attributeHandle).DecodeValue(new CustomAttributeTypeProvider(This.EcmaModule)); } public static CustomAttributeValue<TypeDesc>? GetDecodedCustomAttribute(this EcmaMethod This, string attributeNamespace, string attributeName) { var metadataReader = This.MetadataReader; var attributeHandle = metadataReader.GetCustomAttributeHandle(metadataReader.GetMethodDefinition(This.Handle).GetCustomAttributes(), attributeNamespace, attributeName); if (attributeHandle.IsNil) return null; return metadataReader.GetCustomAttribute(attributeHandle).DecodeValue(new CustomAttributeTypeProvider(This.Module)); } public static IEnumerable<CustomAttributeValue<TypeDesc>> GetDecodedCustomAttributes(this EcmaMethod This, string attributeNamespace, string attributeName) { var metadataReader = This.MetadataReader; var attributeHandles = metadataReader.GetMethodDefinition(This.Handle).GetCustomAttributes(); foreach (var attributeHandle in attributeHandles) { StringHandle namespaceHandle, nameHandle; if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceHandle, out nameHandle)) continue; if (metadataReader.StringComparer.Equals(namespaceHandle, attributeNamespace) && metadataReader.StringComparer.Equals(nameHandle, attributeName)) { yield return metadataReader.GetCustomAttribute(attributeHandle).DecodeValue(new CustomAttributeTypeProvider(This.Module)); } } } public static CustomAttributeValue<TypeDesc>? GetDecodedCustomAttribute(this EcmaField This, string attributeNamespace, string attributeName) { var metadataReader = This.MetadataReader; var attributeHandle = metadataReader.GetCustomAttributeHandle(metadataReader.GetFieldDefinition(This.Handle).GetCustomAttributes(), attributeNamespace, attributeName); if (attributeHandle.IsNil) return null; return metadataReader.GetCustomAttribute(attributeHandle).DecodeValue(new CustomAttributeTypeProvider(This.Module)); } public static IEnumerable<CustomAttributeValue<TypeDesc>> GetDecodedCustomAttributes(this EcmaField This, string attributeNamespace, string attributeName) { var metadataReader = This.MetadataReader; var attributeHandles = metadataReader.GetFieldDefinition(This.Handle).GetCustomAttributes(); foreach (var attributeHandle in attributeHandles) { StringHandle namespaceHandle, nameHandle; if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceHandle, out nameHandle)) continue; if (metadataReader.StringComparer.Equals(namespaceHandle, attributeNamespace) && metadataReader.StringComparer.Equals(nameHandle, attributeName)) { yield return metadataReader.GetCustomAttribute(attributeHandle).DecodeValue(new CustomAttributeTypeProvider(This.Module)); } } } public static CustomAttributeHandle GetCustomAttributeHandle(this MetadataReader metadataReader, CustomAttributeHandleCollection customAttributes, string attributeNamespace, string attributeName) { foreach (var attributeHandle in customAttributes) { StringHandle namespaceHandle, nameHandle; if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceHandle, out nameHandle)) continue; if (metadataReader.StringComparer.Equals(namespaceHandle, attributeNamespace) && metadataReader.StringComparer.Equals(nameHandle, attributeName)) { return attributeHandle; } } return default(CustomAttributeHandle); } public static bool GetAttributeNamespaceAndName(this MetadataReader metadataReader, CustomAttributeHandle attributeHandle, out StringHandle namespaceHandle, out StringHandle nameHandle) { EntityHandle attributeType, attributeCtor; if (!GetAttributeTypeAndConstructor(metadataReader, attributeHandle, out attributeType, out attributeCtor)) { namespaceHandle = default(StringHandle); nameHandle = default(StringHandle); return false; } return GetAttributeTypeNamespaceAndName(metadataReader, attributeType, out namespaceHandle, out nameHandle); } public static bool GetAttributeTypeAndConstructor(this MetadataReader metadataReader, CustomAttributeHandle attributeHandle, out EntityHandle attributeType, out EntityHandle attributeCtor) { attributeCtor = metadataReader.GetCustomAttribute(attributeHandle).Constructor; if (attributeCtor.Kind == HandleKind.MemberReference) { attributeType = metadataReader.GetMemberReference((MemberReferenceHandle)attributeCtor).Parent; return true; } else if (attributeCtor.Kind == HandleKind.MethodDefinition) { attributeType = metadataReader.GetMethodDefinition((MethodDefinitionHandle)attributeCtor).GetDeclaringType(); return true; } else { // invalid metadata attributeType = default(EntityHandle); return false; } } public static bool GetAttributeTypeNamespaceAndName(this MetadataReader metadataReader, EntityHandle attributeType, out StringHandle namespaceHandle, out StringHandle nameHandle) { namespaceHandle = default(StringHandle); nameHandle = default(StringHandle); if (attributeType.Kind == HandleKind.TypeReference) { TypeReference typeRefRow = metadataReader.GetTypeReference((TypeReferenceHandle)attributeType); HandleKind handleType = typeRefRow.ResolutionScope.Kind; // Nested type? if (handleType == HandleKind.TypeReference || handleType == HandleKind.TypeDefinition) return false; nameHandle = typeRefRow.Name; namespaceHandle = typeRefRow.Namespace; return true; } else if (attributeType.Kind == HandleKind.TypeDefinition) { var def = metadataReader.GetTypeDefinition((TypeDefinitionHandle)attributeType); // Nested type? if (IsNested(def.Attributes)) return false; nameHandle = def.Name; namespaceHandle = def.Namespace; return true; } else { // unsupported metadata return false; } } public static PInvokeFlags GetDelegatePInvokeFlags(this EcmaType type) { PInvokeFlags flags = new PInvokeFlags(); if (!type.IsDelegate) { return flags; } var customAttributeValue = type.GetDecodedCustomAttribute( "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute"); if (customAttributeValue == null) { return flags; } if (!customAttributeValue.HasValue) { return flags; } if (customAttributeValue.Value.FixedArguments.Length == 1) { CallingConvention callingConvention = (CallingConvention)customAttributeValue.Value.FixedArguments[0].Value; switch (callingConvention) { case CallingConvention.StdCall: flags.UnmanagedCallingConvention = MethodSignatureFlags.UnmanagedCallingConventionStdCall; break; case CallingConvention.Cdecl: flags.UnmanagedCallingConvention = MethodSignatureFlags.UnmanagedCallingConventionCdecl; break; case CallingConvention.ThisCall: flags.UnmanagedCallingConvention = MethodSignatureFlags.UnmanagedCallingConventionThisCall; break; case CallingConvention.Winapi: flags.UnmanagedCallingConvention = MethodSignatureFlags.UnmanagedCallingConventionStdCall; break; } } foreach (var namedArgument in customAttributeValue.Value.NamedArguments) { if (namedArgument.Name == "CharSet") { flags.CharSet = (CharSet)namedArgument.Value; } else if (namedArgument.Name == "BestFitMapping") { flags.BestFitMapping = (bool)namedArgument.Value; } else if (namedArgument.Name == "SetLastError") { flags.SetLastError = (bool)namedArgument.Value; } else if (namedArgument.Name == "ThrowOnUnmappableChar") { flags.ThrowOnUnmappableChar = (bool)namedArgument.Value; } } return flags; } // This mask is the fastest way to check if a type is nested from its flags, // but it should not be added to the BCL enum as its semantics can be misleading. // Consider, for example, that (NestedFamANDAssem & NestedMask) == NestedFamORAssem. // Only comparison of the masked value to 0 is meaningful, which is different from // the other masks in the enum. private const TypeAttributes NestedMask = (TypeAttributes)0x00000006; public static bool IsNested(this TypeAttributes flags) { return (flags & NestedMask) != 0; } public static bool IsRuntimeSpecialName(this MethodAttributes flags) { return (flags & (MethodAttributes.SpecialName | MethodAttributes.RTSpecialName)) == (MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); } public static bool IsPublic(this MethodAttributes flags) { return (flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; } } }
#pragma warning disable 0168 using nHydrate.Generator.Util; using System; using System.Linq; namespace nHydrate.Dsl { partial class nHydrateDiagram { ///Determine if this diagram is loading from disk public bool IsLoading { get; set; } = false; #region Constructors //Constructors were not generated for this class because it had HasCustomConstructor //set to true. Please provide the constructors below in a partial class. public nHydrateDiagram(Microsoft.VisualStudio.Modeling.Store store, params Microsoft.VisualStudio.Modeling.PropertyAssignment[] propertyAssignments) : this(store != null ? store.DefaultPartitionForClass(DomainClassId) : null, propertyAssignments) { } public nHydrateDiagram(Microsoft.VisualStudio.Modeling.Partition partition, params Microsoft.VisualStudio.Modeling.PropertyAssignment[] propertyAssignments) : base(partition, propertyAssignments) { this.Store.UndoManager.AddCanUndoRedoCallback(CanUndoRedoCallback); this.Store.TransactionManager.AddCanCommitCallback(CanCommitCallback); //Custom code so need to override the constructor this.ShowGrid = false; this.DisplayType = true; this.IsLoading = true; this.DiagramAdded += new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(nHydrateDiagram_DiagramAdded); TextManagerEvents.RegisterForTextManagerEvents(); } private bool CanUndoRedoCallback(bool isUndo, Microsoft.VisualStudio.Modeling.TransactionItem transactionItem) { return true; } public Microsoft.VisualStudio.Modeling.CanCommitResult CanCommitCallback(Microsoft.VisualStudio.Modeling.Transaction transaction) { return Microsoft.VisualStudio.Modeling.CanCommitResult.Commit; } #endregion #region Events protected override void OnElementAdded(Microsoft.VisualStudio.Modeling.ElementAddedEventArgs e) { var model = this.ModelElement as nHydrate.Dsl.nHydrateModel; if (!model.IsLoading) { } base.OnElementAdded(e); } public event EventHandler<ModelElementEventArgs> ShapeDoubleClick; protected void OnShapeDoubleClick(ModelElementEventArgs e) { if (this.ShapeDoubleClick != null) ShapeDoubleClick(this, e); } public event EventHandler<ModelElementEventArgs> ShapeConfiguring; protected void OnShapeConfiguring(ModelElementEventArgs e) { if (this.ShapeConfiguring != null) ShapeConfiguring(this, e); } #endregion #region Event Handlers private void FieldAdded(object sender, Microsoft.VisualStudio.Modeling.ElementAddedEventArgs e) { var field = e.ModelElement as Field; if (field.Entity == null) return; if (field.Entity.nHydrateModel == null) return; if (!field.Entity.nHydrateModel.IsLoading && field.SortOrder == 0) { var maxSortOrder = 1; if (field.Entity.Fields.Count > 0) maxSortOrder = field.Entity.Fields.Max(x => x.SortOrder); using (var transaction = this.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString())) { field.SortOrder = ++maxSortOrder; transaction.Commit(); } } } private void IndexColumnAdded(object sender, Microsoft.VisualStudio.Modeling.ElementAddedEventArgs e) { var ic = e.ModelElement as IndexColumn; if (ic.Index == null) return; if (ic.Index.Entity == null) return; if (ic.Index.Entity.nHydrateModel == null) return; if (!ic.IsInternal && !ic.Index.Entity.nHydrateModel.IsLoading && !this.Store.InUndo) { if (!ic.Index.Entity.nHydrateModel.IsLoading) { if (ic.Index.IndexType != IndexTypeConstants.User) throw new Exception("This is a managed index and cannot be modified."); } } if (!ic.Index.Entity.nHydrateModel.IsLoading) { if (ic.SortOrder == 0) { using (var transaction = this.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString())) { var max = 0; if (ic.Index.IndexColumns.Count > 0) max = ic.Index.IndexColumns.Max(x => x.SortOrder); ic.SortOrder = max + 1; transaction.Commit(); } } } } private void FieldPropertyChanged(object sender, Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs e) { var f = e.ModelElement as Field; f.CachedImage = null; } private void ViewFieldPropertyChanged(object sender, Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs e) { var f = e.ModelElement as ViewField; f.CachedImage = null; } private bool _isLoaded = false; protected void nHydrateDiagram_DiagramAdded(object sender, Microsoft.VisualStudio.Modeling.ElementAddedEventArgs e) { if (_isLoaded) return; _isLoaded = true; var model = this.Diagram.ModelElement as nHydrateModel; //Notify when field is changed so we can refresh icon this.Store.EventManagerDirectory.ElementPropertyChanged.Add( this.Store.DomainDataDirectory.FindDomainClass(typeof(Field)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(FieldPropertyChanged)); this.Store.EventManagerDirectory.ElementPropertyChanged.Add( this.Store.DomainDataDirectory.FindDomainClass(typeof(ViewField)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ViewFieldPropertyChanged)); //Notify when an index column is added this.Store.EventManagerDirectory.ElementAdded.Add( this.Store.DomainDataDirectory.FindDomainClass(typeof(IndexColumn)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(IndexColumnAdded)); //Notify when a Field is added this.Store.EventManagerDirectory.ElementAdded.Add( this.Store.DomainDataDirectory.FindDomainClass(typeof(Field)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(FieldAdded)); this.IsLoading = false; model.IsDirty = true; } #endregion protected override void OnChildConfiguring(Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement child, bool createdDuringViewFixup) { base.OnChildConfiguring(child, createdDuringViewFixup); try { if (!this.IsLoading) { //Add a default field to entities if (child.ModelElement is Entity) { var item = child.ModelElement as Entity; var model = item.nHydrateModel; if (item.Fields.Count == 0) { var field = new Field(item.Partition) { DataType = DataTypeConstants.Int, Identity = IdentityTypeConstants.Database, Name = "ID", }; item.Fields.Add(field); //Add then set PK so it will trigger index code field.IsPrimaryKey = true; } #region Pasting //If there are invalid indexes then try to remap them foreach (var index in item.Indexes.Where(x => x.FieldList.Any(z => z == null))) { foreach (var c in index.IndexColumns.Where(x => x.Field == null && x.FieldID != Guid.Empty)) { var f = model.Entities.SelectMany(x => x.Fields).FirstOrDefault(x => x.Id == c.FieldID); if (f != null) { var f2 = item.Fields.FirstOrDefault(x => x.Name == f.Name); if (f2 != null) c.FieldID = f2.Id; } } } //Add a PK index if not one if (!item.Indexes.Any(x => x.IndexType == IndexTypeConstants.PrimaryKey) && item.PrimaryKeyFields.Count > 0) { var index = new Index(item.Partition) { IndexType = IndexTypeConstants.PrimaryKey }; item.Indexes.Add(index); var loop = 0; foreach (var field in item.PrimaryKeyFields) { var newIndexColumn = new IndexColumn(item.Partition); index.IndexColumns.Add(newIndexColumn); newIndexColumn.FieldID = field.Id; newIndexColumn.SortOrder = loop; loop++; } } #endregion } else if (child.ModelElement is View) { var item = child.ModelElement as View; if (item.Fields.Count == 0) { var field = new ViewField(item.Partition) { DataType = DataTypeConstants.Int, Name = "Field1", }; item.Fields.Add(field); } } this.OnShapeConfiguring(new ModelElementEventArgs() { Shape = child }); } } catch (Exception ex) { throw; } } internal void NotifyShapeDoubleClick(Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement shape) { this.OnShapeDoubleClick(new ModelElementEventArgs() { Shape = shape }); } protected override void InitializeResources(Microsoft.VisualStudio.Modeling.Diagrams.StyleSet classStyleSet) { var dte = GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; nHydrate.Generator.Util.EnvDTEHelper.Instance.SetDTE(dte); } } }
// File generated automatically by ReswPlus. https://github.com/rudyhuyn/ReswPlus // The NuGet package PluralNet is necessary to support Pluralization. using System; using Windows.ApplicationModel.Resources; using Windows.UI.Xaml.Markup; using Windows.UI.Xaml.Data; namespace JustRemember.Strings { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Huyn.ReswPlus", "0.1.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Editor { private static ResourceLoader _resourceLoader; static Editor() { _resourceLoader = ResourceLoader.GetForViewIndependentUse("Editor"); } /// <summary> /// Looks up a localized string similar to: Setting /// </summary> public static string Editor_Setting_Header => _resourceLoader.GetString("Editor_Setting_Header"); /// <summary> /// Looks up a localized string similar to: Bold /// </summary> public static string Edit_bold => _resourceLoader.GetString("Edit_bold"); /// <summary> /// Looks up a localized string similar to: Show content when it less than specific value /// </summary> public static string Edit_Compare_Less => _resourceLoader.GetString("Edit_Compare_Less"); /// <summary> /// Looks up a localized string similar to: Show content when it more than specific /// </summary> public static string Edit_Compare_More => _resourceLoader.GetString("Edit_Compare_More"); /// <summary> /// Looks up a localized string similar to: Show content when it not equal the specific value /// </summary> public static string Edit_Compare_NotSame => _resourceLoader.GetString("Edit_Compare_NotSame"); /// <summary> /// Looks up a localized string similar to: Show content when it equal the specific value /// </summary> public static string Edit_Compare_Same => _resourceLoader.GetString("Edit_Compare_Same"); /// <summary> /// Looks up a localized string similar to: Copy /// </summary> public static string Edit_copy => _resourceLoader.GetString("Edit_copy"); /// <summary> /// Looks up a localized string similar to: Cut /// </summary> public static string Edit_cut => _resourceLoader.GetString("Edit_cut"); /// <summary> /// Looks up a localized string similar to: This operation will replace all your exist content. Do you really want to continue? /// </summary> public static string Edit_Dialog_content => _resourceLoader.GetString("Edit_Dialog_content"); /// <summary> /// Looks up a localized string similar to: Warning. /// </summary> public static string Edit_Dialog_header => _resourceLoader.GetString("Edit_Dialog_header"); /// <summary> /// Looks up a localized string similar to: Italic /// </summary> public static string Edit_italic => _resourceLoader.GetString("Edit_italic"); /// <summary> /// Looks up a localized string similar to: Load /// </summary> public static string Edit_load => _resourceLoader.GetString("Edit_load"); /// <summary> /// Looks up a localized string similar to: Name must be supplied /// </summary> public static string Edit_name_empty => _resourceLoader.GetString("Edit_name_empty"); /// <summary> /// Looks up a localized string similar to: Name has already been used /// </summary> public static string Edit_name_exist => _resourceLoader.GetString("Edit_name_exist"); /// <summary> /// Looks up a localized string similar to: Name can't contain: \ / : * ? " < > | /// </summary> public static string Edit_name_illegal => _resourceLoader.GetString("Edit_name_illegal"); /// <summary> /// Looks up a localized string similar to: New /// </summary> public static string Edit_new => _resourceLoader.GetString("Edit_new"); /// <summary> /// Looks up a localized string similar to: Paste /// </summary> public static string Edit_paste => _resourceLoader.GetString("Edit_paste"); /// <summary> /// Looks up a localized string similar to: Redo /// </summary> public static string Edit_redo => _resourceLoader.GetString("Edit_redo"); /// <summary> /// Looks up a localized string similar to: Save /// </summary> public static string Edit_save => _resourceLoader.GetString("Edit_save"); /// <summary> /// Looks up a localized string similar to: Save a copy /// </summary> public static string Edit_Save_copy => _resourceLoader.GetString("Edit_Save_copy"); /// <summary> /// Looks up a localized string similar to: Save outside /// </summary> public static string Edit_Save_outside => _resourceLoader.GetString("Edit_Save_outside"); /// <summary> /// Looks up a localized string similar to: Show warning /// </summary> public static string Edit_Show_warning => _resourceLoader.GetString("Edit_Show_warning"); /// <summary> /// Looks up a localized string similar to: Font size ( /// </summary> public static string Edit_size_a => _resourceLoader.GetString("Edit_size_a"); /// <summary> /// Looks up a localized string similar to: ) /// </summary> public static string Edit_size_b => _resourceLoader.GetString("Edit_size_b"); /// <summary> /// Looks up a localized string similar to: Undo /// </summary> public static string Edit_undo => _resourceLoader.GetString("Edit_undo"); /// <summary> /// Looks up a localized string similar to: Default /// </summary> public static string Key_default => _resourceLoader.GetString("Key_default"); /// <summary> /// Looks up a localized string similar to: Toggled /// </summary> public static string Key_default_toggle => _resourceLoader.GetString("Key_default_toggle"); /// <summary> /// Looks up a localized string similar to: Number key /// </summary> public static string Key_type_number => _resourceLoader.GetString("Key_type_number"); /// <summary> /// Looks up a localized string similar to: Other key /// </summary> public static string Key_type_other => _resourceLoader.GetString("Key_type_other"); /// <summary> /// Looks up a localized string similar to: Select key /// </summary> public static string Key_type_select => _resourceLoader.GetString("Key_type_select"); /// <summary> /// Looks up a localized string similar to: Text key /// </summary> public static string Key_type_text => _resourceLoader.GetString("Key_type_text"); /// <summary> /// Looks up a localized string similar to: Toggle key /// </summary> public static string Key_type_toggle => _resourceLoader.GetString("Key_type_toggle"); /// <summary> /// Looks up a localized string similar to: File /// </summary> public static string Menu_File => _resourceLoader.GetString("Menu_File"); /// <summary> /// Looks up a localized string similar to: Send to Question designer /// </summary> public static string ME_Send_To_QE => _resourceLoader.GetString("ME_Send_To_QE"); /// <summary> /// Looks up a localized string similar to: Word wrap /// </summary> public static string ME_Wordwrap => _resourceLoader.GetString("ME_Wordwrap"); /// <summary> /// Looks up a localized string similar to: Untitled /// </summary> public static string Note_Untitled => _resourceLoader.GetString("Note_Untitled"); /// <summary> /// Looks up a localized string similar to: Add question /// </summary> public static string QD_AddQuestion => _resourceLoader.GetString("QD_AddQuestion"); /// <summary> /// Looks up a localized string similar to: Answer position /// </summary> public static string QD_answer_pos => _resourceLoader.GetString("QD_answer_pos"); /// <summary> /// Looks up a localized string similar to: Behind question /// </summary> public static string QD_behind_question => _resourceLoader.GetString("QD_behind_question"); /// <summary> /// Looks up a localized string similar to: Bottom of memo /// </summary> public static string QD_bottom_memo => _resourceLoader.GetString("QD_bottom_memo"); /// <summary> /// Looks up a localized string similar to: Custom question header /// </summary> public static string QD_custom_header => _resourceLoader.GetString("QD_custom_header"); /// <summary> /// Looks up a localized string similar to: Example: /// </summary> public static string QD_example => _resourceLoader.GetString("QD_example"); /// <summary> /// Looks up a localized string similar to: Write a question /// </summary> public static string QD_Question_Holder => _resourceLoader.GetString("QD_Question_Holder"); /// <summary> /// Looks up a localized string similar to: Send to Memo editor /// </summary> public static string QD_send_away => _resourceLoader.GetString("QD_send_away"); /// <summary> /// Looks up a localized string similar to: Separate answer and number /// </summary> public static string QD_separator => _resourceLoader.GetString("QD_separator"); /// <summary> /// Looks up a localized string similar to: Separate with ")" /// </summary> public static string QD_separator_bracket => _resourceLoader.GetString("QD_separator_bracket"); /// <summary> /// Looks up a localized string similar to: Separate with "." /// </summary> public static string QD_separator_dot => _resourceLoader.GetString("QD_separator_dot"); /// <summary> /// Looks up a localized string similar to: Settings /// </summary> public static string QD_setting => _resourceLoader.GetString("QD_setting"); /// <summary> /// Looks up a localized string similar to: Space after separate symbol /// </summary> public static string QD_use_space => _resourceLoader.GetString("QD_use_space"); /// <summary> /// Looks up a localized string similar to: Answer header /// </summary> public static string QE_answer_header => _resourceLoader.GetString("QE_answer_header"); /// <summary> /// Looks up a localized string similar to: No question /// </summary> public static string qe_no_question => _resourceLoader.GetString("qe_no_question"); /// <summary> /// Looks up a localized string similar to: Question /// </summary> public static string QE_Question => _resourceLoader.GetString("QE_Question"); /// <summary> /// Looks up a localized string similar to: Questions /// </summary> public static string QE_Questions => _resourceLoader.GetString("QE_Questions"); /// <summary> /// Looks up a localized string similar to: Separator /// </summary> public static string qe_separator => _resourceLoader.GetString("qe_separator"); /// <summary> /// Looks up a localized string similar to: Space separate /// </summary> public static string qe_space_sep => _resourceLoader.GetString("qe_space_sep"); /// <summary> /// Looks up a localized string similar to: Close /// </summary> public static string QuestionDesign_Close => _resourceLoader.GetString("QuestionDesign_Close"); } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Huyn.ReswPlus", "0.1.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [MarkupExtensionReturnType(ReturnType = typeof(string))] public class EditorExtension: MarkupExtension { public enum KeyEnum { __Undefined = 0, Editor_Setting_Header, Edit_bold, Edit_Compare_Less, Edit_Compare_More, Edit_Compare_NotSame, Edit_Compare_Same, Edit_copy, Edit_cut, Edit_Dialog_content, Edit_Dialog_header, Edit_italic, Edit_load, Edit_name_empty, Edit_name_exist, Edit_name_illegal, Edit_new, Edit_paste, Edit_redo, Edit_save, Edit_Save_copy, Edit_Save_outside, Edit_Show_warning, Edit_size_a, Edit_size_b, Edit_undo, Key_default, Key_default_toggle, Key_type_number, Key_type_other, Key_type_select, Key_type_text, Key_type_toggle, Menu_File, ME_Send_To_QE, ME_Wordwrap, Note_Untitled, QD_AddQuestion, QD_answer_pos, QD_behind_question, QD_bottom_memo, QD_custom_header, QD_example, QD_Question_Holder, QD_send_away, QD_separator, QD_separator_bracket, QD_separator_dot, QD_setting, QD_use_space, QE_answer_header, qe_no_question, QE_Question, QE_Questions, qe_separator, qe_space_sep, QuestionDesign_Close, } private static ResourceLoader _resourceLoader; static EditorExtension() { _resourceLoader = ResourceLoader.GetForViewIndependentUse("Editor"); } public KeyEnum Key { get; set;} public IValueConverter Converter { get; set;} public object ConverterParameter { get; set;} protected override object ProvideValue() { string res; if(Key == KeyEnum.__Undefined) { res = ""; } else { res = _resourceLoader.GetString(Key.ToString()); } return Converter == null ? res : Converter.Convert(res, typeof(String), ConverterParameter, null); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; using log4net; using Nini.Config; using OpenMetaverse; namespace OpenSim.Framework.Communications.Cache { /// <summary> /// Basically a hack to give us a Inventory library while we don't have a inventory server /// once the server is fully implemented then should read the data from that /// </summary> public class LibraryRootFolder : InventoryFolderImpl { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private UUID libOwner = new UUID("11111111-1111-0000-0000-000100bba000"); /// <summary> /// Holds the root library folder and all its descendents. This is really only used during inventory /// setup so that we don't have to repeatedly search the tree of library folders. /// </summary> protected Dictionary<UUID, InventoryFolderImpl> libraryFolders = new Dictionary<UUID, InventoryFolderImpl>(); public LibraryRootFolder(string pLibrariesLocation) { Owner = libOwner; ID = new UUID("00000112-000f-0000-0000-000100bba000"); Name = "OpenSim Library"; ParentID = UUID.Zero; Type = (short) 8; Version = (ushort) 1; libraryFolders.Add(ID, this); LoadLibraries(pLibrariesLocation); } public InventoryItemBase CreateItem(UUID inventoryID, UUID assetID, string name, string description, int assetType, int invType, UUID parentFolderID) { InventoryItemBase item = new InventoryItemBase(); item.Owner = libOwner; item.CreatorId = libOwner.ToString(); item.ID = inventoryID; item.AssetID = assetID; item.Description = description; item.Name = name; item.AssetType = assetType; item.InvType = invType; item.Folder = parentFolderID; item.BasePermissions = 0x7FFFFFFF; item.EveryOnePermissions = 0x7FFFFFFF; item.CurrentPermissions = 0x7FFFFFFF; item.NextPermissions = 0x7FFFFFFF; return item; } /// <summary> /// Use the asset set information at path to load assets /// </summary> /// <param name="path"></param> /// <param name="assets"></param> protected void LoadLibraries(string librariesControlPath) { m_log.InfoFormat("[LIBRARY INVENTORY]: Loading library control file {0}", librariesControlPath); LoadFromFile(librariesControlPath, "Libraries control", ReadLibraryFromConfig); } /// <summary> /// Read a library set from config /// </summary> /// <param name="config"></param> protected void ReadLibraryFromConfig(IConfig config, string path) { string basePath = Path.GetDirectoryName(path); string foldersPath = Path.Combine( basePath, config.GetString("foldersFile", String.Empty)); LoadFromFile(foldersPath, "Library folders", ReadFolderFromConfig); string itemsPath = Path.Combine( basePath, config.GetString("itemsFile", String.Empty)); LoadFromFile(itemsPath, "Library items", ReadItemFromConfig); } /// <summary> /// Read a library inventory folder from a loaded configuration /// </summary> /// <param name="source"></param> private void ReadFolderFromConfig(IConfig config, string path) { InventoryFolderImpl folderInfo = new InventoryFolderImpl(); folderInfo.ID = new UUID(config.GetString("folderID", ID.ToString())); folderInfo.Name = config.GetString("name", "unknown"); folderInfo.ParentID = new UUID(config.GetString("parentFolderID", ID.ToString())); folderInfo.Type = (short)config.GetInt("type", 8); folderInfo.Owner = libOwner; folderInfo.Version = 1; if (libraryFolders.ContainsKey(folderInfo.ParentID)) { InventoryFolderImpl parentFolder = libraryFolders[folderInfo.ParentID]; libraryFolders.Add(folderInfo.ID, folderInfo); parentFolder.AddChildFolder(folderInfo); // m_log.InfoFormat("[LIBRARY INVENTORY]: Adding folder {0} ({1})", folderInfo.name, folderInfo.folderID); } else { m_log.WarnFormat( "[LIBRARY INVENTORY]: Couldn't add folder {0} ({1}) since parent folder with ID {2} does not exist!", folderInfo.Name, folderInfo.ID, folderInfo.ParentID); } } /// <summary> /// Read a library inventory item metadata from a loaded configuration /// </summary> /// <param name="source"></param> private void ReadItemFromConfig(IConfig config, string path) { InventoryItemBase item = new InventoryItemBase(); item.Owner = libOwner; item.CreatorId = libOwner.ToString(); item.ID = new UUID(config.GetString("inventoryID", ID.ToString())); item.AssetID = new UUID(config.GetString("assetID", item.ID.ToString())); item.Folder = new UUID(config.GetString("folderID", ID.ToString())); item.Name = config.GetString("name", String.Empty); item.Description = config.GetString("description", item.Name); item.InvType = config.GetInt("inventoryType", 0); item.AssetType = config.GetInt("assetType", item.InvType); item.CurrentPermissions = (uint)config.GetLong("currentPermissions", 0x7FFFFFFF); item.NextPermissions = (uint)config.GetLong("nextPermissions", 0x7FFFFFFF); item.EveryOnePermissions = (uint)config.GetLong("everyonePermissions", 0x7FFFFFFF); item.BasePermissions = (uint)config.GetLong("basePermissions", 0x7FFFFFFF); if (libraryFolders.ContainsKey(item.Folder)) { InventoryFolderImpl parentFolder = libraryFolders[item.Folder]; try { parentFolder.Items.Add(item.ID, item); } catch (Exception) { m_log.WarnFormat("[LIBRARY INVENTORY] Item {1} [{0}] not added, duplicate item", item.ID, item.Name); } } else { m_log.WarnFormat( "[LIBRARY INVENTORY]: Couldn't add item {0} ({1}) since parent folder with ID {2} does not exist!", item.Name, item.ID, item.Folder); } } private delegate void ConfigAction(IConfig config, string path); /// <summary> /// Load the given configuration at a path and perform an action on each Config contained within it /// </summary> /// <param name="path"></param> /// <param name="fileDescription"></param> /// <param name="action"></param> private static void LoadFromFile(string path, string fileDescription, ConfigAction action) { if (File.Exists(path)) { try { XmlConfigSource source = new XmlConfigSource(path); for (int i = 0; i < source.Configs.Count; i++) { action(source.Configs[i], path); } } catch (XmlException e) { m_log.ErrorFormat("[LIBRARY INVENTORY]: Error loading {0} : {1}", path, e); } } else { m_log.ErrorFormat("[LIBRARY INVENTORY]: {0} file {1} does not exist!", fileDescription, path); } } /// <summary> /// Looks like a simple getter, but is written like this for some consistency with the other Request /// methods in the superclass /// </summary> /// <returns></returns> public Dictionary<UUID, InventoryFolderImpl> RequestSelfAndDescendentFolders() { return libraryFolders; } } }
/* * Copyright 2002 Fluent Consulting, Inc. All rights reserved. * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ using System; using System.Data; using System.Data.SqlClient; using System.Globalization; using Inform.Common; namespace Inform.Sql { /// <summary> /// This is the base class for Data Access Commands. /// /// A SqlDataAccessCommand can be used for queries that do not return result sets. They may however still /// return data by registering an output parameter with CreateOutputParameter. The result can be read /// after calling ExecuteNonQuery. /// /// Example usage: /// <code> /// SqlDataAccessCommand updateCommand = dataStore.createDataAccessCommand("Employees_UpdateEmployeeSalary"); /// updateCommand.CreateInputParameter("@EmployeeID",SqlDbType.Int, 2); /// updateCommand.CreateInputParameter("@Salary",SqlDbType.Int, salary); /// updateCommand.ExecuteNonQuery(); /// </code> /// </summary> public class SqlDataAccessCommand : IDataAccessCommand { internal SqlCommand command; internal SqlDataStore dataStore; /// <summary> /// Creates the command. /// </summary> public SqlDataAccessCommand(SqlDataStore dataStore, string cmdText){ this.dataStore = dataStore; this.command = new SqlCommand(cmdText); } /// <summary> /// Creates the command as a specific command type. /// </summary> public SqlDataAccessCommand(SqlDataStore dataStore, string cmdText, System.Data.CommandType commandType){ this.dataStore = dataStore; this.command = new SqlCommand(cmdText); this.command.CommandType = commandType; } /// <summary> /// Gets or sets the transaction in which the Command object executes. /// </summary> public IDbTransaction Transaction { get { return this.command.Transaction; } set { this.command.Transaction = (SqlTransaction)value; } } /// <summary> /// Gets or sets the wait time before terminating the attempt to execute the command and generating an error. /// </summary> public int CommandTimeout { get { return this.command.CommandTimeout; } set { this.command.CommandTimeout = value; } } /// <summary> /// Gets the SqlParameterCollection. /// </summary> public SqlParameterCollection Parameters { get { return this.command.Parameters; } } /// <summary> /// Gets the IDataParameterCollection. /// </summary> IDataParameterCollection IDataParameterCommand.Parameters { get { return this.command.Parameters; } } /// <summary> /// Creates a new input parameter for the stored procedure. /// </summary> /// <param name="parameterName">The name of the input parameter.</param> /// <param name="sqlDbType">The sql data type.</param> /// <param name="paramValue">The value of the input paramter.</param> /// <returns>The new parameter.</returns> /// <example>CreateInputParameter(command, "@UserID",SqlDbType.Int, userID);</example> public IDbDataParameter CreateInputParameter(string parameterName, object parameterValue) { SqlParameter param = command.Parameters.Add(new SqlParameter(parameterName, parameterValue)); param.Value = parameterValue; return param; } /// <summary> /// Creates a new input parameter for the stored procedure. /// </summary> /// <param name="parameterName">The name of the input parameter.</param> /// <param name="sqlDbType">The sql data type.</param> /// <param name="paramValue">The value of the input paramter.</param> /// <returns>The new parameter.</returns> /// <example>CreateInputParameter(command, "@UserID",SqlDbType.Int, userID);</example> public IDbDataParameter CreateInputParameter(string parameterName, SqlDbType sqlDbType, object parameterValue) { SqlParameter param = command.Parameters.Add(parameterName,sqlDbType); param.Value = parameterValue; return param; } /// <summary> /// Creates a new input parameter for a stored procedure. /// </summary> /// <param name="parameterName">The name of the input parameter.</param> /// <param name="sqlDbType">The sql data type.</param> /// <param name="size">The size of the underlying column.</param> /// <param name="paramValue">The value of the input paramter.</param> /// <returns>The new parameter.</returns> /// <example>CreateInputParameter(command, "@UserName",SqlDbType.NVarChar,20,userName);</example> public IDbDataParameter CreateInputParameter(string parameterName, SqlDbType sqlDbType, int size, object parameterValue) { SqlParameter param = command.Parameters.Add(parameterName,sqlDbType, size); param.Value = parameterValue; return param; } /// <summary> /// Creates a new output parameter for a stored procedure. /// </summary> /// <param name="parameterName">The name of the output parameter.</param> /// <param name="sqlDbType">The sql data type.</param> /// <param name="paramValue">The value of the input paramter.</param> /// <returns>The new parameter.</returns> public IDbDataParameter CreateOutputParameter(string parameterName) { SqlParameter param = command.Parameters.Add(new SqlParameter(parameterName, DBNull.Value)); param.Direction = ParameterDirection.Output; return param; } /// <summary> /// Creates a new output parameter for a stored procedure. /// </summary> /// <param name="parameterName">The name of the output parameter.</param> /// <param name="sqlDbType">The sql data type.</param> /// <param name="paramValue">The value of the input paramter.</param> /// <returns>The new parameter.</returns> public IDbDataParameter CreateOutputParameter(string parameterName, SqlDbType sqlDbType) { SqlParameter param = command.Parameters.Add(parameterName, sqlDbType); param.Direction = ParameterDirection.Output; return param; } /// <summary> /// Creates a new output parameter for a stored procedure. /// </summary> /// <param name="parameterName">The name of the output parameter.</param> /// <param name="sqlDbType">The sql data type.</param> /// <param name="size">The size of the underlying column.</param> /// <param name="paramValue">The value of the input paramter.</param> /// <returns>The new parameter.</returns> public IDbDataParameter CreateOutputParameter(string parameterName, SqlDbType sqlDbType, int size) { SqlParameter param = command.Parameters.Add(parameterName, sqlDbType, size); param.Direction = ParameterDirection.Output; return param; } /// <summary> /// Executes a SqlCommand that returns no records. /// </summary> public void ExecuteNonQuery() { if(dataStore.InTransaction){ ExecuteNonQuery(CommandBehavior.Default); } else { ExecuteNonQuery(CommandBehavior.CloseConnection); } } /// <summary> /// Executes a SqlCommand that returns no records. /// </summary> public void ExecuteNonQuery(CommandBehavior cmdBehavior) { if(command.Connection == null){ if(dataStore.InTransaction){ command.Connection = (SqlConnection)dataStore.CurrentTransaction.Connection; command.Transaction = (SqlTransaction)dataStore.CurrentTransaction; } else { command.Connection = (SqlConnection)dataStore.Connection.CreateConnection(); } } if(command.Connection.State != ConnectionState.Open){ command.Connection.Open(); } command.ExecuteNonQuery(); if(cmdBehavior == CommandBehavior.CloseConnection){ command.Connection.Close(); command.Connection = null; } } /// <summary> /// Executes a SqlCommand and returns the first columen of the first row. /// </summary> public object ExecuteScalar() { if(dataStore.InTransaction){ return ExecuteScalar(CommandBehavior.Default); } else { return ExecuteScalar(CommandBehavior.CloseConnection); } } /// <summary> /// Executes a SqlCommand and returns the first columen of the first row. /// </summary> public object ExecuteScalar(CommandBehavior cmdBehavior) { if(command.Connection == null){ if(dataStore.InTransaction){ command.Connection = (SqlConnection)dataStore.CurrentTransaction.Connection; command.Transaction = (SqlTransaction)dataStore.CurrentTransaction; } else { command.Connection = (SqlConnection)dataStore.Connection.CreateConnection(); } } if(command.Connection.State != ConnectionState.Open){ command.Connection.Open(); } object obj = command.ExecuteScalar(); if(cmdBehavior == CommandBehavior.CloseConnection){ command.Connection.Close(); command.Connection = null; } return obj; } /// <summary> /// Gets the SqlDataReader that is the result of excuting a SqlCommand. The associated SqlConnection is closed /// when the SqlDataReader is close. /// </summary> public IDataReader ExecuteReader() { return ExecuteReader(CommandBehavior.CloseConnection); } /// <summary> /// Gets the SqlDataReader that is the result of excuting a SqlCommand. /// </summary> public IDataReader ExecuteReader(CommandBehavior commandBehavior) { command.Connection = (SqlConnection)dataStore.Connection.CreateConnection(); if(command.Connection.State != ConnectionState.Open){ command.Connection.Open(); } return command.ExecuteReader(commandBehavior); } /// <summary> /// Get a DataView as the result of executing a SqlCommand. /// </summary> /// <returns></returns> public DataView ExecuteDataView() { command.Connection = (SqlConnection)dataStore.Connection.CreateConnection(); //Get data into DataTable SqlDataAdapter dataAdapter = new SqlDataAdapter(command); //Create DataSet DataSet dataSet = new DataSet(); //Fill DataSet dataAdapter.Fill(dataSet); //Create View from first table DataTable table = dataSet.Tables[0]; table.Locale = CultureInfo.InvariantCulture; DataView view = table.DefaultView; return view; } #region Implementation of ICloneable public object Clone() { SqlDataAccessCommand cmd = (SqlDataAccessCommand)this.MemberwiseClone(); cmd.command = new SqlCommand(this.command.CommandText); cmd.CommandTimeout = this.CommandTimeout; return cmd; } #endregion } }
// --------------------------------------------------------------------------- // <copyright file="PropertySet.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the PropertySet class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using DefaultPropertySetDictionary = LazyMember<System.Collections.Generic.Dictionary<BasePropertySet, string>>; /// <summary> /// Represents a set of item or folder properties. Property sets are used to indicate what properties of an item or /// folder should be loaded when binding to an existing item or folder or when loading an item or folder's properties. /// </summary> public sealed class PropertySet : ISelfValidate, IEnumerable<PropertyDefinitionBase> { /// <summary> /// Returns a predefined property set that only includes the Id property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable instance")] public static readonly PropertySet IdOnly = PropertySet.CreateReadonlyPropertySet(BasePropertySet.IdOnly); /// <summary> /// Returns a predefined property set that includes the first class properties of an item or folder. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable instance")] public static readonly PropertySet FirstClassProperties = PropertySet.CreateReadonlyPropertySet(BasePropertySet.FirstClassProperties); /// <summary> /// Maps BasePropertySet values to EWS's BaseShape values. /// </summary> private static DefaultPropertySetDictionary defaultPropertySetMap = new DefaultPropertySetDictionary( delegate() { Dictionary<BasePropertySet, string> result = new Dictionary<BasePropertySet, string>(); result.Add(BasePropertySet.IdOnly, "IdOnly"); result.Add(BasePropertySet.FirstClassProperties, "AllProperties"); return result; }); /// <summary> /// The base property set this property set is based upon. /// </summary> private BasePropertySet basePropertySet; /// <summary> /// The list of additional properties included in this property set. /// </summary> private List<PropertyDefinitionBase> additionalProperties = new List<PropertyDefinitionBase>(); /// <summary> /// The requested body type for get and find operations. If null, the "best body" is returned. /// </summary> private BodyType? requestedBodyType; /// <summary> /// The requested unique body type for get and find operations. If null, the should return the same value as body type. /// </summary> private BodyType? requestedUniqueBodyType; /// <summary> /// The requested normalized body type for get and find operations. If null, the should return the same value as body type. /// </summary> private BodyType? requestedNormalizedBodyType; /// <summary> /// Value indicating whether or not the server should filter HTML content. /// </summary> private bool? filterHtml; /// <summary> /// Value indicating whether or not the server should convert HTML code page to UTF8. /// </summary> private bool? convertHtmlCodePageToUTF8; /// <summary> /// Value of the URL template to use for the src attribute of inline IMG elements. /// </summary> private string inlineImageUrlTemplate; /// <summary> /// Value indicating whether or not the server should block references to external images. /// </summary> private bool? blockExternalImages; /// <summary> /// Value indicating whether or not to add a blank target attribute to anchor links. /// </summary> private bool? addTargetToLinks; /// <summary> /// Value indicating whether or not this PropertySet can be modified. /// </summary> private bool isReadOnly; /// <summary> /// Value indicating the maximum body size to retrieve. /// </summary> private int? maximumBodySize; /// <summary> /// Initializes a new instance of PropertySet. /// </summary> /// <param name="basePropertySet">The base property set to base the property set upon.</param> /// <param name="additionalProperties">Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)</param> public PropertySet(BasePropertySet basePropertySet, params PropertyDefinitionBase[] additionalProperties) : this(basePropertySet, (IEnumerable<PropertyDefinitionBase>)additionalProperties) { } /// <summary> /// Initializes a new instance of PropertySet. /// </summary> /// <param name="basePropertySet">The base property set to base the property set upon.</param> /// <param name="additionalProperties">Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)</param> public PropertySet(BasePropertySet basePropertySet, IEnumerable<PropertyDefinitionBase> additionalProperties) { this.basePropertySet = basePropertySet; if (additionalProperties != null) { this.additionalProperties.AddRange(additionalProperties); } } /// <summary> /// Initializes a new instance of PropertySet based upon BasePropertySet.IdOnly. /// </summary> public PropertySet() : this(BasePropertySet.IdOnly, null) { } /// <summary> /// Initializes a new instance of PropertySet. /// </summary> /// <param name="basePropertySet">The base property set to base the property set upon.</param> public PropertySet(BasePropertySet basePropertySet) : this(basePropertySet, null) { } /// <summary> /// Initializes a new instance of PropertySet based upon BasePropertySet.IdOnly. /// </summary> /// <param name="additionalProperties">Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)</param> public PropertySet(params PropertyDefinitionBase[] additionalProperties) : this(BasePropertySet.IdOnly, additionalProperties) { } /// <summary> /// Initializes a new instance of PropertySet based upon BasePropertySet.IdOnly. /// </summary> /// <param name="additionalProperties">Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)</param> public PropertySet(IEnumerable<PropertyDefinitionBase> additionalProperties) : this(BasePropertySet.IdOnly, additionalProperties) { } /// <summary> /// Implements an implicit conversion between PropertySet and BasePropertySet. /// </summary> /// <param name="basePropertySet">The BasePropertySet value to convert from.</param> /// <returns>A PropertySet instance based on the specified base property set.</returns> public static implicit operator PropertySet(BasePropertySet basePropertySet) { return new PropertySet(basePropertySet); } /// <summary> /// Adds the specified property to the property set. /// </summary> /// <param name="property">The property to add.</param> public void Add(PropertyDefinitionBase property) { this.ThrowIfReadonly(); EwsUtilities.ValidateParam(property, "property"); if (!this.additionalProperties.Contains(property)) { this.additionalProperties.Add(property); } } /// <summary> /// Adds the specified properties to the property set. /// </summary> /// <param name="properties">The properties to add.</param> public void AddRange(IEnumerable<PropertyDefinitionBase> properties) { this.ThrowIfReadonly(); EwsUtilities.ValidateParamCollection(properties, "properties"); foreach (PropertyDefinitionBase property in properties) { this.Add(property); } } /// <summary> /// Remove all explicitly added properties from the property set. /// </summary> public void Clear() { this.ThrowIfReadonly(); this.additionalProperties.Clear(); } /// <summary> /// Creates a read-only PropertySet. /// </summary> /// <param name="basePropertySet">The base property set.</param> /// <returns>PropertySet</returns> private static PropertySet CreateReadonlyPropertySet(BasePropertySet basePropertySet) { PropertySet propertySet = new PropertySet(basePropertySet); propertySet.isReadOnly = true; return propertySet; } /// <summary> /// Gets the name of the shape. /// </summary> /// <param name="serviceObjectType">Type of the service object.</param> /// <returns>Shape name.</returns> private static string GetShapeName(ServiceObjectType serviceObjectType) { switch (serviceObjectType) { case ServiceObjectType.Item: return XmlElementNames.ItemShape; case ServiceObjectType.Folder: return XmlElementNames.FolderShape; case ServiceObjectType.Conversation: return XmlElementNames.ConversationShape; case ServiceObjectType.Persona: return XmlElementNames.PersonaShape; default: EwsUtilities.Assert( false, "PropertySet.GetShapeName", string.Format("An unexpected object type {0} for property shape. This code path should never be reached.", serviceObjectType)); return string.Empty; } } /// <summary> /// Throws if readonly property set. /// </summary> private void ThrowIfReadonly() { if (this.isReadOnly) { throw new System.NotSupportedException(Strings.PropertySetCannotBeModified); } } /// <summary> /// Determines whether the specified property has been explicitly added to this property set using the Add or AddRange methods. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if this property set contains the specified propert]; otherwise, <c>false</c>. /// </returns> public bool Contains(PropertyDefinitionBase property) { return this.additionalProperties.Contains(property); } /// <summary> /// Removes the specified property from the set. /// </summary> /// <param name="property">The property to remove.</param> /// <returns>true if the property was successfully removed, false otherwise.</returns> public bool Remove(PropertyDefinitionBase property) { this.ThrowIfReadonly(); return this.additionalProperties.Remove(property); } /// <summary> /// Gets or sets the base property set the property set is based upon. /// </summary> public BasePropertySet BasePropertySet { get { return this.basePropertySet; } set { this.ThrowIfReadonly(); this.basePropertySet = value; } } /// <summary> /// Gets or sets type of body that should be loaded on items. If RequestedBodyType is null, body is returned as HTML if available, plain text otherwise. /// </summary> public BodyType? RequestedBodyType { get { return this.requestedBodyType; } set { this.ThrowIfReadonly(); this.requestedBodyType = value; } } /// <summary> /// Gets or sets type of body that should be loaded on items. If null, the should return the same value as body type. /// </summary> public BodyType? RequestedUniqueBodyType { get { return this.requestedUniqueBodyType; } set { this.ThrowIfReadonly(); this.requestedUniqueBodyType = value; } } /// <summary> /// Gets or sets type of normalized body that should be loaded on items. If null, the should return the same value as body type. /// </summary> public BodyType? RequestedNormalizedBodyType { get { return this.requestedNormalizedBodyType; } set { this.ThrowIfReadonly(); this.requestedNormalizedBodyType = value; } } /// <summary> /// Gets the number of explicitly added properties in this set. /// </summary> public int Count { get { return this.additionalProperties.Count; } } /// <summary> /// Gets or sets value indicating whether or not to filter potentially unsafe HTML content from message bodies. /// </summary> public bool? FilterHtmlContent { get { return this.filterHtml; } set { this.ThrowIfReadonly(); this.filterHtml = value; } } /// <summary> /// Gets or sets value indicating whether or not to convert HTML code page to UTF8 encoding. /// </summary> public bool? ConvertHtmlCodePageToUTF8 { get { return this.convertHtmlCodePageToUTF8; } set { this.ThrowIfReadonly(); this.convertHtmlCodePageToUTF8 = value; } } /// <summary> /// Gets or sets a value of the URL template to use for the src attribute of inline IMG elements. /// </summary> public string InlineImageUrlTemplate { get { return this.inlineImageUrlTemplate; } set { this.ThrowIfReadonly(); this.inlineImageUrlTemplate = value; } } /// <summary> /// Gets or sets value indicating whether or not to convert inline images to data URLs. /// </summary> public bool? BlockExternalImages { get { return this.blockExternalImages; } set { this.ThrowIfReadonly(); this.blockExternalImages = value; } } /// <summary> /// Gets or sets value indicating whether or not to add blank target attribute to anchor links. /// </summary> public bool? AddBlankTargetToLinks { get { return this.addTargetToLinks; } set { this.ThrowIfReadonly(); this.addTargetToLinks = value; } } /// <summary> /// Gets or sets the maximum size of the body to be retrieved. /// </summary> /// <value> /// The maximum size of the body to be retrieved. /// </value> public int? MaximumBodySize { get { return this.maximumBodySize; } set { this.ThrowIfReadonly(); this.maximumBodySize = value; } } /// <summary> /// Gets the <see cref="Microsoft.Exchange.WebServices.Data.PropertyDefinitionBase"/> at the specified index. /// </summary> /// <param name="index">Index.</param> public PropertyDefinitionBase this[int index] { get { return this.additionalProperties[index]; } } /// <summary> /// Implements ISelfValidate.Validate. Validates this property set. /// </summary> void ISelfValidate.Validate() { this.InternalValidate(); } /// <summary> /// Maps BasePropertySet values to EWS's BaseShape values. /// </summary> internal static DefaultPropertySetDictionary DefaultPropertySetMap { get { return PropertySet.defaultPropertySetMap; } } /// <summary> /// Writes additonal properties to XML. /// </summary> /// <param name="writer">The writer to write to.</param> /// <param name="propertyDefinitions">The property definitions to write.</param> internal static void WriteAdditionalPropertiesToXml( EwsServiceXmlWriter writer, IEnumerable<PropertyDefinitionBase> propertyDefinitions) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.AdditionalProperties); foreach (PropertyDefinitionBase propertyDefinition in propertyDefinitions) { propertyDefinition.WriteToXml(writer); } writer.WriteEndElement(); } /// <summary> /// Writes the additional properties to json. /// </summary> /// <param name="jsonItemShape">The json attachment shape.</param> /// <param name="service">The service.</param> /// <param name="propertyDefinitions">The property definitions.</param> internal static void WriteAdditionalPropertiesToJson(JsonObject jsonItemShape, ExchangeService service, IEnumerable<PropertyDefinitionBase> propertyDefinitions) { List<object> additionalProperties = new List<object>(); foreach (PropertyDefinitionBase propertyDefinition in propertyDefinitions) { additionalProperties.Add(((IJsonSerializable)propertyDefinition).ToJson(service)); } jsonItemShape.Add(XmlElementNames.AdditionalProperties, additionalProperties.ToArray()); } /// <summary> /// Validates this property set. /// </summary> internal void InternalValidate() { for (int i = 0; i < this.additionalProperties.Count; i++) { if (this.additionalProperties[i] == null) { throw new ServiceValidationException(string.Format(Strings.AdditionalPropertyIsNull, i)); } } } /// <summary> /// Validates this property set instance for request to ensure that: /// 1. Properties are valid for the request server version. /// 2. If only summary properties are legal for this request (e.g. FindItem) then only summary properties were specified. /// </summary> /// <param name="request">The request.</param> /// <param name="summaryPropertiesOnly">if set to <c>true</c> then only summary properties are allowed.</param> internal void ValidateForRequest(ServiceRequestBase request, bool summaryPropertiesOnly) { foreach (PropertyDefinitionBase propDefBase in this.additionalProperties) { PropertyDefinition propertyDefinition = propDefBase as PropertyDefinition; if (propertyDefinition != null) { if (propertyDefinition.Version > request.Service.RequestedServerVersion) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, propertyDefinition.Name, propertyDefinition.Version)); } if (summaryPropertiesOnly && !propertyDefinition.HasFlag(PropertyDefinitionFlags.CanFind, request.Service.RequestedServerVersion)) { throw new ServiceValidationException( string.Format( Strings.NonSummaryPropertyCannotBeUsed, propertyDefinition.Name, request.GetXmlElementName())); } } } if (this.FilterHtmlContent.HasValue) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2010) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "FilterHtmlContent", ExchangeVersion.Exchange2010)); } } if (this.ConvertHtmlCodePageToUTF8.HasValue) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2010_SP1) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "ConvertHtmlCodePageToUTF8", ExchangeVersion.Exchange2010_SP1)); } } if (!string.IsNullOrEmpty(this.InlineImageUrlTemplate)) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "InlineImageUrlTemplate", ExchangeVersion.Exchange2013)); } } if (this.BlockExternalImages.HasValue) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "BlockExternalImages", ExchangeVersion.Exchange2013)); } } if (this.AddBlankTargetToLinks.HasValue) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "AddTargetToLinks", ExchangeVersion.Exchange2013)); } } if (this.MaximumBodySize.HasValue) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "MaximumBodySize", ExchangeVersion.Exchange2013)); } } } /// <summary> /// Writes the property set to XML. /// </summary> /// <param name="writer">The writer to write to.</param> /// <param name="serviceObjectType">The type of service object the property set is emitted for.</param> internal void WriteToXml(EwsServiceXmlWriter writer, ServiceObjectType serviceObjectType) { string shapeElementName = GetShapeName(serviceObjectType); writer.WriteStartElement( XmlNamespace.Messages, shapeElementName); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.BaseShape, defaultPropertySetMap.Member[this.BasePropertySet]); if (serviceObjectType == ServiceObjectType.Item) { if (this.RequestedBodyType.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.BodyType, this.RequestedBodyType.Value); } if (this.RequestedUniqueBodyType.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.UniqueBodyType, this.RequestedUniqueBodyType.Value); } if (this.RequestedNormalizedBodyType.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.NormalizedBodyType, this.RequestedNormalizedBodyType.Value); } if (this.FilterHtmlContent.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.FilterHtmlContent, this.FilterHtmlContent.Value); } if (this.ConvertHtmlCodePageToUTF8.HasValue && writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2010_SP1) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.ConvertHtmlCodePageToUTF8, this.ConvertHtmlCodePageToUTF8.Value); } if (!string.IsNullOrEmpty(this.InlineImageUrlTemplate) && writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.InlineImageUrlTemplate, this.InlineImageUrlTemplate); } if (this.BlockExternalImages.HasValue && writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.BlockExternalImages, this.BlockExternalImages.Value); } if (this.AddBlankTargetToLinks.HasValue && writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.AddBlankTargetToLinks, this.AddBlankTargetToLinks.Value); } if (this.MaximumBodySize.HasValue && writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.MaximumBodySize, this.MaximumBodySize.Value); } } if (this.additionalProperties.Count > 0) { WriteAdditionalPropertiesToXml(writer, this.additionalProperties); } writer.WriteEndElement(); // Item/FolderShape } /// <summary> /// Writes the get shape to json. /// </summary> /// <param name="jsonRequest">The json request.</param> /// <param name="service">The service.</param> /// <param name="serviceObjectType">Type of the service object.</param> internal void WriteGetShapeToJson(JsonObject jsonRequest, ExchangeService service, ServiceObjectType serviceObjectType) { string shapeName = GetShapeName(serviceObjectType); JsonObject jsonShape = new JsonObject(); jsonShape.Add(XmlElementNames.BaseShape, defaultPropertySetMap.Member[this.BasePropertySet]); if (serviceObjectType == ServiceObjectType.Item) { if (this.RequestedBodyType.HasValue) { jsonShape.Add(XmlElementNames.BodyType, this.RequestedBodyType.Value); } if (this.FilterHtmlContent.HasValue) { jsonShape.Add(XmlElementNames.FilterHtmlContent, this.FilterHtmlContent.Value); } if (this.ConvertHtmlCodePageToUTF8.HasValue && service.RequestedServerVersion >= ExchangeVersion.Exchange2010_SP1) { jsonShape.Add(XmlElementNames.ConvertHtmlCodePageToUTF8, this.ConvertHtmlCodePageToUTF8.Value); } if (!string.IsNullOrEmpty(this.InlineImageUrlTemplate) && service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { jsonShape.Add(XmlElementNames.InlineImageUrlTemplate, this.InlineImageUrlTemplate); } if (this.BlockExternalImages.HasValue && service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { jsonShape.Add(XmlElementNames.BlockExternalImages, this.BlockExternalImages.Value); } if (this.AddBlankTargetToLinks.HasValue && service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { jsonShape.Add(XmlElementNames.AddBlankTargetToLinks, this.AddBlankTargetToLinks.Value); } if (this.MaximumBodySize.HasValue && service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { jsonShape.Add(XmlElementNames.MaximumBodySize, this.MaximumBodySize.Value); } } if (this.additionalProperties.Count > 0) { WriteAdditionalPropertiesToJson(jsonShape, service, this.additionalProperties); } jsonRequest.Add(shapeName, jsonShape); } #region IEnumerable<PropertyDefinitionBase> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<PropertyDefinitionBase> GetEnumerator() { return this.additionalProperties.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.additionalProperties.GetEnumerator(); } #endregion } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Controls; using Xunit; namespace Avalonia.Input.UnitTests { public class KeyboardNavigationTests_Custom { [Fact] public void Tab_Should_Custom_Navigate_Within_Children() { Button current; Button next; var target = new CustomNavigatingStackPanel { Children = { (current = new Button { Content = "Button 1" }), new Button { Content = "Button 2" }, (next = new Button { Content = "Button 3" }), }, NextControl = next, }; var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next); Assert.Same(next, result); } [Fact] public void Right_Should_Custom_Navigate_Within_Children() { Button current; Button next; var target = new CustomNavigatingStackPanel { Children = { (current = new Button { Content = "Button 1" }), new Button { Content = "Button 2" }, (next = new Button { Content = "Button 3" }), }, NextControl = next, }; var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Right); Assert.Same(next, result); } [Fact] public void Tab_Should_Custom_Navigate_From_Outside() { Button current; Button next; var target = new CustomNavigatingStackPanel { Children = { new Button { Content = "Button 1" }, new Button { Content = "Button 2" }, (next = new Button { Content = "Button 3" }), }, NextControl = next, }; var root = new StackPanel { Children = { (current = new Button { Content = "Outside" }), target, } }; var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next); Assert.Same(next, result); } [Fact] public void Tab_Should_Custom_Navigate_From_Outside_When_Wrapping() { Button current; Button next; var target = new CustomNavigatingStackPanel { Children = { new Button { Content = "Button 1" }, new Button { Content = "Button 2" }, (next = new Button { Content = "Button 3" }), }, NextControl = next, }; var root = new StackPanel { Children = { target, (current = new Button { Content = "Outside" }), } }; var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next); Assert.Same(next, result); } [Fact] public void ShiftTab_Should_Custom_Navigate_From_Outside() { Button current; Button next; var target = new CustomNavigatingStackPanel { Children = { new Button { Content = "Button 1" }, new Button { Content = "Button 2" }, (next = new Button { Content = "Button 3" }), }, NextControl = next, }; var root = new StackPanel { Children = { (current = new Button { Content = "Outside" }), target, } }; var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous); Assert.Same(next, result); } [Fact] public void Right_Should_Custom_Navigate_From_Outside() { Button current; Button next; var target = new CustomNavigatingStackPanel { Children = { new Button { Content = "Button 1" }, new Button { Content = "Button 2" }, (next = new Button { Content = "Button 3" }), }, NextControl = next, }; var root = new StackPanel { Children = { (current = new Button { Content = "Outside" }), target, }, [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue, }; var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Right); Assert.Same(next, result); } [Fact] public void Tab_Should_Navigate_Outside_When_Null_Returned_As_Next() { Button current; Button next; var target = new CustomNavigatingStackPanel { Children = { new Button { Content = "Button 1" }, (current = new Button { Content = "Button 2" }), new Button { Content = "Button 3" }, }, }; var root = new StackPanel { Children = { target, (next = new Button { Content = "Outside" }), } }; var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next); Assert.Same(next, result); } private class CustomNavigatingStackPanel : StackPanel, ICustomKeyboardNavigation { public bool CustomNavigates { get; set; } = true; public IInputElement NextControl { get; set; } public (bool handled, IInputElement next) GetNext(IInputElement element, NavigationDirection direction) { return (CustomNavigates, NextControl); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NuGet.Packaging.Core; using NuGet.Versioning; using NuKeeper.Abstractions.CollaborationPlatform; using NuKeeper.Abstractions.Formats; using NuKeeper.Abstractions.RepositoryInspection; namespace NuKeeper.Engine { public class DefaultCommitWorder : ICommitWorder { private const string CommitEmoji = "package"; public string MakePullRequestTitle(IReadOnlyCollection<PackageUpdateSet> updates) { if (updates == null) { throw new ArgumentNullException(nameof(updates)); } if (updates.Count == 1) { return PackageTitle(updates.First()); } return $"Automatic update of {updates.Count} packages"; } private static string PackageTitle(PackageUpdateSet updates) { return $"Automatic update of {updates.SelectedId} to {updates.SelectedVersion}"; } public string MakeCommitMessage(PackageUpdateSet updates) { if (updates == null) { throw new ArgumentNullException(nameof(updates)); } return $":{CommitEmoji}: {PackageTitle(updates)}"; } public string MakeCommitDetails(IReadOnlyCollection<PackageUpdateSet> updates) { if (updates == null) { throw new ArgumentNullException(nameof(updates)); } var builder = new StringBuilder(); if (updates.Count > 1) { MultiPackagePrefix(updates, builder); } foreach (var update in updates) { builder.AppendLine(MakeCommitVersionDetails(update)); } if (updates.Count > 1) { MultiPackageFooter(builder); } AddCommitFooter(builder); return builder.ToString(); } private static void MultiPackagePrefix(IReadOnlyCollection<PackageUpdateSet> updates, StringBuilder builder) { var packageNames = updates .Select(p => CodeQuote(p.SelectedId)) .JoinWithCommas(); var projects = updates.SelectMany( u => u.CurrentPackages) .Select(p => p.Path.FullName) .Distinct() .ToList(); var projectOptS = (projects.Count > 1) ? "s" : string.Empty; builder.AppendLine($"{updates.Count} packages were updated in {projects.Count} project{projectOptS}:"); builder.AppendLine(packageNames); builder.AppendLine("<details>"); builder.AppendLine("<summary>Details of updated packages</summary>"); builder.AppendLine(""); } private static void MultiPackageFooter(StringBuilder builder) { builder.AppendLine("</details>"); builder.AppendLine(""); } private static string MakeCommitVersionDetails(PackageUpdateSet updates) { var versionsInUse = updates.CurrentPackages .Select(u => u.Version) .Distinct() .ToList(); var oldVersions = versionsInUse .Select(v => CodeQuote(v.ToString())) .ToList(); var minOldVersion = versionsInUse.Min(); var newVersion = CodeQuote(updates.SelectedVersion.ToString()); var packageId = CodeQuote(updates.SelectedId); var changeLevel = ChangeLevel(minOldVersion, updates.SelectedVersion); var builder = new StringBuilder(); if (oldVersions.Count == 1) { builder.AppendLine($"NuKeeper has generated a {changeLevel} update of {packageId} to {newVersion} from {oldVersions.JoinWithCommas()}"); } else { builder.AppendLine($"NuKeeper has generated a {changeLevel} update of {packageId} to {newVersion}"); builder.AppendLine($"{oldVersions.Count} versions of {packageId} were found in use: {oldVersions.JoinWithCommas()}"); } if (updates.Selected.Published.HasValue) { var packageWithVersion = CodeQuote(updates.SelectedId + " " + updates.SelectedVersion); var pubDateString = CodeQuote(DateFormat.AsUtcIso8601(updates.Selected.Published)); var pubDate = updates.Selected.Published.Value.UtcDateTime; var ago = TimeSpanFormat.Ago(pubDate, DateTime.UtcNow); builder.AppendLine($"{packageWithVersion} was published at {pubDateString}, {ago}"); } var highestVersion = updates.Packages.Major?.Identity.Version; if (highestVersion != null && (highestVersion > updates.SelectedVersion)) { LogHighestVersion(updates, highestVersion, builder); } builder.AppendLine(); if (updates.CurrentPackages.Count == 1) { builder.AppendLine("1 project update:"); } else { builder.AppendLine($"{updates.CurrentPackages.Count} project updates:"); } foreach (var current in updates.CurrentPackages) { var line = $"Updated {CodeQuote(current.Path.RelativePath)} to {packageId} {CodeQuote(updates.SelectedVersion.ToString())} from {CodeQuote(current.Version.ToString())}"; builder.AppendLine(line); } if (SourceIsPublicNuget(updates.Selected.Source.SourceUri)) { builder.AppendLine(); builder.AppendLine(NugetPackageLink(updates.Selected.Identity)); } return builder.ToString(); } private static void AddCommitFooter(StringBuilder builder) { builder.AppendLine(); builder.AppendLine("This is an automated update. Merge only if it passes tests"); builder.AppendLine("**NuKeeper**: https://github.com/NuKeeperDotNet/NuKeeper"); } private static string ChangeLevel(NuGetVersion oldVersion, NuGetVersion newVersion) { if (newVersion.Major > oldVersion.Major) { return "major"; } if (newVersion.Minor > oldVersion.Minor) { return "minor"; } if (newVersion.Patch > oldVersion.Patch) { return "patch"; } if (!newVersion.IsPrerelease && oldVersion.IsPrerelease) { return "out of beta"; } return string.Empty; } private static void LogHighestVersion(PackageUpdateSet updates, NuGetVersion highestVersion, StringBuilder builder) { var allowedChange = CodeQuote(updates.AllowedChange.ToString()); var highest = CodeQuote(updates.SelectedId + " " + highestVersion); var highestPublishedAt = HighestPublishedAt(updates.Packages.Major.Published); builder.AppendLine( $"There is also a higher version, {highest}{highestPublishedAt}, " + $"but this was not applied as only {allowedChange} version changes are allowed."); } private static string HighestPublishedAt(DateTimeOffset? highestPublishedAt) { if (!highestPublishedAt.HasValue) { return string.Empty; } var highestPubDate = highestPublishedAt.Value; var formattedPubDate = CodeQuote(DateFormat.AsUtcIso8601(highestPubDate)); var highestAgo = TimeSpanFormat.Ago(highestPubDate.UtcDateTime, DateTime.UtcNow); return $" published at {formattedPubDate}, {highestAgo}"; } private static string CodeQuote(string value) { return "`" + value + "`"; } private static bool SourceIsPublicNuget(Uri sourceUrl) { return sourceUrl != null && sourceUrl.ToString().StartsWith("https://api.nuget.org/", StringComparison.OrdinalIgnoreCase); } private static string NugetPackageLink(PackageIdentity package) { var url = $"https://www.nuget.org/packages/{package.Id}/{package.Version}"; return $"[{package.Id} {package.Version} on NuGet.org]({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.Buffers.Binary; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace System.Collections { // A vector of bits. Use this to store bits efficiently, without having to do bit // shifting yourself. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class BitArray : ICollection, ICloneable { private int[] m_array; // Do not rename (binary serialization) private int m_length; // Do not rename (binary serialization) private int _version; // Do not rename (binary serialization) private const int _ShrinkThreshold = 256; /*========================================================================= ** Allocates space to hold length bit values. All of the values in the bit ** array are set to false. ** ** Exceptions: ArgumentException if length < 0. =========================================================================*/ public BitArray(int length) : this(length, false) { } /*========================================================================= ** Allocates space to hold length bit values. All of the values in the bit ** array are set to defaultValue. ** ** Exceptions: ArgumentOutOfRangeException if length < 0. =========================================================================*/ public BitArray(int length, bool defaultValue) { if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), length, SR.ArgumentOutOfRange_NeedNonNegNum); } m_array = new int[GetInt32ArrayLengthFromBitLength(length)]; m_length = length; if (defaultValue) { m_array.AsSpan().Fill(-1); } _version = 0; } /*========================================================================= ** Allocates space to hold the bit values in bytes. bytes[0] represents ** bits 0 - 7, bytes[1] represents bits 8 - 15, etc. The LSB of each byte ** represents the lowest index value; bytes[0] & 1 represents bit 0, ** bytes[0] & 2 represents bit 1, bytes[0] & 4 represents bit 2, etc. ** ** Exceptions: ArgumentException if bytes == null. =========================================================================*/ public BitArray(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException(nameof(bytes)); } // this value is chosen to prevent overflow when computing m_length. // m_length is of type int32 and is exposed as a property, so // type of m_length can't be changed to accommodate. if (bytes.Length > int.MaxValue / BitsPerByte) { throw new ArgumentException(SR.Format(SR.Argument_ArrayTooLarge, BitsPerByte), nameof(bytes)); } m_array = new int[GetInt32ArrayLengthFromByteLength(bytes.Length)]; m_length = bytes.Length * BitsPerByte; uint totalCount = (uint)bytes.Length / 4; ReadOnlySpan<byte> byteSpan = bytes; for (int i = 0; i < totalCount; i++) { m_array[i] = BinaryPrimitives.ReadInt32LittleEndian(byteSpan); byteSpan = byteSpan.Slice(4); } Debug.Assert(byteSpan.Length >= 0 && byteSpan.Length < 4); int last = 0; switch (byteSpan.Length) { case 3: last = byteSpan[2] << 16; goto case 2; // fall through case 2: last |= byteSpan[1] << 8; goto case 1; // fall through case 1: m_array[totalCount] = last | byteSpan[0]; break; } _version = 0; } public BitArray(bool[] values) { if (values == null) { throw new ArgumentNullException(nameof(values)); } m_array = new int[GetInt32ArrayLengthFromBitLength(values.Length)]; m_length = values.Length; for (int i = 0; i < values.Length; i++) { if (values[i]) { int elementIndex = Div32Rem(i, out int extraBits); m_array[elementIndex] |= 1 << extraBits; } } _version = 0; } /*========================================================================= ** Allocates space to hold the bit values in values. values[0] represents ** bits 0 - 31, values[1] represents bits 32 - 63, etc. The LSB of each ** integer represents the lowest index value; values[0] & 1 represents bit ** 0, values[0] & 2 represents bit 1, values[0] & 4 represents bit 2, etc. ** ** Exceptions: ArgumentException if values == null. =========================================================================*/ public BitArray(int[] values) { if (values == null) { throw new ArgumentNullException(nameof(values)); } // this value is chosen to prevent overflow when computing m_length if (values.Length > int.MaxValue / BitsPerInt32) { throw new ArgumentException(SR.Format(SR.Argument_ArrayTooLarge, BitsPerInt32), nameof(values)); } m_array = new int[values.Length]; Array.Copy(values, 0, m_array, 0, values.Length); m_length = values.Length * BitsPerInt32; _version = 0; } /*========================================================================= ** Allocates a new BitArray with the same length and bit values as bits. ** ** Exceptions: ArgumentException if bits == null. =========================================================================*/ public BitArray(BitArray bits) { if (bits == null) { throw new ArgumentNullException(nameof(bits)); } int arrayLength = GetInt32ArrayLengthFromBitLength(bits.m_length); m_array = new int[arrayLength]; Debug.Assert(bits.m_array.Length <= arrayLength); Array.Copy(bits.m_array, 0, m_array, 0, arrayLength); m_length = bits.m_length; _version = bits._version; } public bool this[int index] { get => Get(index); set => Set(index, value); } /*========================================================================= ** Returns the bit value at position index. ** ** Exceptions: ArgumentOutOfRangeException if index < 0 or ** index >= GetLength(). =========================================================================*/ [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Get(int index) { if ((uint)index >= (uint)m_length) ThrowArgumentOutOfRangeException(index); return (m_array[index >> 5] & (1 << index)) != 0; } /*========================================================================= ** Sets the bit value at position index to value. ** ** Exceptions: ArgumentOutOfRangeException if index < 0 or ** index >= GetLength(). =========================================================================*/ [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(int index, bool value) { if ((uint)index >= (uint)m_length) ThrowArgumentOutOfRangeException(index); int bitMask = 1 << index; ref int segment = ref m_array[index >> 5]; if (value) { segment |= bitMask; } else { segment &= ~bitMask; } _version++; } /*========================================================================= ** Sets all the bit values to value. =========================================================================*/ public void SetAll(bool value) { int fillValue = value ? -1 : 0; int[] array = m_array; for (int i = 0; i < array.Length; i++) { array[i] = fillValue; } _version++; } /*========================================================================= ** Returns a reference to the current instance ANDed with value. ** ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ public unsafe BitArray And(BitArray value) { if (value == null) throw new ArgumentNullException(nameof(value)); // This method uses unsafe code to manipulate data in the BitArrays. To avoid issues with // buggy code concurrently mutating these instances in a way that could cause memory corruption, // we snapshot the arrays from both and then operate only on those snapshots, while also validating // that the count we iterate to is within the bounds of both arrays. We don't care about such code // corrupting the BitArray data in a way that produces incorrect answers, since BitArray is not meant // to be thread-safe; we only care about avoiding buffer overruns. int[] thisArray = m_array; int[] valueArray = value.m_array; int count = GetInt32ArrayLengthFromBitLength(Length); if (Length != value.Length || (uint)count > (uint)thisArray.Length || (uint)count > (uint)valueArray.Length) throw new ArgumentException(SR.Arg_ArrayLengthsDiffer); switch (count) { case 3: thisArray[2] &= valueArray[2]; goto case 2; case 2: thisArray[1] &= valueArray[1]; goto case 1; case 1: thisArray[0] &= valueArray[0]; goto Done; case 0: goto Done; } int i = 0; if (Sse2.IsSupported) { fixed (int* leftPtr = thisArray) fixed (int* rightPtr = valueArray) { for (; i < count - (Vector128<int>.Count - 1); i += Vector128<int>.Count) { Vector128<int> leftVec = Sse2.LoadVector128(leftPtr + i); Vector128<int> rightVec = Sse2.LoadVector128(rightPtr + i); Sse2.Store(leftPtr + i, Sse2.And(leftVec, rightVec)); } } } for (; i < count; i++) thisArray[i] &= valueArray[i]; Done: _version++; return this; } /*========================================================================= ** Returns a reference to the current instance ORed with value. ** ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ public unsafe BitArray Or(BitArray value) { if (value == null) throw new ArgumentNullException(nameof(value)); // This method uses unsafe code to manipulate data in the BitArrays. To avoid issues with // buggy code concurrently mutating these instances in a way that could cause memory corruption, // we snapshot the arrays from both and then operate only on those snapshots, while also validating // that the count we iterate to is within the bounds of both arrays. We don't care about such code // corrupting the BitArray data in a way that produces incorrect answers, since BitArray is not meant // to be thread-safe; we only care about avoiding buffer overruns. int[] thisArray = m_array; int[] valueArray = value.m_array; int count = GetInt32ArrayLengthFromBitLength(Length); if (Length != value.Length || (uint)count > (uint)thisArray.Length || (uint)count > (uint)valueArray.Length) throw new ArgumentException(SR.Arg_ArrayLengthsDiffer); switch (count) { case 3: thisArray[2] |= valueArray[2]; goto case 2; case 2: thisArray[1] |= valueArray[1]; goto case 1; case 1: thisArray[0] |= valueArray[0]; goto Done; case 0: goto Done; } int i = 0; if (Sse2.IsSupported) { fixed (int* leftPtr = thisArray) fixed (int* rightPtr = valueArray) { for (; i < count - (Vector128<int>.Count - 1); i += Vector128<int>.Count) { Vector128<int> leftVec = Sse2.LoadVector128(leftPtr + i); Vector128<int> rightVec = Sse2.LoadVector128(rightPtr + i); Sse2.Store(leftPtr + i, Sse2.Or(leftVec, rightVec)); } } } for (; i < count; i++) thisArray[i] |= valueArray[i]; Done: _version++; return this; } /*========================================================================= ** Returns a reference to the current instance XORed with value. ** ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ public unsafe BitArray Xor(BitArray value) { if (value == null) throw new ArgumentNullException(nameof(value)); // This method uses unsafe code to manipulate data in the BitArrays. To avoid issues with // buggy code concurrently mutating these instances in a way that could cause memory corruption, // we snapshot the arrays from both and then operate only on those snapshots, while also validating // that the count we iterate to is within the bounds of both arrays. We don't care about such code // corrupting the BitArray data in a way that produces incorrect answers, since BitArray is not meant // to be thread-safe; we only care about avoiding buffer overruns. int[] thisArray = m_array; int[] valueArray = value.m_array; int count = GetInt32ArrayLengthFromBitLength(Length); if (Length != value.Length || (uint)count > (uint)thisArray.Length || (uint)count > (uint)valueArray.Length) throw new ArgumentException(SR.Arg_ArrayLengthsDiffer); switch (count) { case 3: thisArray[2] ^= valueArray[2]; goto case 2; case 2: thisArray[1] ^= valueArray[1]; goto case 1; case 1: thisArray[0] ^= valueArray[0]; goto Done; case 0: goto Done; } int i = 0; if (Sse2.IsSupported) { fixed (int* leftPtr = thisArray) fixed (int* rightPtr = valueArray) { for (; i < count - (Vector128<int>.Count - 1); i += Vector128<int>.Count) { Vector128<int> leftVec = Sse2.LoadVector128(leftPtr + i); Vector128<int> rightVec = Sse2.LoadVector128(rightPtr + i); Sse2.Store(leftPtr + i, Sse2.Xor(leftVec, rightVec)); } } } for (; i < count; i++) thisArray[i] ^= valueArray[i]; Done: _version++; return this; } /*========================================================================= ** Inverts all the bit values. On/true bit values are converted to ** off/false. Off/false bit values are turned on/true. The current instance ** is updated and returned. =========================================================================*/ public BitArray Not() { int[] array = m_array; for (int i = 0; i < array.Length; i++) { array[i] = ~array[i]; } _version++; return this; } /*========================================================================= ** Shift all the bit values to right on count bits. The current instance is ** updated and returned. * ** Exceptions: ArgumentOutOfRangeException if count < 0 =========================================================================*/ public BitArray RightShift(int count) { if (count <= 0) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } _version++; return this; } int toIndex = 0; int ints = GetInt32ArrayLengthFromBitLength(m_length); if (count < m_length) { // We can not use Math.DivRem without taking a dependency on System.Runtime.Extensions int fromIndex = Div32Rem(count, out int shiftCount); Div32Rem(m_length, out int extraBits); if (shiftCount == 0) { unchecked { // Cannot use `(1u << extraBits) - 1u` as the mask // because for extraBits == 0, we need the mask to be 111...111, not 0. // In that case, we are shifting a uint by 32, which could be considered undefined. // The result of a shift operation is undefined ... if the right operand // is greater than or equal to the width in bits of the promoted left operand, // https://docs.microsoft.com/en-us/cpp/c-language/bitwise-shift-operators?view=vs-2017 // However, the compiler protects us from undefined behaviour by constraining the // right operand to between 0 and width - 1 (inclusive), i.e. right_operand = (right_operand % width). uint mask = uint.MaxValue >> (BitsPerInt32 - extraBits); m_array[ints - 1] &= (int)mask; } Array.Copy(m_array, fromIndex, m_array, 0, ints - fromIndex); toIndex = ints - fromIndex; } else { int lastIndex = ints - 1; unchecked { while (fromIndex < lastIndex) { uint right = (uint)m_array[fromIndex] >> shiftCount; int left = m_array[++fromIndex] << (BitsPerInt32 - shiftCount); m_array[toIndex++] = left | (int)right; } uint mask = uint.MaxValue >> (BitsPerInt32 - extraBits); mask &= (uint)m_array[fromIndex]; m_array[toIndex++] = (int)(mask >> shiftCount); } } } m_array.AsSpan(toIndex, ints - toIndex).Clear(); _version++; return this; } /*========================================================================= ** Shift all the bit values to left on count bits. The current instance is ** updated and returned. * ** Exceptions: ArgumentOutOfRangeException if count < 0 =========================================================================*/ public BitArray LeftShift(int count) { if (count <= 0) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } _version++; return this; } int lengthToClear; if (count < m_length) { int lastIndex = (m_length - 1) >> BitShiftPerInt32; // Divide by 32. // We can not use Math.DivRem without taking a dependency on System.Runtime.Extensions lengthToClear = Div32Rem(count, out int shiftCount); if (shiftCount == 0) { Array.Copy(m_array, 0, m_array, lengthToClear, lastIndex + 1 - lengthToClear); } else { int fromindex = lastIndex - lengthToClear; unchecked { while (fromindex > 0) { int left = m_array[fromindex] << shiftCount; uint right = (uint)m_array[--fromindex] >> (BitsPerInt32 - shiftCount); m_array[lastIndex] = left | (int)right; lastIndex--; } m_array[lastIndex] = m_array[fromindex] << shiftCount; } } } else { lengthToClear = GetInt32ArrayLengthFromBitLength(m_length); // Clear all } m_array.AsSpan(0, lengthToClear).Clear(); _version++; return this; } public int Length { get { return m_length; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedNonNegNum); } int newints = GetInt32ArrayLengthFromBitLength(value); if (newints > m_array.Length || newints + _ShrinkThreshold < m_array.Length) { // grow or shrink (if wasting more than _ShrinkThreshold ints) Array.Resize(ref m_array, newints); } if (value > m_length) { // clear high bit values in the last int int last = (m_length - 1) >> BitShiftPerInt32; Div32Rem(m_length, out int bits); if (bits > 0) { m_array[last] &= (1 << bits) - 1; } // clear remaining int values m_array.AsSpan(last + 1, newints - last - 1).Clear(); } m_length = value; _version++; } } public void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (array is int[] intArray) { Div32Rem(m_length, out int extraBits); if (extraBits == 0) { // we have perfect bit alignment, no need to sanitize, just copy Array.Copy(m_array, 0, intArray, index, m_array.Length); } else { int last = (m_length - 1) >> BitShiftPerInt32; // do not copy the last int, as it is not completely used Array.Copy(m_array, 0, intArray, index, last); // the last int needs to be masked intArray[index + last] = m_array[last] & unchecked((1 << extraBits) - 1); } } else if (array is byte[] byteArray) { int arrayLength = GetByteArrayLengthFromBitLength(m_length); if ((array.Length - index) < arrayLength) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // equivalent to m_length % BitsPerByte, since BitsPerByte is a power of 2 uint extraBits = (uint)m_length & (BitsPerByte - 1); if (extraBits > 0) { // last byte is not aligned, we will directly copy one less byte arrayLength -= 1; } Span<byte> span = byteArray.AsSpan(index); int quotient = Div4Rem(arrayLength, out int remainder); for (int i = 0; i < quotient; i++) { BinaryPrimitives.WriteInt32LittleEndian(span, m_array[i]); span = span.Slice(4); } if (extraBits > 0) { Debug.Assert(span.Length > 0); Debug.Assert(m_array.Length > quotient); // mask the final byte span[remainder] = (byte)((m_array[quotient] >> (remainder * 8)) & ((1 << (int)extraBits) - 1)); } switch (remainder) { case 3: span[2] = (byte)(m_array[quotient] >> 16); goto case 2; // fall through case 2: span[1] = (byte)(m_array[quotient] >> 8); goto case 1; // fall through case 1: span[0] = (byte)m_array[quotient]; break; } } else if (array is bool[] boolArray) { if (array.Length - index < m_length) { throw new ArgumentException(SR.Argument_InvalidOffLen); } for (int i = 0; i < m_length; i++) { int elementIndex = Div32Rem(i, out int extraBits); boolArray[index + i] = ((m_array[elementIndex] >> extraBits) & 0x00000001) != 0; } } else { throw new ArgumentException(SR.Arg_BitArrayTypeUnsupported, nameof(array)); } } public int Count => m_length; public object SyncRoot => this; public bool IsSynchronized => false; public bool IsReadOnly => false; public object Clone() => new BitArray(this); public IEnumerator GetEnumerator() => new BitArrayEnumeratorSimple(this); // XPerY=n means that n Xs can be stored in 1 Y. private const int BitsPerInt32 = 32; private const int BytesPerInt32 = 4; private const int BitsPerByte = 8; private const int BitShiftPerInt32 = 5; private const int BitShiftPerByte = 3; private const int BitShiftForBytesPerInt32 = 2; /// <summary> /// Used for conversion between different representations of bit array. /// Returns (n + (32 - 1)) / 32, rearranged to avoid arithmetic overflow. /// For example, in the bit to int case, the straightforward calc would /// be (n + 31) / 32, but that would cause overflow. So instead it's /// rearranged to ((n - 1) / 32) + 1. /// Due to sign extension, we don't need to special case for n == 0, if we use /// bitwise operations (since ((n - 1) >> 5) + 1 = 0). /// This doesn't hold true for ((n - 1) / 32) + 1, which equals 1. /// /// Usage: /// GetArrayLength(77): returns how many ints must be /// allocated to store 77 bits. /// </summary> /// <param name="n"></param> /// <returns>how many ints are required to store n bytes</returns> private static int GetInt32ArrayLengthFromBitLength(int n) { Debug.Assert(n >= 0); return (int)((uint)(n - 1 + (1 << BitShiftPerInt32)) >> BitShiftPerInt32); } private static int GetInt32ArrayLengthFromByteLength(int n) { Debug.Assert(n >= 0); // Due to sign extension, we don't need to special case for n == 0, since ((n - 1) >> 2) + 1 = 0 // This doesn't hold true for ((n - 1) / 4) + 1, which equals 1. return (int)((uint)(n - 1 + (1 << BitShiftForBytesPerInt32)) >> BitShiftForBytesPerInt32); } private static int GetByteArrayLengthFromBitLength(int n) { Debug.Assert(n >= 0); // Due to sign extension, we don't need to special case for n == 0, since ((n - 1) >> 3) + 1 = 0 // This doesn't hold true for ((n - 1) / 8) + 1, which equals 1. return (int)((uint)(n - 1 + (1 << BitShiftPerByte)) >> BitShiftPerByte); } private static int Div32Rem(int number, out int remainder) { uint quotient = (uint)number / 32; remainder = number & (32 - 1); // equivalent to number % 32, since 32 is a power of 2 return (int)quotient; } private static int Div4Rem(int number, out int remainder) { uint quotient = (uint)number / 4; remainder = number & (4 - 1); // equivalent to number % 4, since 4 is a power of 2 return (int)quotient; } private static void ThrowArgumentOutOfRangeException(int index) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } private class BitArrayEnumeratorSimple : IEnumerator, ICloneable { private BitArray _bitarray; private int _index; private readonly int _version; private bool _currentElement; internal BitArrayEnumeratorSimple(BitArray bitarray) { _bitarray = bitarray; _index = -1; _version = bitarray._version; } public object Clone() => MemberwiseClone(); public virtual bool MoveNext() { ICollection bitarrayAsICollection = _bitarray; if (_version != _bitarray._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index < (bitarrayAsICollection.Count - 1)) { _index++; _currentElement = _bitarray.Get(_index); return true; } else { _index = bitarrayAsICollection.Count; } return false; } public virtual object Current { get { if ((uint)_index >= (uint)_bitarray.Count) throw GetInvalidOperationException(_index); return _currentElement; } } public void Reset() { if (_version != _bitarray._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -1; } private InvalidOperationException GetInvalidOperationException(int index) { if (index == -1) { return new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } else { Debug.Assert(index >= _bitarray.Count); return new InvalidOperationException(SR.InvalidOperation_EnumEnded); } } } } }
/** * (C) Copyright IBM Corp. 2018, 2020. * * 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 NSubstitute; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Collections.Generic; using IBM.Cloud.SDK.Core.Http; using IBM.Cloud.SDK.Core.Http.Exceptions; using IBM.Cloud.SDK.Core.Authentication.NoAuth; using IBM.Watson.NaturalLanguageClassifier.v1.Model; using IBM.Cloud.SDK.Core.Model; namespace IBM.Watson.NaturalLanguageClassifier.v1.UnitTests { [TestClass] public class NaturalLanguageClassifierServiceUnitTests { #region Constructor [TestMethod, ExpectedException(typeof(ArgumentNullException))] public void Constructor_HttpClient_Null() { NaturalLanguageClassifierService service = new NaturalLanguageClassifierService(httpClient: null); } [TestMethod] public void ConstructorHttpClient() { NaturalLanguageClassifierService service = new NaturalLanguageClassifierService(new IBMHttpClient()); Assert.IsNotNull(service); } [TestMethod] public void ConstructorExternalConfig() { var apikey = System.Environment.GetEnvironmentVariable("NATURAL_LANGUAGE_CLASSIFIER_APIKEY"); System.Environment.SetEnvironmentVariable("NATURAL_LANGUAGE_CLASSIFIER_APIKEY", "apikey"); NaturalLanguageClassifierService service = Substitute.For<NaturalLanguageClassifierService>(); Assert.IsNotNull(service); System.Environment.SetEnvironmentVariable("NATURAL_LANGUAGE_CLASSIFIER_APIKEY", apikey); } [TestMethod] public void Constructor() { NaturalLanguageClassifierService service = new NaturalLanguageClassifierService(new IBMHttpClient()); Assert.IsNotNull(service); } [TestMethod] public void ConstructorAuthenticator() { NaturalLanguageClassifierService service = new NaturalLanguageClassifierService(new NoAuthAuthenticator()); Assert.IsNotNull(service); } [TestMethod] public void ConstructorNoUrl() { var apikey = System.Environment.GetEnvironmentVariable("NATURAL_LANGUAGE_CLASSIFIER_APIKEY"); System.Environment.SetEnvironmentVariable("NATURAL_LANGUAGE_CLASSIFIER_APIKEY", "apikey"); var url = System.Environment.GetEnvironmentVariable("NATURAL_LANGUAGE_CLASSIFIER_URL"); System.Environment.SetEnvironmentVariable("NATURAL_LANGUAGE_CLASSIFIER_URL", null); NaturalLanguageClassifierService service = Substitute.For<NaturalLanguageClassifierService>(); Assert.IsTrue(service.ServiceUrl == "https://api.us-south.natural-language-classifier.watson.cloud.ibm.com"); System.Environment.SetEnvironmentVariable("NATURAL_LANGUAGE_CLASSIFIER_URL", url); System.Environment.SetEnvironmentVariable("NATURAL_LANGUAGE_CLASSIFIER_APIKEY", apikey); } #endregion [TestMethod] public void Classify_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); NaturalLanguageClassifierService service = new NaturalLanguageClassifierService(client); var classifierId = "classifierId"; var text = "text"; var result = service.Classify(classifierId: classifierId, text: text); JObject bodyObject = new JObject(); if (!string.IsNullOrEmpty(text)) { bodyObject["text"] = JToken.FromObject(text); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); client.Received().PostAsync($"{service.ServiceUrl}/v1/classifiers/{classifierId}/classify"); } [TestMethod] public void ClassifyCollection_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); NaturalLanguageClassifierService service = new NaturalLanguageClassifierService(client); var classifierId = "classifierId"; var collection = new List<ClassifyInput>(); var result = service.ClassifyCollection(classifierId: classifierId, collection: collection); JObject bodyObject = new JObject(); if (collection != null && collection.Count > 0) { bodyObject["collection"] = JToken.FromObject(collection); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); client.Received().PostAsync($"{service.ServiceUrl}/v1/classifiers/{classifierId}/classify_collection"); } [TestMethod] public void CreateClassifier_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); NaturalLanguageClassifierService service = new NaturalLanguageClassifierService(client); var trainingMetadata = new MemoryStream(); var trainingData = new MemoryStream(); var result = service.CreateClassifier(trainingMetadata: trainingMetadata, trainingData: trainingData); } [TestMethod] public void ListClassifiers_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); NaturalLanguageClassifierService service = new NaturalLanguageClassifierService(client); var result = service.ListClassifiers(); } [TestMethod] public void GetClassifier_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); NaturalLanguageClassifierService service = new NaturalLanguageClassifierService(client); var classifierId = "classifierId"; var result = service.GetClassifier(classifierId: classifierId); client.Received().GetAsync($"{service.ServiceUrl}/v1/classifiers/{classifierId}"); } [TestMethod] public void DeleteClassifier_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.DeleteAsync(Arg.Any<string>()) .Returns(request); NaturalLanguageClassifierService service = new NaturalLanguageClassifierService(client); var classifierId = "classifierId"; var result = service.DeleteClassifier(classifierId: classifierId); client.Received().DeleteAsync($"{service.ServiceUrl}/v1/classifiers/{classifierId}"); } } }
namespace Nancy.Tests.Unit.ViewEngines { using System; using System.Dynamic; using System.IO; using System.Linq; using FakeItEasy; using Nancy.Conventions; using Nancy.Diagnostics; using Nancy.Tests.Fakes; using Nancy.ViewEngines; using Xunit; public class DefaultViewFactoryFixture { private readonly IViewResolver resolver; private readonly IRenderContextFactory renderContextFactory; private readonly ViewLocationContext viewLocationContext; private readonly ViewLocationConventions conventions; private readonly IRootPathProvider rootPathProvider; public DefaultViewFactoryFixture() { this.rootPathProvider = A.Fake<IRootPathProvider>(); A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns("The root path"); this.resolver = A.Fake<IViewResolver>(); this.renderContextFactory = A.Fake<IRenderContextFactory>(); this.conventions = new ViewLocationConventions(Enumerable.Empty<Func<string, object, ViewLocationContext, string>>()); this.viewLocationContext = new ViewLocationContext { Context = new NancyContext { Trace = new DefaultRequestTrace { TraceLog = new DefaultTraceLog() } } }; } private DefaultViewFactory CreateFactory(params IViewEngine[] viewEngines) { if (viewEngines == null) { viewEngines = ArrayCache.Empty<IViewEngine>(); } return new DefaultViewFactory(this.resolver, viewEngines, this.renderContextFactory, this.conventions, this.rootPathProvider); } [Fact] public void Should_get_render_context_from_factory_when_rendering_view() { // Given var viewEngines = new[] { A.Fake<IViewEngine>(), }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" }); var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader()); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location); var factory = this.CreateFactory(viewEngines); // When factory.RenderView("view.html", new object(), this.viewLocationContext); // Then A.CallTo(() => this.renderContextFactory.GetRenderContext(A<ViewLocationContext>.Ignored)).MustHaveHappened(); } [Fact] public void Should_render_view_with_context_created_by_factory() { // Given var viewEngines = new[] { A.Fake<IViewEngine>(), }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" }); var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader()); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location); var context = A.Fake<IRenderContext>(); A.CallTo(() => this.renderContextFactory.GetRenderContext(A<ViewLocationContext>.Ignored)).Returns(context); var factory = this.CreateFactory(viewEngines); // When factory.RenderView("view.html", new object(), this.viewLocationContext); // Then A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, A<object>.Ignored, context)).MustHaveHappened(); } [Fact] public void Should_not_build_render_context_more_than_once() { // Given var viewEngines = new[] { A.Fake<IViewEngine>(), }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" }); var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader()); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location); var factory = this.CreateFactory(viewEngines); // When factory.RenderView("view.html", new object(), this.viewLocationContext); // Then A.CallTo(() => this.renderContextFactory.GetRenderContext(A<ViewLocationContext>.Ignored)).MustHaveHappened(Repeated.NoMoreThan.Once); } [Fact] public void Should_throw_argumentnullexception_when_rendering_view_and_viewlocationcontext_is_null() { // Given var factory = this.CreateFactory(null); // When var exception = Record.Exception(() => factory.RenderView("viewName", new object(), null)); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public void Should_throw_argumentexception_when_rendering_view_and_view_name_is_empty_and_model_is_null() { // Given var factory = this.CreateFactory(null); // When var exception = Record.Exception(() => factory.RenderView(string.Empty, null, this.viewLocationContext)); // Then exception.ShouldBeOfType<ArgumentException>(); } [Fact] public void Should_throw_argumentexception_when_rendering_view_and_both_viewname_and_model_is_null() { // Given var factory = this.CreateFactory(null); // When var exception = Record.Exception(() => factory.RenderView(null, null, this.viewLocationContext)); // Then exception.ShouldBeOfType<ArgumentException>(); } [Fact] public void Should_retrieve_view_from_view_locator_using_provided_view_name() { // Given var factory = this.CreateFactory(); // When Record.Exception(() => factory.RenderView("viewname.html", null, this.viewLocationContext)); // Then A.CallTo(() => this.resolver.GetViewLocation("viewname.html", A<object>.Ignored, A<ViewLocationContext>.Ignored)).MustHaveHappened(); } [Fact] public void Should_retrieve_view_from_view_locator_using_provided_model() { // Given var factory = this.CreateFactory(); var model = new object(); // When Record.Exception(() => factory.RenderView(null, model, this.viewLocationContext)); // Then A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, model, A<ViewLocationContext>.Ignored)).MustHaveHappened(); } [Fact] public void Should_retrieve_view_from_view_locator_using_provided_module_path() { // Given var factory = this.CreateFactory(); var model = new object(); var viewContext = new ViewLocationContext { Context = new NancyContext { Trace = new DefaultRequestTrace { TraceLog = new DefaultTraceLog() } }, ModulePath = "/bar" }; // When Record.Exception(() => factory.RenderView(null, model, viewContext)); // Then A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.That.Matches(x => x.ModulePath.Equals("/bar")))).MustHaveHappened(); } [Fact] public void Should_call_first_view_engine_that_supports_extension_with_view_location_results() { // Given var viewEngines = new[] { A.Fake<IViewEngine>(), A.Fake<IViewEngine>(), }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" }); A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { "html" }); var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader()); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location); var factory = this.CreateFactory(viewEngines); // When factory.RenderView("foo", null, this.viewLocationContext); // Then A.CallTo(() => viewEngines[0].RenderView(location, null, A<IRenderContext>.Ignored)).MustHaveHappened(); } [Fact] public void Should_ignore_case_when_locating_view_engine_for_view_name_extension() { // Given var viewEngines = new[] { A.Fake<IViewEngine>(), }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "HTML" }); var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader()); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location); var factory = this.CreateFactory(viewEngines); // When factory.RenderView("foo", null, this.viewLocationContext); // Then A.CallTo(() => viewEngines[0].RenderView(location, null, A<IRenderContext>.Ignored)).MustHaveHappened(); } [Fact] public void Should_return_response_from_invoked_engine() { // Given var viewEngines = new[] { A.Fake<IViewEngine>(), }; Action<Stream> actionReturnedFromEngine = x => { }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" }); A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, null, A<IRenderContext>.Ignored)).Returns(actionReturnedFromEngine); var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader()); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location); var factory = this.CreateFactory(viewEngines); // When var response = factory.RenderView("foo", null, this.viewLocationContext); // Then response.Contents.ShouldBeSameAs(actionReturnedFromEngine); } [Fact] public void Should_return_empty_action_when_view_engine_throws_exception() { var viewEngines = new[] { A.Fake<IViewEngine>(), }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" }); A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, null, A<IRenderContext>.Ignored)).Throws(new Exception()); var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader()); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location); var stream = new MemoryStream(); var factory = this.CreateFactory(viewEngines); // When var response = factory.RenderView("foo", null, this.viewLocationContext); response.Contents.Invoke(stream); // Then stream.Length.ShouldEqual(0L); } [Fact] public void Should_invoke_view_engine_with_model() { // Given var viewEngines = new[] { A.Fake<IViewEngine>(), }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" }); A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, null, null)).Throws(new Exception()); var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader()); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location); var model = new object(); var factory = this.CreateFactory(viewEngines); // When factory.RenderView("foo", model, this.viewLocationContext); // Then A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, model, A<IRenderContext>.Ignored)).MustHaveHappened(); } [Fact] public void Should_covert_anonymoustype_model_to_expandoobject_before_invoking_view_engine() { // Given var viewEngines = new[] { A.Fake<IViewEngine>(), }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" }); var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader()); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location); var model = new { Name = "" }; var factory = this.CreateFactory(viewEngines); // When factory.RenderView("foo", model, this.viewLocationContext); // Then A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, A<object>.That.Matches(x => x.GetType().Equals(typeof(ExpandoObject))), A<IRenderContext>.Ignored)).MustHaveHappened(); } [Fact] public void Should_transfer_anonymoustype_model_members_to_expandoobject_members_before_invoking_view_engines() { // Given var viewEngines = new[] { new FakeViewEngine { Extensions = new[] { "html"}} }; var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader()); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location); var model = new { Name = "Nancy" }; var factory = this.CreateFactory(viewEngines); // When factory.RenderView("foo", model, this.viewLocationContext); // Then ((string)viewEngines[0].Model.Name).ShouldEqual("Nancy"); } [Fact] public void Should_use_the_name_of_the_model_type_as_view_name_when_only_model_is_specified() { // Given var factory = this.CreateFactory(); // When Record.Exception(() => factory.RenderView(null, new object(), this.viewLocationContext)); // Then A.CallTo(() => this.resolver.GetViewLocation("Object", A<object>.Ignored, A<ViewLocationContext>.Ignored)).MustHaveHappened(); } [Fact] public void Should_use_the_name_of_the_model_type_without_model_suffix_as_view_name_when_only_model_is_specified() { // Given var factory = this.CreateFactory(); // When Record.Exception(() => factory.RenderView(null, new ViewModel(), this.viewLocationContext)); // Then A.CallTo(() => this.resolver.GetViewLocation("View", A<object>.Ignored, A<ViewLocationContext>.Ignored)).MustHaveHappened(); } [Fact] public void Should_throw_when_view_could_not_be_located() { var factory = this.CreateFactory(); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(null); var result = Record.Exception(() => factory.RenderView("foo", null, this.viewLocationContext)); result.ShouldBeOfType<ViewNotFoundException>(); } [Fact] public void Should_provide_view_name_and_available_extensions_in_not_found_exception() { var viewEngines = new[] { A.Fake<IViewEngine>(), A.Fake<IViewEngine>(), }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" }); A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { "sshtml" }); var factory = this.CreateFactory(viewEngines); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(null); var result = Record.Exception(() => factory.RenderView("foo", null, this.viewLocationContext)) as ViewNotFoundException; result.AvailableViewEngineExtensions.ShouldEqualSequence(new[] { "html", "sshtml" }); result.ViewName.ShouldEqual("foo"); } [Fact] public void Should_provide_list_of_inspected_view_locations_in_not_found_exception() { var viewEngines = new[] { A.Fake<IViewEngine>(), A.Fake<IViewEngine>(), }; A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" }); A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { "sshtml" }); var conventions = new Func<string, dynamic, ViewLocationContext, string>[] {(a,b,c) => "baz"}; var factory = new DefaultViewFactory(this.resolver, viewEngines, this.renderContextFactory, new ViewLocationConventions(conventions), this.rootPathProvider); A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(null); var result = (Record.Exception(() => factory.RenderView("foo", null, this.viewLocationContext))) as ViewNotFoundException; result.AvailableViewEngineExtensions.ShouldEqualSequence(new[] { "html", "sshtml" }); result.ViewName.ShouldEqual("foo"); result.InspectedLocations.ShouldEqualSequence(new [] {"baz"}); } private static Func<TextReader> GetEmptyContentReader() { return () => new StreamReader(new MemoryStream()); } } }
using System; using System.Collections.Generic; using System.Web.Routing; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Payments; using Nop.Core.Plugins; using Nop.Plugin.Payments.Manual.Controllers; using Nop.Services.Configuration; using Nop.Services.Localization; using Nop.Services.Orders; using Nop.Services.Payments; namespace Nop.Plugin.Payments.Manual { /// <summary> /// Manual payment processor /// </summary> public class ManualPaymentProcessor : BasePlugin, IPaymentMethod { #region Fields private readonly ILocalizationService _localizationService; private readonly IOrderTotalCalculationService _orderTotalCalculationService; private readonly ISettingService _settingService; private readonly ManualPaymentSettings _manualPaymentSettings; #endregion #region Ctor public ManualPaymentProcessor(ILocalizationService localizationService, IOrderTotalCalculationService orderTotalCalculationService, ISettingService settingService, ManualPaymentSettings manualPaymentSettings) { this._localizationService = localizationService; this._orderTotalCalculationService = orderTotalCalculationService; this._settingService = settingService; this._manualPaymentSettings = manualPaymentSettings; } #endregion #region Methods /// <summary> /// Process a payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); result.AllowStoringCreditCardNumber = true; switch (_manualPaymentSettings.TransactMode) { case TransactMode.Pending: result.NewPaymentStatus = PaymentStatus.Pending; break; case TransactMode.Authorize: result.NewPaymentStatus = PaymentStatus.Authorized; break; case TransactMode.AuthorizeAndCapture: result.NewPaymentStatus = PaymentStatus.Paid; break; default: { result.AddError("Not supported transaction type"); return result; } } return result; } /// <summary> /// Post process payment (used by payment gateways that require redirecting to a third-party URL) /// </summary> /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param> public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest) { //nothing } /// <summary> /// Returns a value indicating whether payment method should be hidden during checkout /// </summary> /// <param name="cart">Shoping cart</param> /// <returns>true - hide; false - display.</returns> public bool HidePaymentMethod(IList<ShoppingCartItem> cart) { //you can put any logic here //for example, hide this payment method if all products in the cart are downloadable //or hide this payment method if current customer is from certain country return false; } /// <summary> /// Gets additional handling fee /// </summary> /// <returns>Additional handling fee</returns> public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart) { var result = this.CalculateAdditionalFee(_orderTotalCalculationService, cart, _manualPaymentSettings.AdditionalFee, _manualPaymentSettings.AdditionalFeePercentage); return result; } /// <summary> /// Captures payment /// </summary> /// <param name="capturePaymentRequest">Capture payment request</param> /// <returns>Capture payment result</returns> public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest) { var result = new CapturePaymentResult(); result.AddError("Capture method not supported"); return result; } /// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); result.AddError("Refund method not supported"); return result; } /// <summary> /// Voids a payment /// </summary> /// <param name="voidPaymentRequest">Request</param> /// <returns>Result</returns> public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest) { var result = new VoidPaymentResult(); result.AddError("Void method not supported"); return result; } /// <summary> /// Process recurring payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); result.AllowStoringCreditCardNumber = true; switch (_manualPaymentSettings.TransactMode) { case TransactMode.Pending: result.NewPaymentStatus = PaymentStatus.Pending; break; case TransactMode.Authorize: result.NewPaymentStatus = PaymentStatus.Authorized; break; case TransactMode.AuthorizeAndCapture: result.NewPaymentStatus = PaymentStatus.Paid; break; default: { result.AddError("Not supported transaction type"); return result; } } return result; } /// <summary> /// Cancels a recurring payment /// </summary> /// <param name="cancelPaymentRequest">Request</param> /// <returns>Result</returns> public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest) { //always success return new CancelRecurringPaymentResult(); } /// <summary> /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods) /// </summary> /// <param name="order">Order</param> /// <returns>Result</returns> public bool CanRePostProcessPayment(Order order) { if (order == null) throw new ArgumentNullException("order"); //it's not a redirection payment method. So we always return false return false; } /// <summary> /// Gets a route for provider configuration /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "Configure"; controllerName = "PaymentManual"; routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.Manual.Controllers" }, { "area", null } }; } /// <summary> /// Gets a route for payment info /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "PaymentInfo"; controllerName = "PaymentManual"; routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.Manual.Controllers" }, { "area", null } }; } /// <summary> /// Get the type of controller /// </summary> /// <returns>Type</returns> public Type GetControllerType() { return typeof(PaymentManualController); } /// <summary> /// Install the plugin /// </summary> public override void Install() { //settings var settings = new ManualPaymentSettings { TransactMode = TransactMode.Pending }; _settingService.SaveSetting(settings); //locales this.AddOrUpdatePluginLocaleResource("Plugins.Payments.Manual.Fields.AdditionalFee", "Additional fee"); this.AddOrUpdatePluginLocaleResource("Plugins.Payments.Manual.Fields.AdditionalFee.Hint", "Enter additional fee to charge your customers."); this.AddOrUpdatePluginLocaleResource("Plugins.Payments.Manual.Fields.AdditionalFeePercentage", "Additional fee. Use percentage"); this.AddOrUpdatePluginLocaleResource("Plugins.Payments.Manual.Fields.AdditionalFeePercentage.Hint", "Determines whether to apply a percentage additional fee to the order total. If not enabled, a fixed value is used."); this.AddOrUpdatePluginLocaleResource("Plugins.Payments.Manual.Fields.TransactMode", "After checkout mark payment as"); this.AddOrUpdatePluginLocaleResource("Plugins.Payments.Manual.Fields.TransactMode.Hint", "Specify transaction mode."); this.AddOrUpdatePluginLocaleResource("Plugins.Payments.Manual.PaymentMethodDescription", "Pay by credit / debit card"); base.Install(); } /// <summary> /// Uninstall the plugin /// </summary> public override void Uninstall() { //settings _settingService.DeleteSetting<ManualPaymentSettings>(); //locales this.DeletePluginLocaleResource("Plugins.Payments.Manual.Fields.AdditionalFee"); this.DeletePluginLocaleResource("Plugins.Payments.Manual.Fields.AdditionalFee.Hint"); this.DeletePluginLocaleResource("Plugins.Payments.Manual.Fields.AdditionalFeePercentage"); this.DeletePluginLocaleResource("Plugins.Payments.Manual.Fields.AdditionalFeePercentage.Hint"); this.DeletePluginLocaleResource("Plugins.Payments.Manual.Fields.TransactMode"); this.DeletePluginLocaleResource("Plugins.Payments.Manual.Fields.TransactMode.Hint"); this.DeletePluginLocaleResource("Plugins.Payments.Manual.PaymentMethodDescription"); base.Uninstall(); } #endregion #region Properties /// <summary> /// Gets a value indicating whether capture is supported /// </summary> public bool SupportCapture { get { return false; } } /// <summary> /// Gets a value indicating whether partial refund is supported /// </summary> public bool SupportPartiallyRefund { get { return false; } } /// <summary> /// Gets a value indicating whether refund is supported /// </summary> public bool SupportRefund { get { return false; } } /// <summary> /// Gets a value indicating whether void is supported /// </summary> public bool SupportVoid { get { return false; } } /// <summary> /// Gets a recurring payment type of payment method /// </summary> public RecurringPaymentType RecurringPaymentType { get { return RecurringPaymentType.Manual; } } /// <summary> /// Gets a payment method type /// </summary> public PaymentMethodType PaymentMethodType { get { return PaymentMethodType.Standard; } } /// <summary> /// Gets a value indicating whether we should display a payment information page for this plugin /// </summary> public bool SkipPaymentInfo { get { return false; } } /// <summary> /// Gets a payment method description that will be displayed on checkout pages in the public store /// </summary> public string PaymentMethodDescription { //return description of this payment method to be display on "payment method" checkout step. good practice is to make it localizable //for example, for a redirection payment method, description may be like this: "You will be redirected to PayPal site to complete the payment" get { return _localizationService.GetResource("Plugins.Payments.Manual.PaymentMethodDescription"); } } #endregion } }
using FluentAssertions; using Microsoft.EntityFrameworkCore; using Moq; using Ritter.Domain; using Ritter.Infra.Crosscutting.Specifications; using Ritter.Infra.Data.Tests.Extensions; using Ritter.Infra.Data.Tests.Mocks; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Ritter.Infra.Data.Tests.Repositories { public class Repository_Any { [Fact] public void ReturnsTrueGivenAnyEntity() { List<Test> mockedTests = MockTests(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.Any(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeTrue(); } [Fact] public void ReturnsTrueGivenAnyEntityAsync() { List<Test> mockedTests = MockTests(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.AnyAsync().GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeTrue(); } [Fact] public void ReturnsFalseGivenNoneEntity() { List<Test> mockedTests = MockTests(0); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.Any(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeFalse(); } [Fact] public void ReturnsFalseGivenNoneEntityAsync() { List<Test> mockedTests = MockTests(0); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.AnyAsync().GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeFalse(); } [Fact] public void ReturnsTrueGivenAnyActiveEntity() { List<Test> mockedTests = MockTests(); mockedTests.First().Deactivate(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISpecification<Test> spec = new DirectSpecification<Test>(t => t.Active); ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.Any(spec); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeTrue(); } [Fact] public void ReturnsTrueGivenAnyActiveEntityAsync() { List<Test> mockedTests = MockTests(); mockedTests.First().Deactivate(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISpecification<Test> spec = new DirectSpecification<Test>(t => t.Active); ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.AnyAsync(spec).GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeTrue(); } [Fact] public void ReturnsFalseGivenNoneActiveEntity() { List<Test> mockedTests = MockTests(1); mockedTests.First().Deactivate(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISpecification<Test> spec = new DirectSpecification<Test>(t => t.Active); ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.Any(spec); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeFalse(); } [Fact] public void ReturnsFalseGivenNoneActiveEntityAsync() { List<Test> mockedTests = MockTests(1); mockedTests.First().Deactivate(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISpecification<Test> spec = new DirectSpecification<Test>(t => t.Active); ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.AnyAsync(spec).GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeFalse(); } [Fact] public void ThrowsArgumentNullExceptionGivenNullSpecification() { Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); Action act = () => { ISpecification<Test> spec = null; ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.Any(spec); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("specification"); } [Fact] public void ThrowsArgumentNullExceptionGivenNullSpecificationAsync() { Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); Action act = () => { ISpecification<Test> spec = null; ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.AnyAsync(spec).GetAwaiter().GetResult(); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("specification"); } private static List<Test> MockTests(int count) { List<Test> tests = new List<Test>(); for (int i = 1; i <= count; i++) { tests.Add(new Test(i)); } return tests; } private static List<Test> MockTests() { return MockTests(5); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.UseCoalesceExpression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.UseCoalesceExpression; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCoalesceExpression { public class UseCoalesceExpressionTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseCoalesceExpressionDiagnosticAnalyzer(), new UseCoalesceExpressionCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnLeft_Equals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y) { var z = [||]x == null ? y : x; } }", @"using System; class C { void M(string x, string y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnLeft_NotEquals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y) { var z = [||]x != null ? x : y; } }", @"using System; class C { void M(string x, string y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnRight_Equals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y) { var z = [||]null == x ? y : x; } }", @"using System; class C { void M(string x, string y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnRight_NotEquals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y) { var z = [||]null != x ? x : y; } }", @"using System; class C { void M(string x, string y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestComplexExpression() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y) { var z = [||]x.ToString() == null ? y : x.ToString(); } }", @"using System; class C { void M(string x, string y) { var z = x.ToString() ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestParens1() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y) { var z = [||](x == null) ? y : x; } }", @"using System; class C { void M(string x, string y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestParens2() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y) { var z = [||](x) == null ? y : x; } }", @"using System; class C { void M(string x, string y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestParens3() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y) { var z = [||]x == null ? y : (x); } }", @"using System; class C { void M(string x, string y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestParens4() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y) { var z = [||]x == null ? (y) : x; } }", @"using System; class C { void M(string x, string y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y) { var z1 = {|FixAllInDocument:x|} == null ? y : x; var z2 = x != null ? x : y; } }", @"using System; class C { void M(string x, string y) { var z1 = x ?? y; var z2 = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y, string z) { var w = {|FixAllInDocument:x|} != null ? x : y.ToString(z != null ? z : y); } }", @"using System; class C { void M(string x, string y, string z) { var w = x ?? y.ToString(z ?? y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestFixAll3() { await TestInRegularAndScriptAsync( @"using System; class C { void M(string x, string y, string z) { var w = {|FixAllInDocument:x|} != null ? x : y != null ? y : z; } }", @"using System; class C { void M(string x, string y, string z) { var w = x ?? y ?? z; } }"); } [WorkItem(16025, "https://github.com/dotnet/roslyn/issues/16025")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestTrivia1() { await TestInRegularAndScriptAsync( @"using System; class Program { public Program() { string x = ""; string y = [|x|] == null ? string.Empty : x; } }", @"using System; class Program { public Program() { string x = ""; string y = x ?? string.Empty; } }", ignoreTrivia: false); } [WorkItem(17028, "https://github.com/dotnet/roslyn/issues/17028")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestInExpressionOfT() { await TestInRegularAndScriptAsync( @"using System; using System.Linq.Expressions; class C { void Main(string s, string y) { Expression<Func<string>> e = () => [||]s != null ? s : y; } }", @"using System; using System.Linq.Expressions; class C { void Main(string s, string y) { Expression<Func<string>> e = () => {|Warning:s ?? y|}; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestUnconstrainedTypeParameter() { await TestMissingInRegularAndScriptAsync( @" class C<T> { void Main(T t) { var v = [||]t == null ? throw new Exception() : t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestStructConstrainedTypeParameter() { await TestMissingInRegularAndScriptAsync( @" class C<T> where T : struct { void Main(T t) { var v = [||]t == null ? throw new Exception() : t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestClassConstrainedTypeParameter() { await TestInRegularAndScriptAsync( @" class C<T> where T : class { void Main(T t) { var v = [||]t == null ? throw new Exception() : t; } }", @" class C<T> where T : class { void Main(T t) { var v = t ?? throw new Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestNotOnNullable() { await TestMissingInRegularAndScriptAsync( @" class C { void Main(int? t) { var v = [||]t == null ? throw new Exception() : t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnArray() { await TestInRegularAndScriptAsync( @" class C { void Main(int[] t) { var v = [||]t == null ? throw new Exception() : t; } }", @" class C { void Main(int[] t) { var v = t ?? throw new Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnInterface() { await TestInRegularAndScriptAsync( @" class C { void Main(System.ICloneable t) { var v = [||]t == null ? throw new Exception() : t; } }", @" class C { void Main(System.ICloneable t) { var v = t ?? throw new Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnDynamic() { await TestInRegularAndScriptAsync( @" class C { void Main(dynamic t) { var v = [||]t == null ? throw new Exception() : t; } }", @" class C { void Main(dynamic t) { var v = t ?? throw new Exception(); } }"); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Lucene.Net.Search; using NUnit.Framework; namespace Lucene.Net.Search.Vectorhighlight { [TestFixture] public class SimpleFragListBuilderTest : AbstractTestCase { [Test] public void TestNullFieldFragList() { SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl("a", "b c d"), 100); Assert.AreEqual(0, ffl.fragInfos.Count); } [Test] public void TestTooSmallFragSize() { SimpleFragListBuilder sflb = new SimpleFragListBuilder(); Assert.Throws<ArgumentException>( () => sflb.CreateFieldFragList(fpl("a", "b c d"), SimpleFragListBuilder.MIN_FRAG_CHAR_SIZE - 1), "ArgumentException must be thrown"); } [Test] public void TestSmallerFragSizeThanTermQuery() { SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl("abcdefghijklmnopqrs", "abcdefghijklmnopqrs"), SimpleFragListBuilder.MIN_FRAG_CHAR_SIZE); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(abcdefghijklmnopqrs((0,19)))/1.0(0,19)", ffl.fragInfos[0].ToString()); } [Test] public void TestSmallerFragSizeThanPhraseQuery() { SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList( fpl( "\"abcdefgh jklmnopqrs\"", "abcdefgh jklmnopqrs" ), SimpleFragListBuilder.MIN_FRAG_CHAR_SIZE ); Assert.AreEqual( 1, ffl.fragInfos.Count ); Console.WriteLine( ffl.fragInfos[ 0 ].ToString() ); Assert.AreEqual( "subInfos=(abcdefghjklmnopqrs((0,21)))/1.0(0,21)", ffl.fragInfos[0] .ToString() ); } [Test] public void Test1TermIndex() { SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl("a", "a"), 100); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(a((0,1)))/1.0(0,100)", ffl.fragInfos[0].ToString()); } [Test] public void Test2TermsIndex1Frag() { SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl("a", "a a"), 100); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(a((0,1))a((2,3)))/2.0(0,100)", ffl.fragInfos[0].ToString()); ffl = sflb.CreateFieldFragList(fpl("a", "a b b b b b b b b a"), 20); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(a((0,1))a((18,19)))/2.0(0,20)", ffl.fragInfos[0].ToString()); ffl = sflb.CreateFieldFragList(fpl("a", "b b b b a b b b b a"), 20); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(a((8,9))a((18,19)))/2.0(2,22)", ffl.fragInfos[0].ToString()); } [Test] public void Test2TermsIndex2Frags() { SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl("a", "a b b b b b b b b b b b b b a"), 20); Assert.AreEqual(2, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(a((0,1)))/1.0(0,20)", ffl.fragInfos[0].ToString()); Assert.AreEqual("subInfos=(a((28,29)))/1.0(22,42)", ffl.fragInfos[1].ToString()); ffl = sflb.CreateFieldFragList(fpl("a", "a b b b b b b b b b b b b a"), 20); Assert.AreEqual(2, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(a((0,1)))/1.0(0,20)", ffl.fragInfos[0].ToString()); Assert.AreEqual("subInfos=(a((26,27)))/1.0(20,40)", ffl.fragInfos[1].ToString()); ffl = sflb.CreateFieldFragList(fpl("a", "a b b b b b b b b b a"), 20); Assert.AreEqual(2, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(a((0,1)))/1.0(0,20)", ffl.fragInfos[0].ToString()); Assert.AreEqual("subInfos=(a((20,21)))/1.0(20,40)", ffl.fragInfos[1].ToString()); } [Test] public void Test2TermsQuery() { SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl("a b", "c d e"), 20); Assert.AreEqual(0, ffl.fragInfos.Count); ffl = sflb.CreateFieldFragList(fpl("a b", "d b c"), 20); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(b((2,3)))/1.0(0,20)", ffl.fragInfos[0].ToString()); ffl = sflb.CreateFieldFragList(fpl("a b", "a b c"), 20); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(a((0,1))b((2,3)))/2.0(0,20)", ffl.fragInfos[0].ToString()); } [Test] public void TestPhraseQuery() { SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl("\"a b\"", "c d e"), 20); Assert.AreEqual(0, ffl.fragInfos.Count); ffl = sflb.CreateFieldFragList(fpl("\"a b\"", "a c b"), 20); Assert.AreEqual(0, ffl.fragInfos.Count); ffl = sflb.CreateFieldFragList(fpl("\"a b\"", "a b c"), 20); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(ab((0,3)))/1.0(0,20)", ffl.fragInfos[0].ToString()); } [Test] public void TestPhraseQuerySlop() { SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl("\"a b\"~1", "a c b"), 20); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(ab((0,1)(4,5)))/1.0(0,20)", ffl.fragInfos[0].ToString()); } private FieldPhraseList fpl(String queryValue, String indexValue) { Make1d1fIndex(indexValue); Query query = paW.Parse(queryValue); FieldQuery fq = new FieldQuery(query, true, true); FieldTermStack stack = new FieldTermStack(reader, 0, F, fq); return new FieldPhraseList(stack, fq); } [Test] public void Test1PhraseShortMV() { MakeIndexShortMV(); FieldQuery fq = new FieldQuery(Tq("d"), true, true); FieldTermStack stack = new FieldTermStack(reader, 0, F, fq); FieldPhraseList fpl = new FieldPhraseList(stack, fq); SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl, 100); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(d((6,7)))/1.0(0,100)", ffl.fragInfos[0].ToString()); } [Test] public void Test1PhraseLongMV() { MakeIndexLongMV(); FieldQuery fq = new FieldQuery(PqF("search", "engines"), true, true); FieldTermStack stack = new FieldTermStack(reader, 0, F, fq); FieldPhraseList fpl = new FieldPhraseList(stack, fq); SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl, 100); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(searchengines((102,116))searchengines((157,171)))/2.0(96,196)", ffl.fragInfos[0].ToString()); } [Test] public void Test1PhraseLongMVB() { MakeIndexLongMVB(); FieldQuery fq = new FieldQuery(PqF("sp", "pe", "ee", "ed"), true, true); // "speed" -(2gram)-> "sp","pe","ee","ed" FieldTermStack stack = new FieldTermStack(reader, 0, F, fq); FieldPhraseList fpl = new FieldPhraseList(stack, fq); SimpleFragListBuilder sflb = new SimpleFragListBuilder(); FieldFragList ffl = sflb.CreateFieldFragList(fpl, 100); Assert.AreEqual(1, ffl.fragInfos.Count); Assert.AreEqual("subInfos=(sppeeeed((88,93)))/1.0(82,182)", ffl.fragInfos[0].ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class GroupJoinTests : EnumerableTests { public struct CustomerRec { public string name; public int? custID; } public struct OrderRec { public int? orderID; public int? custID; public int? total; } public struct AnagramRec { public string name; public int? orderID; public int? total; } public struct JoinRec : IEquatable<JoinRec> { public string name; public int?[] orderID; public int?[] total; public override int GetHashCode() { // Not great, but it'll serve. return name.GetHashCode() ^ orderID.Length ^ (total.Length * 31); } public bool Equals(JoinRec other) { if (!string.Equals(name, other.name)) return false; if (orderID == null) { if (other.orderID != null) return false; } else { if (other.orderID == null) return false; if (orderID.Length != other.orderID.Length) return false; for (int i = 0; i != other.orderID.Length; ++i) if (orderID[i] != other.orderID[i]) return false; } if (total == null) { if (other.total != null) return false; } else { if (other.total == null) return false; if (total.Length != other.total.Length) return false; for (int i = 0; i != other.total.Length; ++i) if (total[i] != other.total[i]) return false; } return true; } public override bool Equals(object obj) { return obj is JoinRec && Equals((JoinRec)obj); } } public static JoinRec createJoinRec(CustomerRec cr, IEnumerable<OrderRec> orIE) { return new JoinRec { name = cr.name, orderID = orIE.Select(o => o.orderID).ToArray(), total = orIE.Select(o => o.total).ToArray(), }; } public static JoinRec createJoinRec(CustomerRec cr, IEnumerable<AnagramRec> arIE) { return new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray(), }; } [Fact] public void OuterEmptyInnerNonEmpty() { CustomerRec[] outer = { }; OrderRec[] inner = new [] { new OrderRec{ orderID = 45321, custID = 98022, total = 50 }, new OrderRec{ orderID = 97865, custID = 32103, total = 25 } }; Assert.Empty(outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void CustomComparer() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new [] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ 93489 }, total = new int?[]{ 45 } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Robert", orderID = new int?[]{ 93483 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void OuterNull() { CustomerRec[] outer = null; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("outer", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void InnerNull() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = null; Assert.Throws<ArgumentNullException>("inner", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void OuterKeySelectorNull() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("outerKeySelector", () => outer.GroupJoin(inner, null, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void InnerKeySelectorNull() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("innerKeySelector", () => outer.GroupJoin(inner, e => e.name, null, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNull() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("resultSelector", () => outer.GroupJoin(inner, e => e.name, e => e.name, (Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec>)null, new AnagramEqualityComparer())); } [Fact] public void OuterNullNoComparer() { CustomerRec[] outer = null; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("outer", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec)); } [Fact] public void InnerNullNoComparer() { CustomerRec[] outer = new[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = null; Assert.Throws<ArgumentNullException>("inner", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec)); } [Fact] public void OuterKeySelectorNullNoComparer() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("outerKeySelector", () => outer.GroupJoin(inner, null, e => e.name, createJoinRec)); } [Fact] public void InnerKeySelectorNullNoComparer() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("innerKeySelector", () => outer.GroupJoin(inner, e => e.name, null, createJoinRec)); } [Fact] public void ResultSelectorNullNoComparer() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("resultSelector", () => outer.GroupJoin(inner, e => e.name, e => e.name, (Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec>)null)); } [Fact] public void OuterInnerBothSingleNullElement() { string[] outer = new string[] { null }; string[] inner = new string[] { null }; string[] expected = new string[] { null }; Assert.Equal(expected, outer.GroupJoin(inner, e => e, e => e, (x, y) => x, EqualityComparer<string>.Default)); } [Fact] public void OuterNonEmptyInnerEmpty() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 43434 }, new CustomerRec{ name = "Bob", custID = 34093 } }; OrderRec[] inner = { }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void SingleElementEachAndMatches() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 43434 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 43434, total = 25 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ 97865 }, total = new int?[]{ 25 } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void SingleElementEachAndDoesntMatch() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 43434 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 49434, total = 25 } }; JoinRec[] expected = new JoinRec[] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void SelectorsReturnNull() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = null }, new CustomerRec{ name = "Bob", custID = null } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = null, total = 25 }, new OrderRec{ orderID = 34390, custID = null, total = 19 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void InnerSameKeyMoreThanOneElementAndMatches() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 1234, total = 25 }, new OrderRec{ orderID = 34390, custID = 1234, total = 19 }, new OrderRec{ orderID = 34390, custID = 9865, total = 19 } }; JoinRec[] expected = new [] { new JoinRec { name = "Tim", orderID = new int?[]{ 97865, 34390 }, total = new int?[] { 25, 19 } }, new JoinRec { name = "Bob", orderID = new int?[]{ 34390 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void OuterSameKeyMoreThanOneElementAndMatches() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9865 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 1234, total = 25 }, new OrderRec{ orderID = 34390, custID = 9865, total = 19 } }; JoinRec[] expected = new [] { new JoinRec { name = "Tim", orderID = new int?[]{ 97865 }, total = new int?[]{ 25 } }, new JoinRec { name = "Bob", orderID = new int?[]{ 34390 }, total = new int?[]{ 19 } }, new JoinRec { name = "Robert", orderID = new int?[]{ 34390 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void NoMatches() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 2334, total = 25 }, new OrderRec{ orderID = 34390, custID = 9065, total = 19 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Robert", orderID = new int?[]{ }, total = new int?[]{ } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void NullComparer() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new [] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Robert", orderID = new int?[]{ 93483 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, null)); } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).GroupJoin(Enumerable.Empty<int>(), i => i, i => i, (o, i) => i); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<IEnumerable<int>>; Assert.False(en != null && en.MoveNext()); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Runtime.Serialization; using System.Text; using System.Xml; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests { [TestFixture] public class JsonTextWriterTest : TestFixtureBase { [Test] public void BufferTest() { JsonTextReaderTest.FakeArrayPool arrayPool = new JsonTextReaderTest.FakeArrayPool(); string longString = new string('A', 2000); string longEscapedString = "Hello!" + new string('!', 50) + new string('\n', 1000) + "Good bye!"; string longerEscapedString = "Hello!" + new string('!', 2000) + new string('\n', 1000) + "Good bye!"; for (int i = 0; i < 1000; i++) { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.ArrayPool = arrayPool; writer.WriteStartObject(); writer.WritePropertyName("Prop1"); writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)); writer.WritePropertyName("Prop2"); writer.WriteValue(longString); writer.WritePropertyName("Prop3"); writer.WriteValue(longEscapedString); writer.WritePropertyName("Prop4"); writer.WriteValue(longerEscapedString); writer.WriteEndObject(); } if ((i + 1) % 100 == 0) { Console.WriteLine("Allocated buffers: " + arrayPool.FreeArrays.Count); } } Assert.AreEqual(0, arrayPool.UsedArrays.Count); Assert.AreEqual(3, arrayPool.FreeArrays.Count); } [Test] public void BufferTest_WithError() { JsonTextReaderTest.FakeArrayPool arrayPool = new JsonTextReaderTest.FakeArrayPool(); StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); try { // dispose will free used buffers using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.ArrayPool = arrayPool; writer.WriteStartObject(); writer.WritePropertyName("Prop1"); writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)); writer.WritePropertyName("Prop2"); writer.WriteValue("This is an escaped \n string!"); writer.WriteValue("Error!"); } Assert.Fail(); } catch { } Assert.AreEqual(0, arrayPool.UsedArrays.Count); Assert.AreEqual(1, arrayPool.FreeArrays.Count); } [Test] public void NewLine() { MemoryStream ms = new MemoryStream(); using (var streamWriter = new StreamWriter(ms, new UTF8Encoding(false)) { NewLine = "\n" }) using (var jsonWriter = new JsonTextWriter(streamWriter) { CloseOutput = true, Indentation = 2, Formatting = Formatting.Indented }) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("prop"); jsonWriter.WriteValue(true); jsonWriter.WriteEndObject(); } byte[] data = ms.ToArray(); string json = Encoding.UTF8.GetString(data, 0, data.Length); Assert.AreEqual(@"{" + '\n' + @" ""prop"": true" + '\n' + "}", json); } [Test] public void QuoteNameAndStrings() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonTextWriter writer = new JsonTextWriter(sw) { QuoteName = false }; writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("value"); writer.WriteEndObject(); writer.Flush(); Assert.AreEqual(@"{name:""value""}", sb.ToString()); } [Test] public void CloseOutput() { MemoryStream ms = new MemoryStream(); JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms)); Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsFalse(ms.CanRead); ms = new MemoryStream(); writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false }; Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsTrue(ms.CanRead); } #if !(PORTABLE) [Test] public void WriteIConvertable() { var sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(new ConvertibleInt(1)); Assert.AreEqual("1", sw.ToString()); } #endif [Test] public void ValueFormatting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue((string)null); jsonWriter.WriteValue((object)null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteEndArray(); } string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void NullableValueFormatting() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue((char?)null); jsonWriter.WriteValue((char?)'c'); jsonWriter.WriteValue((bool?)null); jsonWriter.WriteValue((bool?)true); jsonWriter.WriteValue((byte?)null); jsonWriter.WriteValue((byte?)1); jsonWriter.WriteValue((sbyte?)null); jsonWriter.WriteValue((sbyte?)1); jsonWriter.WriteValue((short?)null); jsonWriter.WriteValue((short?)1); jsonWriter.WriteValue((ushort?)null); jsonWriter.WriteValue((ushort?)1); jsonWriter.WriteValue((int?)null); jsonWriter.WriteValue((int?)1); jsonWriter.WriteValue((uint?)null); jsonWriter.WriteValue((uint?)1); jsonWriter.WriteValue((long?)null); jsonWriter.WriteValue((long?)1); jsonWriter.WriteValue((ulong?)null); jsonWriter.WriteValue((ulong?)1); jsonWriter.WriteValue((double?)null); jsonWriter.WriteValue((double?)1.1); jsonWriter.WriteValue((float?)null); jsonWriter.WriteValue((float?)1.1); jsonWriter.WriteValue((decimal?)null); jsonWriter.WriteValue((decimal?)1.1m); jsonWriter.WriteValue((DateTime?)null); jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc)); #if !NET20 jsonWriter.WriteValue((DateTimeOffset?)null); jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero)); #endif jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected; #if !NET20 expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]"; #else expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]"; #endif Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithNullable() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { char? value = 'c'; jsonWriter.WriteStartArray(); jsonWriter.WriteValue((object)value); jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected = @"[""c""]"; Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithUnsupportedValue() { ExceptionAssert.Throws<JsonWriterException>(() => { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(new Version(1, 1, 1, 1)); jsonWriter.WriteEndArray(); } }, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''."); } [Test] public void StringEscaping() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(@"""These pretzels are making me thirsty!"""); jsonWriter.WriteValue("Jeff's house was burninated."); jsonWriter.WriteValue("1. You don't talk about fight club.\r\n2. You don't talk about fight club."); jsonWriter.WriteValue("35% of\t statistics\n are made\r up."); jsonWriter.WriteEndArray(); } string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteEnd() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void CloseWithRemainingContent() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.Close(); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Indenting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } // { // "CPU": "Intel", // "PSU": "500W", // "Drives": [ // "DVD read/writer" // /*(broken)*/, // "500 gigabyte hard drive", // "200 gigabype hard drive" // ] // } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void State() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); jsonWriter.WriteStartObject(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); jsonWriter.WritePropertyName("CPU"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WriteValue("Intel"); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WritePropertyName("Drives"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteStartArray(); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual("Drives[0]", jsonWriter.Path); jsonWriter.WriteEnd(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); } } [Test] public void FloatingPointNonFiniteNumbers_Symbol() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ NaN, Infinity, -Infinity, NaN, Infinity, -Infinity ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_Zero() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue((double?)double.NaN); jsonWriter.WriteValue((double?)double.PositiveInfinity); jsonWriter.WriteValue((double?)double.NegativeInfinity); jsonWriter.WriteValue((float?)float.NaN); jsonWriter.WriteValue((float?)float.PositiveInfinity); jsonWriter.WriteValue((float?)float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, null, null, null, null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_String() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ ""NaN"", ""Infinity"", ""-Infinity"", ""NaN"", ""Infinity"", ""-Infinity"" ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_QuoteChar() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.QuoteChar = '\''; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 'NaN', 'Infinity', '-Infinity', 'NaN', 'Infinity', '-Infinity' ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInStart() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteRaw("[1,2,3,4,5]"); jsonWriter.WriteWhitespace(" "); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndArray(); } string expected = @"[1,2,3,4,5] [ NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } string expected = @"[ NaN,[1,2,3,4,5],[1,2,3,4,5], NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInObject() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]"); jsonWriter.WriteEnd(); } string expected = @"{""PropertyName"":[1,2,3,4,5]}"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteToken() { JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]")); reader.Read(); reader.Read(); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteToken(reader); Assert.AreEqual("1", sw.ToString()); } [Test] public void WriteRawValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { int i = 0; string rawJson = "[1,2]"; jsonWriter.WriteStartObject(); while (i < 3) { jsonWriter.WritePropertyName("d" + i); jsonWriter.WriteRawValue(rawJson); i++; } jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString()); } [Test] public void WriteObjectNestedInConstructor() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("con"); jsonWriter.WriteStartConstructor("Ext.data.JsonStore"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("aa"); jsonWriter.WriteValue("aa"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndConstructor(); jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString()); } [Test] public void WriteFloatingPointNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteValue(0f); jsonWriter.WriteValue(0.1); jsonWriter.WriteValue(1.0); jsonWriter.WriteValue(1.000001); jsonWriter.WriteValue(0.000001); jsonWriter.WriteValue(double.Epsilon); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.MaxValue); jsonWriter.WriteValue(double.MinValue); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); } [Test] public void WriteIntegerNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented }) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(int.MaxValue); jsonWriter.WriteValue(int.MinValue); jsonWriter.WriteValue(0); jsonWriter.WriteValue(-0); jsonWriter.WriteValue(9L); jsonWriter.WriteValue(9UL); jsonWriter.WriteValue(long.MaxValue); jsonWriter.WriteValue(long.MinValue); jsonWriter.WriteValue(ulong.MaxValue); jsonWriter.WriteValue(ulong.MinValue); jsonWriter.WriteEndArray(); } Console.WriteLine(sb.ToString()); StringAssert.AreEqual(@"[ 2147483647, -2147483648, 0, 0, 9, 9, 9223372036854775807, -9223372036854775808, 18446744073709551615, 0 ]", sb.ToString()); } [Test] public void WriteTokenDirect() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); jsonWriter.WriteToken(JsonToken.Integer, 1); jsonWriter.WriteToken(JsonToken.StartObject); jsonWriter.WriteToken(JsonToken.PropertyName, "string"); jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue); jsonWriter.WriteToken(JsonToken.EndObject); jsonWriter.WriteToken(JsonToken.EndArray); } Assert.AreEqual(@"[1,{""string"":2147483647}]", sb.ToString()); } [Test] public void WriteTokenDirect_BadValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); ExceptionAssert.Throws<FormatException>(() => { jsonWriter.WriteToken(JsonToken.Integer, "three"); }, "Input string was not in a correct format."); ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(JsonToken.Integer); }, @"Value cannot be null. Parameter name: value"); } } [Test] public void WriteTokenNullCheck() { using (JsonWriter jsonWriter = new JsonTextWriter(new StringWriter())) { ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(null); }); ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(null, true); }); } } [Test] public void TokenTypeOutOfRange() { using (JsonWriter jsonWriter = new JsonTextWriter(new StringWriter())) { ArgumentOutOfRangeException ex = ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => jsonWriter.WriteToken((JsonToken)int.MinValue)); Assert.AreEqual("token", ex.ParamName); ex = ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => jsonWriter.WriteToken((JsonToken)int.MinValue, "test")); Assert.AreEqual("token", ex.ParamName); } } [Test] public void BadWriteEndArray() { ExceptionAssert.Throws<JsonWriterException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray(); } }, "No token to close. Path ''."); } [Test] public void InvalidQuoteChar() { ExceptionAssert.Throws<ArgumentException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.QuoteChar = '*'; } }, @"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); } [Test] public void Indentation() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.Indentation = 5; Assert.AreEqual(5, jsonWriter.Indentation); jsonWriter.IndentChar = '_'; Assert.AreEqual('_', jsonWriter.IndentChar); jsonWriter.QuoteName = true; Assert.AreEqual(true, jsonWriter.QuoteName); jsonWriter.QuoteChar = '\''; Assert.AreEqual('\'', jsonWriter.QuoteChar); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("propertyName"); jsonWriter.WriteValue(double.NaN); jsonWriter.IndentChar = '?'; Assert.AreEqual('?', jsonWriter.IndentChar); jsonWriter.Indentation = 6; Assert.AreEqual(6, jsonWriter.Indentation); jsonWriter.WritePropertyName("prop2"); jsonWriter.WriteValue(123); jsonWriter.WriteEndObject(); } string expected = @"{ _____'propertyName': NaN, ??????'prop2': 123 }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteSingleBytes() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteValue(data); } string expected = @"""SGVsbG8gd29ybGQu"""; string result = sb.ToString(); Assert.AreEqual(expected, result); byte[] d2 = Convert.FromBase64String(result.Trim('"')); Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length)); } [Test] public void WriteBytesInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(data); jsonWriter.WriteValue(data); jsonWriter.WriteValue((object)data); jsonWriter.WriteValue((byte[])null); jsonWriter.WriteValue((Uri)null); jsonWriter.WriteEndArray(); } string expected = @"[ ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Path() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartArray(); Assert.AreEqual("", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[0]", writer.Path); writer.WritePropertyName("Property1"); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteValue(1); Assert.AreEqual("[0].Property1[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0][0]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[0]", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[1]", writer.Path); writer.WritePropertyName("Property2"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteStartConstructor("Constructor1"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteNull(); Assert.AreEqual("[1].Property2[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteValue(1); Assert.AreEqual("[1].Property2[1][0]", writer.Path); writer.WriteEnd(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[1]", writer.Path); writer.WriteEndArray(); Assert.AreEqual("", writer.Path); } StringAssert.AreEqual(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]", sb.ToString()); } [Test] public void BuildStateArray() { JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray(); var valueStates = JsonWriter.StateArrayTempate[7]; foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) { switch (valueToken) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states."); break; } } } [Test] public void DateTimeZoneHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc }; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString()); } [Test] public void HtmlStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeHtml }; string script = @"<script type=""text/javascript"">alert('hi');</script>"; writer.WriteValue(script); string json = sw.ToString(); Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(script, reader.ReadAsString()); } [Test] public void NonAsciiStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }; string unicode = "\u5f20"; writer.WriteValue(unicode); string json = sw.ToString(); Assert.AreEqual(8, json.Length); Assert.AreEqual(@"""\u5f20""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(unicode, reader.ReadAsString()); sw = new StringWriter(); writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.Default }; writer.WriteValue(unicode); json = sw.ToString(); Assert.AreEqual(3, json.Length); Assert.AreEqual("\"\u5f20\"", json); } [Test] public void WriteEndOnProperty() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); writer.WriteEnd(); Assert.AreEqual("{'Blah':null}", sw.ToString()); } #if !NET20 [Test] public void QuoteChar() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatString = "yyyy gg"; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteValue(new byte[] { 1, 2, 3 }); writer.WriteValue(TimeSpan.Zero); writer.WriteValue(new Uri("http://www.google.com/")); writer.WriteValue(Guid.Empty); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000-01-01T01:01:01Z', '2000-01-01T01:01:01+00:00', '\/Date(946688461000)\/', '\/Date(946688461000+0000)\/', '2000 A.D.', '2000 A.D.', 'AQID', '00:00:00', 'http://www.google.com/', '00000000-0000-0000-0000-000000000000' ]", sw.ToString()); } [Test] public void Culture() { CultureInfo culture = new CultureInfo("en-NZ"); culture.DateTimeFormat.AMDesignator = "a.m."; culture.DateTimeFormat.PMDesignator = "p.m."; StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.DateFormatString = "yyyy tt"; writer.Culture = culture; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000 a.m.', '2000 a.m.' ]", sw.ToString()); } #endif [Test] public void CompareNewStringEscapingWithOld() { char c = (char)0; do { StringWriter swNew = new StringWriter(); char[] buffer = null; JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); StringWriter swOld = new StringWriter(); WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true); string newText = swNew.ToString(); string oldText = swOld.ToString(); if (newText != oldText) { throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText)); } c++; } while (c != char.MaxValue); } private const string EscapedUnicodeText = "!"; private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (s != null) { char[] chars = null; char[] unicodeBuffer = null; int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != delimiter) { continue; } string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; case '\'': // this charater is being used as the delimiter escapedValue = @"\'"; break; case '"': // this charater is being used as the delimiter escapedValue = "\\\""; break; default: if (c <= '\u001f') { if (unicodeBuffer == null) { unicodeBuffer = new char[6]; } StringUtils.ToCharAsUnicode(c, unicodeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } if (i > lastWritePosition) { if (chars == null) { chars = s.ToCharArray(); } // write unchanged chars before writing escaped text writer.Write(chars, lastWritePosition, i - lastWritePosition); } lastWritePosition = i + 1; if (!string.Equals(escapedValue, EscapedUnicodeText)) { writer.Write(escapedValue); } else { writer.Write(unicodeBuffer); } } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { if (chars == null) { chars = s.ToCharArray(); } // write remaining text writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } [Test] public void CustomJsonTextWriterTests() { StringWriter sw = new StringWriter(); CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented }; writer.WriteStartObject(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WritePropertyName("Property1"); Assert.AreEqual(WriteState.Property, writer.WriteState); Assert.AreEqual("Property1", writer.Path); writer.WriteNull(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WriteEndObject(); Assert.AreEqual(WriteState.Start, writer.WriteState); StringAssert.AreEqual(@"{{{ ""1ytreporP"": NULL!!! }}}", sw.ToString()); } [Test] public void QuoteDictionaryNames() { var d = new Dictionary<string, int> { { "a", 1 }, }; var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, }; var serializer = JsonSerializer.Create(jsonSerializerSettings); using (var stringWriter = new StringWriter()) { using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false }) { serializer.Serialize(writer, d); writer.Close(); } StringAssert.AreEqual(@"{ a: 1 }", stringWriter.ToString()); } } [Test] public void WriteComments() { string json = @"//comment*//*hi*/ {//comment Name://comment true//comment after true" + StringUtils.CarriageReturn + @" ,//comment after comma" + StringUtils.CarriageReturnLineFeed + @" ""ExpiryDate""://comment" + StringUtils.LineFeed + @" new " + StringUtils.LineFeed + @"Constructor (//comment null//comment ), ""Price"": 3.99, ""Sizes"": //comment [//comment ""Small""//comment ]//comment }//comment //comment 1 "; JsonTextReader r = new JsonTextReader(new StringReader(json)); StringWriter sw = new StringWriter(); JsonTextWriter w = new JsonTextWriter(sw); w.Formatting = Formatting.Indented; w.WriteToken(r, true); StringAssert.AreEqual(@"/*comment*//*hi*/*/{/*comment*/ ""Name"": /*comment*/ true/*comment after true*//*comment after comma*/, ""ExpiryDate"": /*comment*/ new Constructor( /*comment*/, null /*comment*/ ), ""Price"": 3.99, ""Sizes"": /*comment*/ [ /*comment*/ ""Small"" /*comment*/ ]/*comment*/ }/*comment *//*comment 1 */", sw.ToString()); } [Test] public void DisposeSupressesFinalization() { UnmanagedResourceFakingJsonWriter.CreateAndDispose(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.AreEqual(1, UnmanagedResourceFakingJsonWriter.DisposalCalls); } } public class CustomJsonTextWriter : JsonTextWriter { private readonly TextWriter _writer; public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter) { _writer = textWriter; } public override void WritePropertyName(string name) { WritePropertyName(name, true); } public override void WritePropertyName(string name, bool escape) { SetWriteState(JsonToken.PropertyName, name); if (QuoteName) { _writer.Write(QuoteChar); } _writer.Write(new string(name.ToCharArray().Reverse().ToArray())); if (QuoteName) { _writer.Write(QuoteChar); } _writer.Write(':'); } public override void WriteNull() { SetWriteState(JsonToken.Null, null); _writer.Write("NULL!!!"); } public override void WriteStartObject() { SetWriteState(JsonToken.StartObject, null); _writer.Write("{{{"); } public override void WriteEndObject() { SetWriteState(JsonToken.EndObject, null); } protected override void WriteEnd(JsonToken token) { if (token == JsonToken.EndObject) { _writer.Write("}}}"); } else { base.WriteEnd(token); } } } #if !(PORTABLE || NETFX_CORE) public struct ConvertibleInt : IConvertible { private readonly int _value; public ConvertibleInt(int value) { _value = value; } public TypeCode GetTypeCode() { return TypeCode.Int32; } public bool ToBoolean(IFormatProvider provider) { throw new NotImplementedException(); } public byte ToByte(IFormatProvider provider) { throw new NotImplementedException(); } public char ToChar(IFormatProvider provider) { throw new NotImplementedException(); } public DateTime ToDateTime(IFormatProvider provider) { throw new NotImplementedException(); } public decimal ToDecimal(IFormatProvider provider) { throw new NotImplementedException(); } public double ToDouble(IFormatProvider provider) { throw new NotImplementedException(); } public short ToInt16(IFormatProvider provider) { throw new NotImplementedException(); } public int ToInt32(IFormatProvider provider) { throw new NotImplementedException(); } public long ToInt64(IFormatProvider provider) { throw new NotImplementedException(); } public sbyte ToSByte(IFormatProvider provider) { throw new NotImplementedException(); } public float ToSingle(IFormatProvider provider) { throw new NotImplementedException(); } public string ToString(IFormatProvider provider) { throw new NotImplementedException(); } public object ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(int)) { return _value; } throw new Exception("Type not supported: " + conversionType.FullName); } public ushort ToUInt16(IFormatProvider provider) { throw new NotImplementedException(); } public uint ToUInt32(IFormatProvider provider) { throw new NotImplementedException(); } public ulong ToUInt64(IFormatProvider provider) { throw new NotImplementedException(); } } #endif public class UnmanagedResourceFakingJsonWriter : JsonWriter { public static int DisposalCalls; public static void CreateAndDispose() { ((IDisposable)new UnmanagedResourceFakingJsonWriter()).Dispose(); } public UnmanagedResourceFakingJsonWriter() { DisposalCalls = 0; } protected override void Dispose(bool disposing) { base.Dispose(disposing); ++DisposalCalls; } ~UnmanagedResourceFakingJsonWriter() { Dispose(false); } public override void Flush() { throw new NotImplementedException(); } } }
// // PkzipClassic encryption // // Copyright 2004 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // // ************************************************************************* // // Name: PkzipClassic.cs // // Created: 19-02-2008 SharedCache.com, rschuetz // Modified: 19-02-2008 SharedCache.com, rschuetz : Creation // ************************************************************************* using System; using System.Security.Cryptography; using MergeSystem.Indexus.WinServiceCommon.SharpZipLib.Checksum; namespace MergeSystem.Indexus.WinServiceCommon.SharpZipLib.Encryption { /// <summary> /// PkzipClassic embodies the classic or original encryption facilities used in Pkzip archives. /// While it has been superceded by more recent and more powerful algorithms, its still in use and /// is viable for preventing casual snooping /// </summary> public abstract class PkzipClassic : SymmetricAlgorithm { /// <summary> /// Generates new encryption keys based on given seed /// </summary> /// <param name="seed">The seed value to initialise keys with.</param> /// <returns>A new key value.</returns> static public byte[] GenerateKeys(byte[] seed) { if (seed == null) { throw new ArgumentNullException("seed"); } if (seed.Length == 0) { throw new ArgumentException("Length is zero", "seed"); } uint[] newKeys = new uint[] { 0x12345678, 0x23456789, 0x34567890 }; for (int i = 0; i < seed.Length; ++i) { newKeys[0] = Crc32.ComputeCrc32(newKeys[0], seed[i]); newKeys[1] = newKeys[1] + (byte)newKeys[0]; newKeys[1] = newKeys[1] * 134775813 + 1; newKeys[2] = Crc32.ComputeCrc32(newKeys[2], (byte)(newKeys[1] >> 24)); } byte[] result = new byte[12]; result[0] = (byte)(newKeys[0] & 0xff); result[1] = (byte)((newKeys[0] >> 8) & 0xff); result[2] = (byte)((newKeys[0] >> 16) & 0xff); result[3] = (byte)((newKeys[0] >> 24) & 0xff); result[4] = (byte)(newKeys[1] & 0xff); result[5] = (byte)((newKeys[1] >> 8) & 0xff); result[6] = (byte)((newKeys[1] >> 16) & 0xff); result[7] = (byte)((newKeys[1] >> 24) & 0xff); result[8] = (byte)(newKeys[2] & 0xff); result[9] = (byte)((newKeys[2] >> 8) & 0xff); result[10] = (byte)((newKeys[2] >> 16) & 0xff); result[11] = (byte)((newKeys[2] >> 24) & 0xff); return result; } } /// <summary> /// PkzipClassicCryptoBase provides the low level facilities for encryption /// and decryption using the PkzipClassic algorithm. /// </summary> class PkzipClassicCryptoBase { /// <summary> /// Transform a single byte /// </summary> /// <returns> /// The transformed value /// </returns> protected byte TransformByte() { uint temp = ((keys[2] & 0xFFFF) | 2); return (byte)((temp * (temp ^ 1)) >> 8); } /// <summary> /// Set the key schedule for encryption/decryption. /// </summary> /// <param name="keyData">The data use to set the keys from.</param> protected void SetKeys(byte[] keyData) { if (keyData == null) { throw new ArgumentNullException("keyData"); } if (keyData.Length != 12) { throw new InvalidOperationException("Key length is not valid"); } keys = new uint[3]; keys[0] = (uint)((keyData[3] << 24) | (keyData[2] << 16) | (keyData[1] << 8) | keyData[0]); keys[1] = (uint)((keyData[7] << 24) | (keyData[6] << 16) | (keyData[5] << 8) | keyData[4]); keys[2] = (uint)((keyData[11] << 24) | (keyData[10] << 16) | (keyData[9] << 8) | keyData[8]); } /// <summary> /// Update encryption keys /// </summary> protected void UpdateKeys(byte ch) { keys[0] = Crc32.ComputeCrc32(keys[0], ch); keys[1] = keys[1] + (byte)keys[0]; keys[1] = keys[1] * 134775813 + 1; keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24)); } /// <summary> /// Reset the internal state. /// </summary> protected void Reset() { keys[0] = 0; keys[1] = 0; keys[2] = 0; } #region Instance Fields uint[] keys; #endregion } /// <summary> /// PkzipClassic CryptoTransform for encryption. /// </summary> class PkzipClassicEncryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform { /// <summary> /// Initialise a new instance of <see cref="PkzipClassicEncryptCryptoTransform"></see> /// </summary> /// <param name="keyBlock">The key block to use.</param> internal PkzipClassicEncryptCryptoTransform(byte[] keyBlock) { SetKeys(keyBlock); } #region ICryptoTransform Members /// <summary> /// Transforms the specified region of the specified byte array. /// </summary> /// <param name="inputBuffer">The input for which to compute the transform.</param> /// <param name="inputOffset">The offset into the byte array from which to begin using data.</param> /// <param name="inputCount">The number of bytes in the byte array to use as data.</param> /// <returns>The computed transform.</returns> public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { byte[] result = new byte[inputCount]; TransformBlock(inputBuffer, inputOffset, inputCount, result, 0); return result; } /// <summary> /// Transforms the specified region of the input byte array and copies /// the resulting transform to the specified region of the output byte array. /// </summary> /// <param name="inputBuffer">The input for which to compute the transform.</param> /// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param> /// <param name="inputCount">The number of bytes in the input byte array to use as data.</param> /// <param name="outputBuffer">The output to which to write the transform.</param> /// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param> /// <returns>The number of bytes written.</returns> public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { for (int i = inputOffset; i < inputOffset + inputCount; ++i) { byte oldbyte = inputBuffer[i]; outputBuffer[outputOffset++] = (byte)(inputBuffer[i] ^ TransformByte()); UpdateKeys(oldbyte); } return inputCount; } /// <summary> /// Gets a value indicating whether the current transform can be reused. /// </summary> public bool CanReuseTransform { get { return true; } } /// <summary> /// Gets the size of the input data blocks in bytes. /// </summary> public int InputBlockSize { get { return 1; } } /// <summary> /// Gets the size of the output data blocks in bytes. /// </summary> public int OutputBlockSize { get { return 1; } } /// <summary> /// Gets a value indicating whether multiple blocks can be transformed. /// </summary> public bool CanTransformMultipleBlocks { get { return true; } } #endregion #region IDisposable Members /// <summary> /// Cleanup internal state. /// </summary> public void Dispose() { Reset(); } #endregion } /// <summary> /// PkzipClassic CryptoTransform for decryption. /// </summary> class PkzipClassicDecryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform { /// <summary> /// Initialise a new instance of <see cref="PkzipClassicDecryptCryptoTransform"></see>. /// </summary> /// <param name="keyBlock">The key block to decrypt with.</param> internal PkzipClassicDecryptCryptoTransform(byte[] keyBlock) { SetKeys(keyBlock); } #region ICryptoTransform Members /// <summary> /// Transforms the specified region of the specified byte array. /// </summary> /// <param name="inputBuffer">The input for which to compute the transform.</param> /// <param name="inputOffset">The offset into the byte array from which to begin using data.</param> /// <param name="inputCount">The number of bytes in the byte array to use as data.</param> /// <returns>The computed transform.</returns> public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { byte[] result = new byte[inputCount]; TransformBlock(inputBuffer, inputOffset, inputCount, result, 0); return result; } /// <summary> /// Transforms the specified region of the input byte array and copies /// the resulting transform to the specified region of the output byte array. /// </summary> /// <param name="inputBuffer">The input for which to compute the transform.</param> /// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param> /// <param name="inputCount">The number of bytes in the input byte array to use as data.</param> /// <param name="outputBuffer">The output to which to write the transform.</param> /// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param> /// <returns>The number of bytes written.</returns> public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { for (int i = inputOffset; i < inputOffset + inputCount; ++i) { byte newByte = (byte)(inputBuffer[i] ^ TransformByte()); outputBuffer[outputOffset++] = newByte; UpdateKeys(newByte); } return inputCount; } /// <summary> /// Gets a value indicating whether the current transform can be reused. /// </summary> public bool CanReuseTransform { get { return true; } } /// <summary> /// Gets the size of the input data blocks in bytes. /// </summary> public int InputBlockSize { get { return 1; } } /// <summary> /// Gets the size of the output data blocks in bytes. /// </summary> public int OutputBlockSize { get { return 1; } } /// <summary> /// Gets a value indicating whether multiple blocks can be transformed. /// </summary> public bool CanTransformMultipleBlocks { get { return true; } } #endregion #region IDisposable Members /// <summary> /// Cleanup internal state. /// </summary> public void Dispose() { Reset(); } #endregion } /// <summary> /// Defines a wrapper object to access the Pkzip algorithm. /// This class cannot be inherited. /// </summary> public sealed class PkzipClassicManaged : PkzipClassic { /// <summary> /// Get / set the applicable block size in bits. /// </summary> /// <remarks>The only valid block size is 8.</remarks> public override int BlockSize { get { return 8; } set { if (value != 8) { throw new CryptographicException("Block size is invalid"); } } } /// <summary> /// Get an array of legal <see cref="KeySizes">key sizes.</see> /// </summary> public override KeySizes[] LegalKeySizes { get { KeySizes[] keySizes = new KeySizes[1]; keySizes[0] = new KeySizes(12 * 8, 12 * 8, 0); return keySizes; } } /// <summary> /// Generate an initial vector. /// </summary> public override void GenerateIV() { // Do nothing. } /// <summary> /// Get an array of legal <see cref="KeySizes">block sizes</see>. /// </summary> public override KeySizes[] LegalBlockSizes { get { KeySizes[] keySizes = new KeySizes[1]; keySizes[0] = new KeySizes(1 * 8, 1 * 8, 0); return keySizes; } } /// <summary> /// Get / set the key value applicable. /// </summary> public override byte[] Key { get { if (key_ == null) { GenerateKey(); } return (byte[])key_.Clone(); } set { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length != 12) { throw new CryptographicException("Key size is illegal"); } key_ = (byte[])value.Clone(); } } /// <summary> /// Generate a new random key. /// </summary> public override void GenerateKey() { key_ = new byte[12]; Random rnd = new Random(); rnd.NextBytes(key_); } /// <summary> /// Create an encryptor. /// </summary> /// <param name="rgbKey">The key to use for this encryptor.</param> /// <param name="rgbIV">Initialisation vector for the new encryptor.</param> /// <returns>Returns a new PkzipClassic encryptor</returns> public override ICryptoTransform CreateEncryptor( byte[] rgbKey, byte[] rgbIV) { key_ = rgbKey; return new PkzipClassicEncryptCryptoTransform(Key); } /// <summary> /// Create a decryptor. /// </summary> /// <param name="rgbKey">Keys to use for this new decryptor.</param> /// <param name="rgbIV">Initialisation vector for the new decryptor.</param> /// <returns>Returns a new decryptor.</returns> public override ICryptoTransform CreateDecryptor( byte[] rgbKey, byte[] rgbIV) { key_ = rgbKey; return new PkzipClassicDecryptCryptoTransform(Key); } #region Instance Fields byte[] key_; #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public static class RemoveDeadCode { // // Helper Methods // public static bool Execute( ControlFlowGraphStateForCodeTransformation cfg , bool fLookForDeadAssignments ) { cfg.TraceToFile( "RemoveDeadCode" ); using(new PerformanceCounters.ContextualTiming( cfg, "RemoveDeadCode" )) { bool fModified = false; while(true) { VariableExpression[] vars = cfg.DataFlow_SpanningTree_Variables; VariableExpression.Property[] varProp = cfg.DataFlow_PropertiesOfVariables; Operator[] operators = cfg.DataFlow_SpanningTree_Operators; Operator[][] defChains = cfg.DataFlow_DefinitionChains; Operator[][] useChains = cfg.DataFlow_UseChains; Abstractions.Platform pa = cfg.TypeSystem.PlatformAbstraction; Abstractions.RegisterDescriptor[] registers = pa.GetRegisters(); bool[] unneededVars = new bool[vars.Length]; bool fDone = true; for(int i = 0; i < vars.Length; i++) { VariableExpression.Property prop = varProp[i]; if((prop & VariableExpression.Property.PhysicalRegister) != 0) { PhysicalRegisterExpression reg = (PhysicalRegisterExpression)vars[i].AliasedVariable; if(registers[ reg.Number ].IsSpecial) { continue; } } { VariableExpression var = vars[i]; bool fKeep = false; if(ShouldKeep( cfg, var, defChains, useChains )) { fKeep = true; } else if(var.AliasedVariable is StackLocationExpression) { // // Check if the variable is a fragment of an aggregate type, keep it around if any of the fragments are used. // StackLocationExpression stackVar = (StackLocationExpression)var.AliasedVariable; foreach(VariableExpression var2 in vars) { StackLocationExpression stackVar2 = var2.AliasedVariable as StackLocationExpression; if(stackVar2 != null && stackVar.SourceVariable == stackVar2.SourceVariable) { if(useChains[var2.SpanningTreeIndex].Length > 0) { fKeep = true; break; } } } } if(fKeep == false) { CHECKS.ASSERT( (prop & VariableExpression.Property.AddressTaken) == 0, "Variable {0} cannot be unused and its address taken", vars[i] ); unneededVars[i] = true; } } } // // Only remove an operator if ALL the results are dead. // foreach(var op in operators) { if(op.HasAnnotation< DontRemoveAnnotation >() == false) { bool fDelete = false; foreach(var lhs in op.Results) { if(unneededVars[lhs.SpanningTreeIndex]) { fDelete = true; } else { fDelete = false; break; } } if(fDelete) { op.Delete(); fDone = false; } } } // // Refresh the u/d chains. // if(fDone == false) { varProp = cfg.DataFlow_PropertiesOfVariables; operators = cfg.DataFlow_SpanningTree_Operators; defChains = cfg.DataFlow_DefinitionChains; useChains = cfg.DataFlow_UseChains; } // // Get rid of all the operators that do nothing, evaluate constant operations, etc. // BitVector[] livenessMap = fLookForDeadAssignments ? cfg.DataFlow_LivenessAtOperator : null; // It's indexed as [<operator index>][<variable index>] foreach(Operator op in operators) { if(op.PerformsNoActions) { op.Delete(); fDone = false; continue; } op.EnsureConstantToTheRight(); if(op.Simplify( defChains, useChains, varProp )) { fDone = false; continue; } if(fLookForDeadAssignments) { // // All the variables have to be initialized with their default values, // but most of the times these assignments are overwritten by other assignments. // Look for these pattern and remove the duplicate code. // if(op is SingleAssignmentOperator && op.HasAnnotation< InvalidationAnnotation >() == false) { int idxVar = op.FirstResult.SpanningTreeIndex; if((varProp[idxVar] & VariableExpression.Property.AddressTaken) == 0) { int idxOp = op.SpanningTreeIndex; if(livenessMap[idxOp+1][idxVar] == false) { // // The variable is dead at the next operator, thus it's a useless assignment. // op.Delete(); fDone = false; continue; } } } } } if(fDone) { break; } fModified = true; } return fModified; } } private static bool ShouldKeep( ControlFlowGraphStateForCodeTransformation cfg , VariableExpression var , Operator[][] defChains , Operator[][] useChains ) { if(ShouldKeep( var, defChains, useChains )) { return true; } Expression[] fragments = cfg.GetFragmentsForExpression( var ); if(fragments != null) { foreach(Expression ex in fragments) { if(ShouldKeep( ex, defChains, useChains )) { return true; } } } return false; } private static bool ShouldKeep( Expression var , Operator[][] defChains , Operator[][] useChains ) { if(useChains[var.SpanningTreeIndex].Length > 0) { return true; } foreach(Operator op in defChains[var.SpanningTreeIndex]) { if(op.ShouldNotBeRemoved || op.MayMutateExistingStorage || op.MayThrow ) { return true; } foreach(var an in op.FilterAnnotations< InvalidationAnnotation >()) { if(useChains[an.Target.SpanningTreeIndex].Length > 0) { return true; } } } return false; } } }
/* * Copyright 2013 Splunk, 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. */ namespace Splunk.Client.AcceptanceTests { using Splunk.Client; using Splunk.Client.Helpers; using System; using System.Linq; using System.Threading.Tasks; using Xunit; /// <summary> /// Application tests /// </summary> public class ApplicationTest { /// <summary> /// The app tests /// </summary> [Trait("acceptance-test", "Splunk.Client.Application")] [MockContext] [Fact] public async Task Application() { using (var service = await SdkHelper.CreateService()) { ApplicationCollection apps = service.Applications; await apps.GetAllAsync(); foreach (Application app in apps) { await CheckApplication(app); } for (int i = 0; i < apps.Count; i++) { await CheckApplication(apps[i]); } if (await service.Applications.RemoveAsync("sdk-tests")) { await service.Server.RestartAsync(2 * 60 * 1000); await service.LogOnAsync(); } ApplicationAttributes attributes = new ApplicationAttributes { ApplicationAuthor = "me", Description = "this is a description", Label = "SDKTEST", Visible = false }; var testApp = await service.Applications.CreateAsync("sdk-tests", "barebones", attributes); testApp = await service.Applications.GetAsync("sdk-tests"); Assert.Equal("SDKTEST", testApp.Label); Assert.Equal("me", testApp.ApplicationAuthor); Assert.Equal("nobody", testApp.Author); Assert.False(testApp.Configured); Assert.False(testApp.Visible); Assert.DoesNotThrow(() => { bool p = testApp.CheckForUpdates; }); attributes = new ApplicationAttributes { ApplicationAuthor = "not me", Description = "new description", Label = "new label", Visible = false, Version = "1.5" }; //// Update the application await testApp.UpdateAsync(attributes, true); await testApp.GetAsync(); Assert.Equal("not me", testApp.ApplicationAuthor); Assert.Equal("nobody", testApp.Author); Assert.Equal("new description", testApp.Description); Assert.Equal("new label", testApp.Label); Assert.Equal("1.5", testApp.Version); Assert.False(testApp.Visible); ApplicationUpdateInfo updateInfo = await testApp.GetUpdateInfoAsync(); Assert.NotNull(updateInfo.Eai.Acl); //// Package the application ApplicationArchiveInfo archiveInfo = await testApp.PackageAsync(); Assert.Equal("Package", archiveInfo.Title); Assert.NotEqual(DateTime.MinValue, archiveInfo.Updated); Assert.DoesNotThrow(() => { string p = archiveInfo.ApplicationName; }); Assert.True(archiveInfo.ApplicationName.Length > 0); Assert.DoesNotThrow(() => { Eai p = archiveInfo.Eai; }); Assert.NotNull(archiveInfo.Eai); Assert.NotNull(archiveInfo.Eai.Acl); Assert.DoesNotThrow(() => { string p = archiveInfo.Path; }); Assert.True(archiveInfo.Path.Length > 0); Assert.DoesNotThrow(() => { bool p = archiveInfo.Refresh; }); Assert.DoesNotThrow(() => { Uri p = archiveInfo.Uri; }); Assert.True(archiveInfo.Uri.AbsolutePath.Length > 0); Assert.True(await service.Applications.RemoveAsync("sdk-tests")); await service.Server.RestartAsync(2 * 60 * 1000); } } #region Privates/internals internal async Task CheckApplication(Application app) { ApplicationSetupInfo setupInfo = null; try { setupInfo = await app.GetSetupInfoAsync(); //// TODO: Install an app which hits this code before this test runs Assert.NotNull(setupInfo.Eai); Assert.DoesNotThrow(() => { bool p = setupInfo.Refresh; }); } catch (InternalServerErrorException e) { Assert.Contains("Setup configuration file does not exist", e.Message); } ApplicationArchiveInfo archiveInfo = await app.PackageAsync(); Assert.DoesNotThrow(() => { string p = app.Author; Assert.NotNull(p); }); Assert.DoesNotThrow(() => { string p = app.ApplicationAuthor; }); Assert.DoesNotThrow(() => { bool p = app.CheckForUpdates; }); Assert.DoesNotThrow(() => { string p = app.Description; }); Assert.DoesNotThrow(() => { string p = app.Label; }); Assert.DoesNotThrow(() => { bool p = app.Refresh; }); Assert.DoesNotThrow(() => { string p = app.Version; }); Assert.DoesNotThrow(() => { bool p = app.Configured; }); Assert.DoesNotThrow(() => { bool p = app.StateChangeRequiresRestart; }); Assert.DoesNotThrow(() => { bool p = app.Visible; }); ApplicationUpdateInfo updateInfo = await app.GetUpdateInfoAsync(); Assert.NotNull(updateInfo.Eai); if (updateInfo.Update != null) { var update = updateInfo.Update; Assert.DoesNotThrow(() => { string p = updateInfo.Update.ApplicationName; }); Assert.DoesNotThrow(() => { Uri p = updateInfo.Update.ApplicationUri; }); Assert.DoesNotThrow(() => { string p = updateInfo.Update.ApplicationName; }); Assert.DoesNotThrow(() => { string p = updateInfo.Update.ChecksumType; }); Assert.DoesNotThrow(() => { string p = updateInfo.Update.Homepage; }); Assert.DoesNotThrow(() => { bool p = updateInfo.Update.ImplicitIdRequired; }); Assert.DoesNotThrow(() => { long p = updateInfo.Update.Size; }); Assert.DoesNotThrow(() => { string p = updateInfo.Update.Version; }); } Assert.DoesNotThrow(() => { DateTime p = updateInfo.Updated; }); } #endregion } }
using System.Management.Automation; using WebApiWorkItem = Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItem; using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models; using Microsoft.VisualStudio.Services.WebApi.Patch.Json; using Microsoft.VisualStudio.Services.WebApi.Patch; using TfsCmdlets.Models; using Microsoft.TeamFoundation.WorkItemTracking.WebApi; using TfsCmdlets.Extensions; namespace TfsCmdlets.Cmdlets.WorkItem { /// <summary> /// Moves a work item to a different team project in the same collection. /// </summary> [Cmdlet(VerbsCommon.Move, "TfsWorkItem", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)] [OutputType(typeof(WebApiWorkItem))] public class MoveWorkItem : CmdletBase { /// <summary> /// Specifies a work item. Valid values are the work item ID or an instance of /// Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItem. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] [Alias("id")] [ValidateNotNull()] public object WorkItem { get; set; } /// <summary> /// Specifies the team project where the work item will be moved to. /// </summary> [Parameter(Mandatory = true, Position = 1)] [Alias("Destination")] public object Project { get; set; } /// <summary> /// Specifies the area path in the destination project where the work item will be moved to. /// When omitted, the work item is moved to the root area path in the destination project. /// </summary> [Parameter()] public object Area { get; set; } /// <summary> /// Specifies the iteration path in the destination project where the work item will be moved to. /// When omitted, the work item is moved to the root iteration path in the destination project. /// </summary> [Parameter()] public object Iteration { get; set; } /// <summary> /// Specifies a new state for the work item in the destination project. /// When omitted, it retains the current state. /// </summary> [Parameter()] public string State { get; set; } /// <summary> /// Specifies a comment to be added to the history /// </summary> [Parameter()] public string Comment { get; set; } /// <summary> /// HELP_PARAM_COLLECTION /// </summary> [Parameter()] public object Collection { get; set; } /// <summary> /// HELP_PARAM_PASSTHRU /// </summary> [Parameter()] public SwitchParameter Passthru { get; set; } /// <summary> /// Performs execution of the command /// </summary> protected override void DoProcessRecord() { var wis = GetItems<WebApiWorkItem>(); var (tpc, targetTp) = GetCollectionAndProject(); string targetAreaPath; string targetIterationPath; if (Area != null) { var targetArea = GetItem<ClassificationNode>(new { Node = Area, StructureGroup = TreeStructureGroup.Areas }); if (targetArea == null) { if (!ShouldProcess($"Team project '{targetTp.Name}'", $"Create area path {Area}")) { return; } targetArea = NewItem<ClassificationNode>(new { Node = Area, StructureGroup = TreeStructureGroup.Areas }); } this.Log($"Moving to area {targetArea.Path}"); targetAreaPath = $"{targetTp.Name}{targetArea.RelativePath}"; } else { this.Log("Area not informed. Moving to root iteration."); targetAreaPath = targetTp.Name; } if (Iteration != null) { var targetIteration = GetItem<ClassificationNode>(new { Node = Iteration, StructureGroup = TreeStructureGroup.Iterations }); if (targetIteration == null) { if (!ShouldProcess($"Team project '{targetTp.Name}'", $"Create iteration path {Iteration}")) { return; } targetIteration = NewItem<ClassificationNode>(new { Node = Iteration, StructureGroup = TreeStructureGroup.Iterations }); } targetIterationPath = $"{targetTp.Name}{targetIteration.RelativePath}"; } else { this.Log("Iteration not informed. Moving to root iteration."); targetIterationPath = targetTp.Name; } foreach (var wi in wis) { if (!ShouldProcess($"Work item {wi.Id}", $"Move work item to team project '{targetTp.Name}'")) { continue; } var patch = new JsonPatchDocument() { new JsonPatchOperation(){ Operation = Operation.Add, Path = "/fields/System.TeamProject", Value = targetTp.Name }, new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.AreaPath", Value = targetAreaPath }, new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.IterationPath", Value = targetIterationPath } }; if (!string.IsNullOrEmpty(State)) { patch.Add(new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.State", Value = State }); } if (!string.IsNullOrEmpty(Comment)) { patch.Add(new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.History", Value = Comment }); } var client = GetClient<WorkItemTrackingHttpClient>(); var result = client.UpdateWorkItemAsync(patch, (int)wi.Id) .GetResult("Error moving work item"); if (Passthru) { WriteObject(GetItem<WebApiWorkItem>(new { WorkItem = (int)result.Id })); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace EasyStitch.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.Data.Common; using System.Runtime.InteropServices; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Data.SqlTypes { /// <summary> /// Represents a floating point number within the range of -3.40E +38 through /// 3.40E +38 to be stored in or retrieved from a database. /// </summary> [StructLayout(LayoutKind.Sequential)] [Serializable] [XmlSchemaProvider("GetXsdType")] public struct SqlSingle : INullable, IComparable, IXmlSerializable { private bool _fNotNull; // false if null private float _value; // constructor // construct a Null private SqlSingle(bool fNull) { _fNotNull = false; _value = (float)0.0; } public SqlSingle(float value) { if (float.IsInfinity(value) || float.IsNaN(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); else { _fNotNull = true; _value = value; } } public SqlSingle(double value) : this(checked((float)value)) { } // INullable public bool IsNull { get { return !_fNotNull; } } // property: Value public float Value { get { if (_fNotNull) return _value; else throw new SqlNullValueException(); } } // Implicit conversion from float to SqlSingle public static implicit operator SqlSingle(float x) { return new SqlSingle(x); } // Explicit conversion from SqlSingle to float. Throw exception if x is Null. public static explicit operator float (SqlSingle x) { return x.Value; } public override string ToString() { return IsNull ? SQLResource.NullString : _value.ToString((IFormatProvider)null); } public static SqlSingle Parse(string s) { if (s == SQLResource.NullString) return SqlSingle.Null; else return new SqlSingle(float.Parse(s, CultureInfo.InvariantCulture)); } // Unary operators public static SqlSingle operator -(SqlSingle x) { return x.IsNull ? Null : new SqlSingle(-x._value); } // Binary operators // Arithmetic operators public static SqlSingle operator +(SqlSingle x, SqlSingle y) { if (x.IsNull || y.IsNull) return Null; float value = x._value + y._value; if (float.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlSingle(value); } public static SqlSingle operator -(SqlSingle x, SqlSingle y) { if (x.IsNull || y.IsNull) return Null; float value = x._value - y._value; if (float.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlSingle(value); } public static SqlSingle operator *(SqlSingle x, SqlSingle y) { if (x.IsNull || y.IsNull) return Null; float value = x._value * y._value; if (float.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlSingle(value); } public static SqlSingle operator /(SqlSingle x, SqlSingle y) { if (x.IsNull || y.IsNull) return Null; if (y._value == (float)0.0) throw new DivideByZeroException(SQLResource.DivideByZeroMessage); float value = x._value / y._value; if (float.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlSingle(value); } // Implicit conversions // Implicit conversion from SqlBoolean to SqlSingle public static explicit operator SqlSingle(SqlBoolean x) { return x.IsNull ? Null : new SqlSingle(x.ByteValue); } // Implicit conversion from SqlByte to SqlSingle public static implicit operator SqlSingle(SqlByte x) { // Will not overflow return x.IsNull ? Null : new SqlSingle(x.Value); } // Implicit conversion from SqlInt16 to SqlSingle public static implicit operator SqlSingle(SqlInt16 x) { // Will not overflow return x.IsNull ? Null : new SqlSingle(x.Value); } // Implicit conversion from SqlInt32 to SqlSingle public static implicit operator SqlSingle(SqlInt32 x) { // Will not overflow return x.IsNull ? Null : new SqlSingle(x.Value); } // Implicit conversion from SqlInt64 to SqlSingle public static implicit operator SqlSingle(SqlInt64 x) { // Will not overflow return x.IsNull ? Null : new SqlSingle(x.Value); } // Implicit conversion from SqlMoney to SqlSingle public static implicit operator SqlSingle(SqlMoney x) { return x.IsNull ? Null : new SqlSingle(x.ToDouble()); } // Implicit conversion from SqlDecimal to SqlSingle public static implicit operator SqlSingle(SqlDecimal x) { // Will not overflow return x.IsNull ? Null : new SqlSingle(x.ToDouble()); } // Explicit conversions // Explicit conversion from SqlDouble to SqlSingle public static explicit operator SqlSingle(SqlDouble x) { return x.IsNull ? Null : new SqlSingle(x.Value); } // Explicit conversion from SqlString to SqlSingle // Throws FormatException or OverflowException if necessary. public static explicit operator SqlSingle(SqlString x) { if (x.IsNull) return SqlSingle.Null; return Parse(x.Value); } // Overloading comparison operators public static SqlBoolean operator ==(SqlSingle x, SqlSingle y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value == y._value); } public static SqlBoolean operator !=(SqlSingle x, SqlSingle y) { return !(x == y); } public static SqlBoolean operator <(SqlSingle x, SqlSingle y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value < y._value); } public static SqlBoolean operator >(SqlSingle x, SqlSingle y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value > y._value); } public static SqlBoolean operator <=(SqlSingle x, SqlSingle y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value <= y._value); } public static SqlBoolean operator >=(SqlSingle x, SqlSingle y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value >= y._value); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator + public static SqlSingle Add(SqlSingle x, SqlSingle y) { return x + y; } // Alternative method for operator - public static SqlSingle Subtract(SqlSingle x, SqlSingle y) { return x - y; } // Alternative method for operator * public static SqlSingle Multiply(SqlSingle x, SqlSingle y) { return x * y; } // Alternative method for operator / public static SqlSingle Divide(SqlSingle x, SqlSingle y) { return x / y; } // Alternative method for operator == public static SqlBoolean Equals(SqlSingle x, SqlSingle y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlSingle x, SqlSingle y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlSingle x, SqlSingle y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlSingle x, SqlSingle y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlSingle x, SqlSingle y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlSingle x, SqlSingle y) { return (x >= y); } // Alternative method for conversions. public SqlBoolean ToSqlBoolean() { return (SqlBoolean)this; } public SqlByte ToSqlByte() { return (SqlByte)this; } public SqlDouble ToSqlDouble() { return this; } public SqlInt16 ToSqlInt16() { return (SqlInt16)this; } public SqlInt32 ToSqlInt32() { return (SqlInt32)this; } public SqlInt64 ToSqlInt64() { return (SqlInt64)this; } public SqlMoney ToSqlMoney() { return (SqlMoney)this; } public SqlDecimal ToSqlDecimal() { return (SqlDecimal)this; } public SqlString ToSqlString() { return (SqlString)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object value) { if (value is SqlSingle) { SqlSingle i = (SqlSingle)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlSingle)); } public int CompareTo(SqlSingle value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object public override bool Equals(object value) { if (!(value is SqlSingle)) { return false; } SqlSingle i = (SqlSingle)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose public override int GetHashCode() { return IsNull ? 0 : Value.GetHashCode(); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); _fNotNull = false; } else { _value = XmlConvert.ToSingle(reader.ReadElementString()); _fNotNull = true; } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { writer.WriteString(XmlConvert.ToString(_value)); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("float", XmlSchema.Namespace); } public static readonly SqlSingle Null = new SqlSingle(true); public static readonly SqlSingle Zero = new SqlSingle((float)0.0); public static readonly SqlSingle MinValue = new SqlSingle(float.MinValue); public static readonly SqlSingle MaxValue = new SqlSingle(float.MaxValue); } // SqlSingle } // namespace System.Data.SqlTypes
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the AprHistoriaClinicaPerinatalDetalle class. /// </summary> [Serializable] public partial class AprHistoriaClinicaPerinatalDetalleCollection : ActiveList<AprHistoriaClinicaPerinatalDetalle, AprHistoriaClinicaPerinatalDetalleCollection> { public AprHistoriaClinicaPerinatalDetalleCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprHistoriaClinicaPerinatalDetalleCollection</returns> public AprHistoriaClinicaPerinatalDetalleCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprHistoriaClinicaPerinatalDetalle o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the APR_HistoriaClinicaPerinatalDetalle table. /// </summary> [Serializable] public partial class AprHistoriaClinicaPerinatalDetalle : ActiveRecord<AprHistoriaClinicaPerinatalDetalle>, IActiveRecord { #region .ctors and Default Settings public AprHistoriaClinicaPerinatalDetalle() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprHistoriaClinicaPerinatalDetalle(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprHistoriaClinicaPerinatalDetalle(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprHistoriaClinicaPerinatalDetalle(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("APR_HistoriaClinicaPerinatalDetalle", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdHistoriaClinicaPerinatalDetalle = new TableSchema.TableColumn(schema); colvarIdHistoriaClinicaPerinatalDetalle.ColumnName = "idHistoriaClinicaPerinatalDetalle"; colvarIdHistoriaClinicaPerinatalDetalle.DataType = DbType.Int32; colvarIdHistoriaClinicaPerinatalDetalle.MaxLength = 0; colvarIdHistoriaClinicaPerinatalDetalle.AutoIncrement = true; colvarIdHistoriaClinicaPerinatalDetalle.IsNullable = false; colvarIdHistoriaClinicaPerinatalDetalle.IsPrimaryKey = true; colvarIdHistoriaClinicaPerinatalDetalle.IsForeignKey = false; colvarIdHistoriaClinicaPerinatalDetalle.IsReadOnly = false; colvarIdHistoriaClinicaPerinatalDetalle.DefaultSetting = @""; colvarIdHistoriaClinicaPerinatalDetalle.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdHistoriaClinicaPerinatalDetalle); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = false; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarIdHistoriaClinicaPerinatal = new TableSchema.TableColumn(schema); colvarIdHistoriaClinicaPerinatal.ColumnName = "idHistoriaClinicaPerinatal"; colvarIdHistoriaClinicaPerinatal.DataType = DbType.Int32; colvarIdHistoriaClinicaPerinatal.MaxLength = 0; colvarIdHistoriaClinicaPerinatal.AutoIncrement = false; colvarIdHistoriaClinicaPerinatal.IsNullable = false; colvarIdHistoriaClinicaPerinatal.IsPrimaryKey = false; colvarIdHistoriaClinicaPerinatal.IsForeignKey = true; colvarIdHistoriaClinicaPerinatal.IsReadOnly = false; colvarIdHistoriaClinicaPerinatal.DefaultSetting = @""; colvarIdHistoriaClinicaPerinatal.ForeignKeyTableName = "APR_HistoriaClinicaPerinatal"; schema.Columns.Add(colvarIdHistoriaClinicaPerinatal); TableSchema.TableColumn colvarIdConsulta = new TableSchema.TableColumn(schema); colvarIdConsulta.ColumnName = "idConsulta"; colvarIdConsulta.DataType = DbType.Int32; colvarIdConsulta.MaxLength = 0; colvarIdConsulta.AutoIncrement = false; colvarIdConsulta.IsNullable = true; colvarIdConsulta.IsPrimaryKey = false; colvarIdConsulta.IsForeignKey = true; colvarIdConsulta.IsReadOnly = false; colvarIdConsulta.DefaultSetting = @""; colvarIdConsulta.ForeignKeyTableName = "CON_Consulta"; schema.Columns.Add(colvarIdConsulta); TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema); colvarFecha.ColumnName = "Fecha"; colvarFecha.DataType = DbType.DateTime; colvarFecha.MaxLength = 0; colvarFecha.AutoIncrement = false; colvarFecha.IsNullable = true; colvarFecha.IsPrimaryKey = false; colvarFecha.IsForeignKey = false; colvarFecha.IsReadOnly = false; colvarFecha.DefaultSetting = @""; colvarFecha.ForeignKeyTableName = ""; schema.Columns.Add(colvarFecha); TableSchema.TableColumn colvarEdadGestacional = new TableSchema.TableColumn(schema); colvarEdadGestacional.ColumnName = "EdadGestacional"; colvarEdadGestacional.DataType = DbType.Decimal; colvarEdadGestacional.MaxLength = 0; colvarEdadGestacional.AutoIncrement = false; colvarEdadGestacional.IsNullable = true; colvarEdadGestacional.IsPrimaryKey = false; colvarEdadGestacional.IsForeignKey = false; colvarEdadGestacional.IsReadOnly = false; colvarEdadGestacional.DefaultSetting = @""; colvarEdadGestacional.ForeignKeyTableName = ""; schema.Columns.Add(colvarEdadGestacional); TableSchema.TableColumn colvarPeso = new TableSchema.TableColumn(schema); colvarPeso.ColumnName = "Peso"; colvarPeso.DataType = DbType.Decimal; colvarPeso.MaxLength = 0; colvarPeso.AutoIncrement = false; colvarPeso.IsNullable = true; colvarPeso.IsPrimaryKey = false; colvarPeso.IsForeignKey = false; colvarPeso.IsReadOnly = false; colvarPeso.DefaultSetting = @""; colvarPeso.ForeignKeyTableName = ""; schema.Columns.Add(colvarPeso); TableSchema.TableColumn colvarImc = new TableSchema.TableColumn(schema); colvarImc.ColumnName = "IMC"; colvarImc.DataType = DbType.Decimal; colvarImc.MaxLength = 0; colvarImc.AutoIncrement = false; colvarImc.IsNullable = true; colvarImc.IsPrimaryKey = false; colvarImc.IsForeignKey = false; colvarImc.IsReadOnly = false; colvarImc.DefaultSetting = @""; colvarImc.ForeignKeyTableName = ""; schema.Columns.Add(colvarImc); TableSchema.TableColumn colvarPa = new TableSchema.TableColumn(schema); colvarPa.ColumnName = "PA"; colvarPa.DataType = DbType.AnsiString; colvarPa.MaxLength = -1; colvarPa.AutoIncrement = false; colvarPa.IsNullable = true; colvarPa.IsPrimaryKey = false; colvarPa.IsForeignKey = false; colvarPa.IsReadOnly = false; colvarPa.DefaultSetting = @""; colvarPa.ForeignKeyTableName = ""; schema.Columns.Add(colvarPa); TableSchema.TableColumn colvarAlturaUterina = new TableSchema.TableColumn(schema); colvarAlturaUterina.ColumnName = "AlturaUterina"; colvarAlturaUterina.DataType = DbType.Decimal; colvarAlturaUterina.MaxLength = 0; colvarAlturaUterina.AutoIncrement = false; colvarAlturaUterina.IsNullable = true; colvarAlturaUterina.IsPrimaryKey = false; colvarAlturaUterina.IsForeignKey = false; colvarAlturaUterina.IsReadOnly = false; colvarAlturaUterina.DefaultSetting = @""; colvarAlturaUterina.ForeignKeyTableName = ""; schema.Columns.Add(colvarAlturaUterina); TableSchema.TableColumn colvarPresentacion = new TableSchema.TableColumn(schema); colvarPresentacion.ColumnName = "Presentacion"; colvarPresentacion.DataType = DbType.AnsiString; colvarPresentacion.MaxLength = -1; colvarPresentacion.AutoIncrement = false; colvarPresentacion.IsNullable = true; colvarPresentacion.IsPrimaryKey = false; colvarPresentacion.IsForeignKey = false; colvarPresentacion.IsReadOnly = false; colvarPresentacion.DefaultSetting = @""; colvarPresentacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarPresentacion); TableSchema.TableColumn colvarFcf = new TableSchema.TableColumn(schema); colvarFcf.ColumnName = "FCF"; colvarFcf.DataType = DbType.Int32; colvarFcf.MaxLength = 0; colvarFcf.AutoIncrement = false; colvarFcf.IsNullable = true; colvarFcf.IsPrimaryKey = false; colvarFcf.IsForeignKey = false; colvarFcf.IsReadOnly = false; colvarFcf.DefaultSetting = @""; colvarFcf.ForeignKeyTableName = ""; schema.Columns.Add(colvarFcf); TableSchema.TableColumn colvarMovimientosFetales = new TableSchema.TableColumn(schema); colvarMovimientosFetales.ColumnName = "MovimientosFetales"; colvarMovimientosFetales.DataType = DbType.AnsiString; colvarMovimientosFetales.MaxLength = -1; colvarMovimientosFetales.AutoIncrement = false; colvarMovimientosFetales.IsNullable = true; colvarMovimientosFetales.IsPrimaryKey = false; colvarMovimientosFetales.IsForeignKey = false; colvarMovimientosFetales.IsReadOnly = false; colvarMovimientosFetales.DefaultSetting = @""; colvarMovimientosFetales.ForeignKeyTableName = ""; schema.Columns.Add(colvarMovimientosFetales); TableSchema.TableColumn colvarProteinuria = new TableSchema.TableColumn(schema); colvarProteinuria.ColumnName = "Proteinuria"; colvarProteinuria.DataType = DbType.AnsiString; colvarProteinuria.MaxLength = -1; colvarProteinuria.AutoIncrement = false; colvarProteinuria.IsNullable = true; colvarProteinuria.IsPrimaryKey = false; colvarProteinuria.IsForeignKey = false; colvarProteinuria.IsReadOnly = false; colvarProteinuria.DefaultSetting = @""; colvarProteinuria.ForeignKeyTableName = ""; schema.Columns.Add(colvarProteinuria); TableSchema.TableColumn colvarAlarmaExamenesTratamientos = new TableSchema.TableColumn(schema); colvarAlarmaExamenesTratamientos.ColumnName = "AlarmaExamenesTratamientos"; colvarAlarmaExamenesTratamientos.DataType = DbType.AnsiString; colvarAlarmaExamenesTratamientos.MaxLength = -1; colvarAlarmaExamenesTratamientos.AutoIncrement = false; colvarAlarmaExamenesTratamientos.IsNullable = true; colvarAlarmaExamenesTratamientos.IsPrimaryKey = false; colvarAlarmaExamenesTratamientos.IsForeignKey = false; colvarAlarmaExamenesTratamientos.IsReadOnly = false; colvarAlarmaExamenesTratamientos.DefaultSetting = @""; colvarAlarmaExamenesTratamientos.ForeignKeyTableName = ""; schema.Columns.Add(colvarAlarmaExamenesTratamientos); TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema); colvarObservaciones.ColumnName = "Observaciones"; colvarObservaciones.DataType = DbType.AnsiString; colvarObservaciones.MaxLength = -1; colvarObservaciones.AutoIncrement = false; colvarObservaciones.IsNullable = true; colvarObservaciones.IsPrimaryKey = false; colvarObservaciones.IsForeignKey = false; colvarObservaciones.IsReadOnly = false; colvarObservaciones.DefaultSetting = @""; colvarObservaciones.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservaciones); TableSchema.TableColumn colvarInicialesTecnico = new TableSchema.TableColumn(schema); colvarInicialesTecnico.ColumnName = "InicialesTecnico"; colvarInicialesTecnico.DataType = DbType.AnsiString; colvarInicialesTecnico.MaxLength = -1; colvarInicialesTecnico.AutoIncrement = false; colvarInicialesTecnico.IsNullable = true; colvarInicialesTecnico.IsPrimaryKey = false; colvarInicialesTecnico.IsForeignKey = false; colvarInicialesTecnico.IsReadOnly = false; colvarInicialesTecnico.DefaultSetting = @""; colvarInicialesTecnico.ForeignKeyTableName = ""; schema.Columns.Add(colvarInicialesTecnico); TableSchema.TableColumn colvarProximaCita = new TableSchema.TableColumn(schema); colvarProximaCita.ColumnName = "ProximaCita"; colvarProximaCita.DataType = DbType.DateTime; colvarProximaCita.MaxLength = 0; colvarProximaCita.AutoIncrement = false; colvarProximaCita.IsNullable = true; colvarProximaCita.IsPrimaryKey = false; colvarProximaCita.IsForeignKey = false; colvarProximaCita.IsReadOnly = false; colvarProximaCita.DefaultSetting = @""; colvarProximaCita.ForeignKeyTableName = ""; schema.Columns.Add(colvarProximaCita); TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema); colvarCreatedBy.ColumnName = "CreatedBy"; colvarCreatedBy.DataType = DbType.AnsiString; colvarCreatedBy.MaxLength = 50; colvarCreatedBy.AutoIncrement = false; colvarCreatedBy.IsNullable = true; colvarCreatedBy.IsPrimaryKey = false; colvarCreatedBy.IsForeignKey = false; colvarCreatedBy.IsReadOnly = false; colvarCreatedBy.DefaultSetting = @""; colvarCreatedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedBy); TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema); colvarCreatedOn.ColumnName = "CreatedOn"; colvarCreatedOn.DataType = DbType.DateTime; colvarCreatedOn.MaxLength = 0; colvarCreatedOn.AutoIncrement = false; colvarCreatedOn.IsNullable = true; colvarCreatedOn.IsPrimaryKey = false; colvarCreatedOn.IsForeignKey = false; colvarCreatedOn.IsReadOnly = false; colvarCreatedOn.DefaultSetting = @""; colvarCreatedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedOn); TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema); colvarModifiedBy.ColumnName = "ModifiedBy"; colvarModifiedBy.DataType = DbType.AnsiString; colvarModifiedBy.MaxLength = 50; colvarModifiedBy.AutoIncrement = false; colvarModifiedBy.IsNullable = true; colvarModifiedBy.IsPrimaryKey = false; colvarModifiedBy.IsForeignKey = false; colvarModifiedBy.IsReadOnly = false; colvarModifiedBy.DefaultSetting = @""; colvarModifiedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedBy); TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema); colvarModifiedOn.ColumnName = "ModifiedOn"; colvarModifiedOn.DataType = DbType.DateTime; colvarModifiedOn.MaxLength = 0; colvarModifiedOn.AutoIncrement = false; colvarModifiedOn.IsNullable = true; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; colvarModifiedOn.DefaultSetting = @""; colvarModifiedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedOn); TableSchema.TableColumn colvarActiva = new TableSchema.TableColumn(schema); colvarActiva.ColumnName = "activa"; colvarActiva.DataType = DbType.Boolean; colvarActiva.MaxLength = 0; colvarActiva.AutoIncrement = false; colvarActiva.IsNullable = false; colvarActiva.IsPrimaryKey = false; colvarActiva.IsForeignKey = false; colvarActiva.IsReadOnly = false; colvarActiva.DefaultSetting = @"((1))"; colvarActiva.ForeignKeyTableName = ""; schema.Columns.Add(colvarActiva); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_HistoriaClinicaPerinatalDetalle",schema); } } #endregion #region Props [XmlAttribute("IdHistoriaClinicaPerinatalDetalle")] [Bindable(true)] public int IdHistoriaClinicaPerinatalDetalle { get { return GetColumnValue<int>(Columns.IdHistoriaClinicaPerinatalDetalle); } set { SetColumnValue(Columns.IdHistoriaClinicaPerinatalDetalle, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("IdHistoriaClinicaPerinatal")] [Bindable(true)] public int IdHistoriaClinicaPerinatal { get { return GetColumnValue<int>(Columns.IdHistoriaClinicaPerinatal); } set { SetColumnValue(Columns.IdHistoriaClinicaPerinatal, value); } } [XmlAttribute("IdConsulta")] [Bindable(true)] public int? IdConsulta { get { return GetColumnValue<int?>(Columns.IdConsulta); } set { SetColumnValue(Columns.IdConsulta, value); } } [XmlAttribute("Fecha")] [Bindable(true)] public DateTime? Fecha { get { return GetColumnValue<DateTime?>(Columns.Fecha); } set { SetColumnValue(Columns.Fecha, value); } } [XmlAttribute("EdadGestacional")] [Bindable(true)] public decimal? EdadGestacional { get { return GetColumnValue<decimal?>(Columns.EdadGestacional); } set { SetColumnValue(Columns.EdadGestacional, value); } } [XmlAttribute("Peso")] [Bindable(true)] public decimal? Peso { get { return GetColumnValue<decimal?>(Columns.Peso); } set { SetColumnValue(Columns.Peso, value); } } [XmlAttribute("Imc")] [Bindable(true)] public decimal? Imc { get { return GetColumnValue<decimal?>(Columns.Imc); } set { SetColumnValue(Columns.Imc, value); } } [XmlAttribute("Pa")] [Bindable(true)] public string Pa { get { return GetColumnValue<string>(Columns.Pa); } set { SetColumnValue(Columns.Pa, value); } } [XmlAttribute("AlturaUterina")] [Bindable(true)] public decimal? AlturaUterina { get { return GetColumnValue<decimal?>(Columns.AlturaUterina); } set { SetColumnValue(Columns.AlturaUterina, value); } } [XmlAttribute("Presentacion")] [Bindable(true)] public string Presentacion { get { return GetColumnValue<string>(Columns.Presentacion); } set { SetColumnValue(Columns.Presentacion, value); } } [XmlAttribute("Fcf")] [Bindable(true)] public int? Fcf { get { return GetColumnValue<int?>(Columns.Fcf); } set { SetColumnValue(Columns.Fcf, value); } } [XmlAttribute("MovimientosFetales")] [Bindable(true)] public string MovimientosFetales { get { return GetColumnValue<string>(Columns.MovimientosFetales); } set { SetColumnValue(Columns.MovimientosFetales, value); } } [XmlAttribute("Proteinuria")] [Bindable(true)] public string Proteinuria { get { return GetColumnValue<string>(Columns.Proteinuria); } set { SetColumnValue(Columns.Proteinuria, value); } } [XmlAttribute("AlarmaExamenesTratamientos")] [Bindable(true)] public string AlarmaExamenesTratamientos { get { return GetColumnValue<string>(Columns.AlarmaExamenesTratamientos); } set { SetColumnValue(Columns.AlarmaExamenesTratamientos, value); } } [XmlAttribute("Observaciones")] [Bindable(true)] public string Observaciones { get { return GetColumnValue<string>(Columns.Observaciones); } set { SetColumnValue(Columns.Observaciones, value); } } [XmlAttribute("InicialesTecnico")] [Bindable(true)] public string InicialesTecnico { get { return GetColumnValue<string>(Columns.InicialesTecnico); } set { SetColumnValue(Columns.InicialesTecnico, value); } } [XmlAttribute("ProximaCita")] [Bindable(true)] public DateTime? ProximaCita { get { return GetColumnValue<DateTime?>(Columns.ProximaCita); } set { SetColumnValue(Columns.ProximaCita, value); } } [XmlAttribute("CreatedBy")] [Bindable(true)] public string CreatedBy { get { return GetColumnValue<string>(Columns.CreatedBy); } set { SetColumnValue(Columns.CreatedBy, value); } } [XmlAttribute("CreatedOn")] [Bindable(true)] public DateTime? CreatedOn { get { return GetColumnValue<DateTime?>(Columns.CreatedOn); } set { SetColumnValue(Columns.CreatedOn, value); } } [XmlAttribute("ModifiedBy")] [Bindable(true)] public string ModifiedBy { get { return GetColumnValue<string>(Columns.ModifiedBy); } set { SetColumnValue(Columns.ModifiedBy, value); } } [XmlAttribute("ModifiedOn")] [Bindable(true)] public DateTime? ModifiedOn { get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); } set { SetColumnValue(Columns.ModifiedOn, value); } } [XmlAttribute("Activa")] [Bindable(true)] public bool Activa { get { return GetColumnValue<bool>(Columns.Activa); } set { SetColumnValue(Columns.Activa, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a AprHistoriaClinicaPerinatal ActiveRecord object related to this AprHistoriaClinicaPerinatalDetalle /// /// </summary> public DalSic.AprHistoriaClinicaPerinatal AprHistoriaClinicaPerinatal { get { return DalSic.AprHistoriaClinicaPerinatal.FetchByID(this.IdHistoriaClinicaPerinatal); } set { SetColumnValue("idHistoriaClinicaPerinatal", value.IdHistoriaClinicaPerinatal); } } /// <summary> /// Returns a ConConsultum ActiveRecord object related to this AprHistoriaClinicaPerinatalDetalle /// /// </summary> public DalSic.ConConsultum ConConsultum { get { return DalSic.ConConsultum.FetchByID(this.IdConsulta); } set { SetColumnValue("idConsulta", value.IdConsulta); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdEfector,int varIdHistoriaClinicaPerinatal,int? varIdConsulta,DateTime? varFecha,decimal? varEdadGestacional,decimal? varPeso,decimal? varImc,string varPa,decimal? varAlturaUterina,string varPresentacion,int? varFcf,string varMovimientosFetales,string varProteinuria,string varAlarmaExamenesTratamientos,string varObservaciones,string varInicialesTecnico,DateTime? varProximaCita,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn,bool varActiva) { AprHistoriaClinicaPerinatalDetalle item = new AprHistoriaClinicaPerinatalDetalle(); item.IdEfector = varIdEfector; item.IdHistoriaClinicaPerinatal = varIdHistoriaClinicaPerinatal; item.IdConsulta = varIdConsulta; item.Fecha = varFecha; item.EdadGestacional = varEdadGestacional; item.Peso = varPeso; item.Imc = varImc; item.Pa = varPa; item.AlturaUterina = varAlturaUterina; item.Presentacion = varPresentacion; item.Fcf = varFcf; item.MovimientosFetales = varMovimientosFetales; item.Proteinuria = varProteinuria; item.AlarmaExamenesTratamientos = varAlarmaExamenesTratamientos; item.Observaciones = varObservaciones; item.InicialesTecnico = varInicialesTecnico; item.ProximaCita = varProximaCita; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; item.Activa = varActiva; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdHistoriaClinicaPerinatalDetalle,int varIdEfector,int varIdHistoriaClinicaPerinatal,int? varIdConsulta,DateTime? varFecha,decimal? varEdadGestacional,decimal? varPeso,decimal? varImc,string varPa,decimal? varAlturaUterina,string varPresentacion,int? varFcf,string varMovimientosFetales,string varProteinuria,string varAlarmaExamenesTratamientos,string varObservaciones,string varInicialesTecnico,DateTime? varProximaCita,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn,bool varActiva) { AprHistoriaClinicaPerinatalDetalle item = new AprHistoriaClinicaPerinatalDetalle(); item.IdHistoriaClinicaPerinatalDetalle = varIdHistoriaClinicaPerinatalDetalle; item.IdEfector = varIdEfector; item.IdHistoriaClinicaPerinatal = varIdHistoriaClinicaPerinatal; item.IdConsulta = varIdConsulta; item.Fecha = varFecha; item.EdadGestacional = varEdadGestacional; item.Peso = varPeso; item.Imc = varImc; item.Pa = varPa; item.AlturaUterina = varAlturaUterina; item.Presentacion = varPresentacion; item.Fcf = varFcf; item.MovimientosFetales = varMovimientosFetales; item.Proteinuria = varProteinuria; item.AlarmaExamenesTratamientos = varAlarmaExamenesTratamientos; item.Observaciones = varObservaciones; item.InicialesTecnico = varInicialesTecnico; item.ProximaCita = varProximaCita; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; item.Activa = varActiva; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdHistoriaClinicaPerinatalDetalleColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdHistoriaClinicaPerinatalColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdConsultaColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn FechaColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn EdadGestacionalColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn PesoColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn ImcColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn PaColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn AlturaUterinaColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn PresentacionColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn FcfColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn MovimientosFetalesColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn ProteinuriaColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn AlarmaExamenesTratamientosColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn ObservacionesColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn InicialesTecnicoColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn ProximaCitaColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn CreatedByColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn CreatedOnColumn { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn ModifiedByColumn { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn ModifiedOnColumn { get { return Schema.Columns[21]; } } public static TableSchema.TableColumn ActivaColumn { get { return Schema.Columns[22]; } } #endregion #region Columns Struct public struct Columns { public static string IdHistoriaClinicaPerinatalDetalle = @"idHistoriaClinicaPerinatalDetalle"; public static string IdEfector = @"idEfector"; public static string IdHistoriaClinicaPerinatal = @"idHistoriaClinicaPerinatal"; public static string IdConsulta = @"idConsulta"; public static string Fecha = @"Fecha"; public static string EdadGestacional = @"EdadGestacional"; public static string Peso = @"Peso"; public static string Imc = @"IMC"; public static string Pa = @"PA"; public static string AlturaUterina = @"AlturaUterina"; public static string Presentacion = @"Presentacion"; public static string Fcf = @"FCF"; public static string MovimientosFetales = @"MovimientosFetales"; public static string Proteinuria = @"Proteinuria"; public static string AlarmaExamenesTratamientos = @"AlarmaExamenesTratamientos"; public static string Observaciones = @"Observaciones"; public static string InicialesTecnico = @"InicialesTecnico"; public static string ProximaCita = @"ProximaCita"; public static string CreatedBy = @"CreatedBy"; public static string CreatedOn = @"CreatedOn"; public static string ModifiedBy = @"ModifiedBy"; public static string ModifiedOn = @"ModifiedOn"; public static string Activa = @"activa"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Vhd { using System; using System.Collections.Generic; using System.IO; internal class DynamicStream : MappedStream { private Stream _fileStream; private DynamicHeader _dynamicHeader; private long _length; private SparseStream _parentStream; private Ownership _ownsParentStream; private long _position; private bool _atEof; private uint[] _blockAllocationTable; private byte[][] _blockBitmaps; private int _blockBitmapSize; private long _nextBlockStart; private bool _newBlocksAllocated; private bool _autoCommitFooter = true; private byte[] _footerCache; public DynamicStream(Stream fileStream, DynamicHeader dynamicHeader, long length, SparseStream parentStream, Ownership ownsParentStream) { if (fileStream == null) { throw new ArgumentNullException("fileStream"); } if (dynamicHeader == null) { throw new ArgumentNullException("dynamicHeader"); } if (parentStream == null) { throw new ArgumentNullException("parentStream"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", length, "Negative lengths not allowed"); } _fileStream = fileStream; _dynamicHeader = dynamicHeader; _length = length; _parentStream = parentStream; _ownsParentStream = ownsParentStream; _blockBitmaps = new byte[_dynamicHeader.MaxTableEntries][]; _blockBitmapSize = (int)Utilities.RoundUp((_dynamicHeader.BlockSize / Utilities.SectorSize) / 8, Utilities.SectorSize); ReadBlockAllocationTable(); // Detect where next block should go (cope if the footer is missing) _fileStream.Position = Utilities.RoundDown(_fileStream.Length, Utilities.SectorSize) - Utilities.SectorSize; byte[] footerBytes = Utilities.ReadFully(_fileStream, Utilities.SectorSize); Footer footer = Footer.FromBytes(footerBytes, 0); _nextBlockStart = _fileStream.Position - (footer.IsValid() ? Utilities.SectorSize : 0); } public bool AutoCommitFooter { get { return _autoCommitFooter; } set { _autoCommitFooter = value; if (_autoCommitFooter) { UpdateFooter(); } } } public override bool CanRead { get { CheckDisposed(); return true; } } public override bool CanSeek { get { CheckDisposed(); return true; } } public override bool CanWrite { get { CheckDisposed(); return _fileStream.CanWrite; } } public override long Length { get { CheckDisposed(); return _length; } } public override long Position { get { CheckDisposed(); return _position; } set { CheckDisposed(); _atEof = false; _position = value; } } public override IEnumerable<StreamExtent> Extents { get { return GetExtentsInRange(0, Length); } } public override void Flush() { CheckDisposed(); } public override IEnumerable<StreamExtent> MapContent(long start, long length) { long position = start; int maxToRead = (int)Math.Min(length, _length - position); int numRead = 0; while (numRead < maxToRead) { long block = position / _dynamicHeader.BlockSize; uint offsetInBlock = (uint)(position % _dynamicHeader.BlockSize); if (PopulateBlockBitmap(block)) { int sectorInBlock = (int)(offsetInBlock / Utilities.SectorSize); int offsetInSector = (int)(offsetInBlock % Utilities.SectorSize); int toRead = (int)Math.Min(maxToRead - numRead, _dynamicHeader.BlockSize - offsetInBlock); // 512 - offsetInSector); if (offsetInSector != 0 || toRead < Utilities.SectorSize) { byte mask = (byte)(1 << (7 - (sectorInBlock % 8))); if ((_blockBitmaps[block][sectorInBlock / 8] & mask) != 0) { long extentStart = ((((long)_blockAllocationTable[block]) + sectorInBlock) * Utilities.SectorSize) + _blockBitmapSize + offsetInSector; yield return new StreamExtent(extentStart, toRead); } numRead += toRead; position += toRead; } else { // Processing at least one whole sector, read as many as possible int toReadSectors = toRead / Utilities.SectorSize; byte mask = (byte)(1 << (7 - (sectorInBlock % 8))); bool readFromParent = (_blockBitmaps[block][sectorInBlock / 8] & mask) == 0; int numSectors = 1; while (numSectors < toReadSectors) { mask = (byte)(1 << (7 - ((sectorInBlock + numSectors) % 8))); if (((_blockBitmaps[block][(sectorInBlock + numSectors) / 8] & mask) == 0) != readFromParent) { break; } ++numSectors; } toRead = numSectors * Utilities.SectorSize; if (!readFromParent) { long extentStart = ((((long)_blockAllocationTable[block]) + sectorInBlock) * Utilities.SectorSize) + _blockBitmapSize; yield return new StreamExtent(extentStart, toRead); } numRead += toRead; position += toRead; } } else { int toRead = Math.Min(maxToRead - numRead, (int)(_dynamicHeader.BlockSize - offsetInBlock)); numRead += toRead; position += toRead; } } } public override int Read(byte[] buffer, int offset, int count) { CheckDisposed(); if (_atEof || _position > _length) { _atEof = true; throw new IOException("Attempt to read beyond end of file"); } if (_position == _length) { _atEof = true; return 0; } int maxToRead = (int)Math.Min(count, _length - _position); int numRead = 0; while (numRead < maxToRead) { long block = _position / _dynamicHeader.BlockSize; uint offsetInBlock = (uint)(_position % _dynamicHeader.BlockSize); if (PopulateBlockBitmap(block)) { int sectorInBlock = (int)(offsetInBlock / Utilities.SectorSize); int offsetInSector = (int)(offsetInBlock % Utilities.SectorSize); int toRead = (int)Math.Min(maxToRead - numRead, _dynamicHeader.BlockSize - offsetInBlock); // 512 - offsetInSector); if (offsetInSector != 0 || toRead < Utilities.SectorSize) { byte mask = (byte)(1 << (7 - (sectorInBlock % 8))); if ((_blockBitmaps[block][sectorInBlock / 8] & mask) != 0) { _fileStream.Position = ((((long)_blockAllocationTable[block]) + sectorInBlock) * Utilities.SectorSize) + _blockBitmapSize + offsetInSector; if (Utilities.ReadFully(_fileStream, buffer, offset + numRead, toRead) != toRead) { throw new IOException("Failed to read entire sector"); } } else { _parentStream.Position = _position; Utilities.ReadFully(_parentStream, buffer, offset + numRead, toRead); } numRead += toRead; _position += toRead; } else { // Processing at least one whole sector, read as many as possible int toReadSectors = toRead / Utilities.SectorSize; byte mask = (byte)(1 << (7 - (sectorInBlock % 8))); bool readFromParent = (_blockBitmaps[block][sectorInBlock / 8] & mask) == 0; int numSectors = 1; while (numSectors < toReadSectors) { mask = (byte)(1 << (7 - ((sectorInBlock + numSectors) % 8))); if (((_blockBitmaps[block][(sectorInBlock + numSectors) / 8] & mask) == 0) != readFromParent) { break; } ++numSectors; } toRead = numSectors * Utilities.SectorSize; if (readFromParent) { _parentStream.Position = _position; Utilities.ReadFully(_parentStream, buffer, offset + numRead, toRead); } else { _fileStream.Position = ((((long)_blockAllocationTable[block]) + sectorInBlock) * Utilities.SectorSize) + _blockBitmapSize; if (Utilities.ReadFully(_fileStream, buffer, offset + numRead, toRead) != toRead) { throw new IOException("Failed to read entire chunk"); } } numRead += toRead; _position += toRead; } } else { int toRead = Math.Min(maxToRead - numRead, (int)(_dynamicHeader.BlockSize - offsetInBlock)); _parentStream.Position = _position; Utilities.ReadFully(_parentStream, buffer, offset + numRead, toRead); numRead += toRead; _position += toRead; } } return numRead; } public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); long effectiveOffset = offset; if (origin == SeekOrigin.Current) { effectiveOffset += _position; } else if (origin == SeekOrigin.End) { effectiveOffset += _length; } _atEof = false; if (effectiveOffset < 0) { throw new IOException("Attempt to move before beginning of disk"); } else { _position = effectiveOffset; return _position; } } public override void SetLength(long value) { CheckDisposed(); throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { CheckDisposed(); if (!CanWrite) { throw new IOException("Attempt to write to read-only stream"); } if (_position + count > _length) { throw new IOException("Attempt to write beyond end of the stream"); } int numWritten = 0; while (numWritten < count) { long block = _position / _dynamicHeader.BlockSize; uint offsetInBlock = (uint)(_position % _dynamicHeader.BlockSize); if (!PopulateBlockBitmap(block)) { AllocateBlock(block); } int sectorInBlock = (int)(offsetInBlock / Utilities.SectorSize); int offsetInSector = (int)(offsetInBlock % Utilities.SectorSize); int toWrite = (int)Math.Min(count - numWritten, _dynamicHeader.BlockSize - offsetInBlock); bool blockBitmapDirty = false; // Need to read - we're not handling a full sector if (offsetInSector != 0 || toWrite < Utilities.SectorSize) { // Reduce the write to just the end of the current sector toWrite = Math.Min(count - numWritten, Utilities.SectorSize - offsetInSector); byte sectorMask = (byte)(1 << (7 - (sectorInBlock % 8))); long sectorStart = ((((long)_blockAllocationTable[block]) + sectorInBlock) * Utilities.SectorSize) + _blockBitmapSize; // Get the existing sector data (if any), or otherwise the parent's content byte[] sectorBuffer; if ((_blockBitmaps[block][sectorInBlock / 8] & sectorMask) != 0) { _fileStream.Position = sectorStart; sectorBuffer = Utilities.ReadFully(_fileStream, Utilities.SectorSize); } else { _parentStream.Position = (_position / Utilities.SectorSize) * Utilities.SectorSize; sectorBuffer = Utilities.ReadFully(_parentStream, Utilities.SectorSize); } // Overlay as much data as we have for this sector Array.Copy(buffer, offset + numWritten, sectorBuffer, offsetInSector, toWrite); // Write the sector back _fileStream.Position = sectorStart; _fileStream.Write(sectorBuffer, 0, Utilities.SectorSize); // Update the in-memory block bitmap if ((_blockBitmaps[block][sectorInBlock / 8] & sectorMask) == 0) { _blockBitmaps[block][sectorInBlock / 8] |= sectorMask; blockBitmapDirty = true; } } else { // Processing at least one whole sector, just write (after making sure to trim any partial sectors from the end)... toWrite = (toWrite / Utilities.SectorSize) * Utilities.SectorSize; _fileStream.Position = ((((long)_blockAllocationTable[block]) + sectorInBlock) * Utilities.SectorSize) + _blockBitmapSize; _fileStream.Write(buffer, offset + numWritten, toWrite); // Update all of the bits in the block bitmap for (int i = offset; i < offset + toWrite; i += Utilities.SectorSize) { byte sectorMask = (byte)(1 << (7 - (sectorInBlock % 8))); if ((_blockBitmaps[block][sectorInBlock / 8] & sectorMask) == 0) { _blockBitmaps[block][sectorInBlock / 8] |= sectorMask; blockBitmapDirty = true; } sectorInBlock++; } } if (blockBitmapDirty) { WriteBlockBitmap(block); } numWritten += toWrite; _position += toWrite; } _atEof = false; } public override IEnumerable<StreamExtent> GetExtentsInRange(long start, long count) { CheckDisposed(); long maxCount = Math.Min(Length, start + count) - start; if (maxCount < 0) { return new StreamExtent[0]; } var parentExtents = _parentStream.GetExtentsInRange(start, maxCount); var result = StreamExtent.Union(LayerExtents(start, maxCount), parentExtents); result = StreamExtent.Intersect(result, new StreamExtent[] { new StreamExtent(start, maxCount) }); return result; } protected override void Dispose(bool disposing) { try { if (disposing) { UpdateFooter(); if (_ownsParentStream == Ownership.Dispose && _parentStream != null) { _parentStream.Dispose(); _parentStream = null; } } } finally { base.Dispose(disposing); } } private IEnumerable<StreamExtent> LayerExtents(long start, long count) { long maxPos = start + count; long pos = FindNextPresentSector(Utilities.RoundDown(start, Utilities.SectorSize), maxPos); while (pos < maxPos) { long end = FindNextAbsentSector(pos, maxPos); yield return new StreamExtent(pos, end - pos); pos = FindNextPresentSector(end, maxPos); } } private long FindNextPresentSector(long pos, long maxPos) { bool foundStart = false; while (pos < maxPos && !foundStart) { long block = pos / _dynamicHeader.BlockSize; if (!PopulateBlockBitmap(block)) { pos += _dynamicHeader.BlockSize; } else { uint offsetInBlock = (uint)(pos % _dynamicHeader.BlockSize); int sectorInBlock = (int)(offsetInBlock / Utilities.SectorSize); if (_blockBitmaps[block][sectorInBlock / 8] == 0) { pos += (8 - (sectorInBlock % 8)) * Utilities.SectorSize; } else { byte mask = (byte)(1 << (7 - (sectorInBlock % 8))); if ((_blockBitmaps[block][sectorInBlock / 8] & mask) != 0) { foundStart = true; } else { pos += Utilities.SectorSize; } } } } return Math.Min(pos, maxPos); } private long FindNextAbsentSector(long pos, long maxPos) { bool foundEnd = false; while (pos < maxPos && !foundEnd) { long block = pos / _dynamicHeader.BlockSize; if (!PopulateBlockBitmap(block)) { foundEnd = true; } else { uint offsetInBlock = (uint)(pos % _dynamicHeader.BlockSize); int sectorInBlock = (int)(offsetInBlock / Utilities.SectorSize); if (_blockBitmaps[block][sectorInBlock / 8] == 0xFF) { pos += (8 - (sectorInBlock % 8)) * Utilities.SectorSize; } else { byte mask = (byte)(1 << (7 - (sectorInBlock % 8))); if ((_blockBitmaps[block][sectorInBlock / 8] & mask) == 0) { foundEnd = true; } else { pos += Utilities.SectorSize; } } } } return Math.Min(pos, maxPos); } private void ReadBlockAllocationTable() { _fileStream.Position = _dynamicHeader.TableOffset; byte[] data = Utilities.ReadFully(_fileStream, _dynamicHeader.MaxTableEntries * 4); uint[] bat = new uint[_dynamicHeader.MaxTableEntries]; for (int i = 0; i < _dynamicHeader.MaxTableEntries; ++i) { bat[i] = Utilities.ToUInt32BigEndian(data, i * 4); } _blockAllocationTable = bat; } private bool PopulateBlockBitmap(long block) { if (_blockBitmaps[block] != null) { // Nothing to do... return true; } if (_blockAllocationTable[block] == uint.MaxValue) { // No such block stored... return false; } // Read in bitmap _fileStream.Position = ((long)_blockAllocationTable[block]) * Utilities.SectorSize; _blockBitmaps[block] = Utilities.ReadFully(_fileStream, _blockBitmapSize); return true; } private void AllocateBlock(long block) { if (_blockAllocationTable[block] != uint.MaxValue) { throw new ArgumentException("Attempt to allocate existing block"); } _newBlocksAllocated = true; long newBlockStart = _nextBlockStart; // Create and write new sector bitmap byte[] bitmap = new byte[_blockBitmapSize]; _fileStream.Position = newBlockStart; _fileStream.Write(bitmap, 0, _blockBitmapSize); _blockBitmaps[block] = bitmap; _nextBlockStart += _blockBitmapSize + _dynamicHeader.BlockSize; if (_fileStream.Length < _nextBlockStart) { _fileStream.SetLength(_nextBlockStart); } // Update the BAT entry for the new block byte[] entryBuffer = new byte[4]; Utilities.WriteBytesBigEndian((uint)(newBlockStart / 512), entryBuffer, 0); _fileStream.Position = _dynamicHeader.TableOffset + (block * 4); _fileStream.Write(entryBuffer, 0, 4); _blockAllocationTable[block] = (uint)(newBlockStart / 512); if (_autoCommitFooter) { UpdateFooter(); } } private void WriteBlockBitmap(long block) { _fileStream.Position = ((long)_blockAllocationTable[block]) * Utilities.SectorSize; _fileStream.Write(_blockBitmaps[block], 0, _blockBitmapSize); } private void CheckDisposed() { if (_parentStream == null) { throw new ObjectDisposedException("DynamicStream", "Attempt to use closed stream"); } } private void UpdateFooter() { if (_newBlocksAllocated) { // Update the footer at the end of the file (if we allocated new blocks). if (_footerCache == null) { _fileStream.Position = 0; _footerCache = Utilities.ReadFully(_fileStream, Utilities.SectorSize); } _fileStream.Position = _nextBlockStart; _fileStream.Write(_footerCache, 0, _footerCache.Length); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using Xunit; using Tests.HashSet_HashSetTestSupport; using Tests.HashSet_SetCollectionComparerTests; using Tests.HashSet_HashSet_ICollectionT_Add_T; namespace Tests { public class HashSet_ICollectionAddTest { #region Set/Item Relationship Tests //Test 1: Set/Item Relationship Test 1: set is Empty [Fact] public static void ICollectionAdd_Test1() { HashSet<Item> hashSet = new HashSet<Item>(); Item item = new Item(1); ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { item }, EqualityComparer<Item>.Default); } //Test 2: Set/Item Relationship Test 2: set is single-item, item in set [Fact] public static void ICollectionAdd_Test2() { Item x = new Item(2); HashSet<Item> hashSet = new HashSet<Item>(); hashSet.Add(x); Item item = x; ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { item }, EqualityComparer<Item>.Default); } //Test 3: Set/Item Relationship Test 3: set is single-item, item not in set [Fact] public static void ICollectionAdd_Test3() { Item x = new Item(2); HashSet<Item> hashSet = new HashSet<Item>(new ItemEqualityComparer()); hashSet.Add(x); Item item = new Item(3); ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { item, new Item(2) }, hashSet.Comparer); } //Test 4: Set/Item Relationship Test 4: set is multi-item, item in set [Fact] public static void ICollectionAdd_Test4() { Item x = new Item(2); Item y = new Item(4); Item z = new Item(-23); HashSet<Item> hashSet = new HashSet<Item>(new ItemEqualityComparer()); hashSet.Add(x); hashSet.Add(y); hashSet.Add(z); Item item = z; ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { item, new Item(2), new Item(4) }, hashSet.Comparer); } //Test 5: Set/Item Relationship Test 5: set is multi-item, item not in set [Fact] public static void ICollectionAdd_Test5() { Item x = new Item(2); Item y = new Item(4); Item z = new Item(-23); HashSet<Item> hashSet = new HashSet<Item>(new ItemEqualityComparer()); hashSet.Add(x); hashSet.Add(y); hashSet.Add(z); Item item = new Item(0); ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), item, new Item(2), new Item(4) }, hashSet.Comparer); } //Test 6: Set/Item Relationship Test 6: Item is the set and item is in the set [Fact] public static void ICollectionAdd_Test6() { List<int> item1 = new List<int>(new int[] { 1, 2 }); List<int> item2 = new List<int>(new int[] { 2, -1 }); IEnumerableEqualityComparer comparer = new IEnumerableEqualityComparer(); HashSet<IEnumerable> hashSet = new HashSet<IEnumerable>(comparer); comparer.setSelf(hashSet); hashSet.Add(item1); hashSet.Add(item2); hashSet.Add(hashSet); IEnumerable item = hashSet; ((ICollection<IEnumerable>)hashSet).Add(item); HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2, item }, hashSet.Comparer); } //Test 7: Set/Item Relationship Test 7: Item is the set and item is not in the set [Fact] public static void ICollectionAdd_Test7() { List<int> item1 = new List<int>(new int[] { 1, 2 }); List<int> item2 = new List<int>(new int[] { 2, -1 }); IEnumerableEqualityComparer comparer = new IEnumerableEqualityComparer(); HashSet<IEnumerable> hashSet = new HashSet<IEnumerable>(comparer); comparer.setSelf(hashSet); hashSet.Add(item1); hashSet.Add(item2); IEnumerable item = hashSet; ((ICollection<IEnumerable>)hashSet).Add(item); HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2, item }, hashSet.Comparer); } //Test 8: Set/Item Relationship Test 8: Item is Default<T> and in set. T is a numeric type [Fact] public static void ICollectionAdd_Test8() { int x = 0; HashSet<int> hashSet = new HashSet<int>(new int[] { 1, 2, 3, 4, x, 6, 7 }); int item = x; ((ICollection<int>)hashSet).Add(item); HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 6, 7, 4, 0 }, hashSet.Comparer); } //Test 9: Set/Item Relationship Test 9: Item is Default<T> and in set. T is a reference type [Fact] public static void ICollectionAdd_Test9() { Item x = null; Item item1 = new Item(3); Item item2 = new Item(-3); HashSet<Item> hashSet = new HashSet<Item>(new ItemEqualityComparer()); hashSet.Add(item1); hashSet.Add(item2); hashSet.Add(x); Item item = x; ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { item, new Item(3), new Item(-3) }, hashSet.Comparer); } //Test 10: Set/Item Relationship Test 10: Item is Default<T> and not in set. T is a numeric type [Fact] public static void ICollectionAdd_Test10() { int x = 0; HashSet<int> hashSet = new HashSet<int>(new int[] { 1, 2, 3, 4, 5, 6, 7 }); int item = x; ((ICollection<int>)hashSet).Add(item); HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 6, 7, 4, 0, 5 }, hashSet.Comparer); } //Test 11: Set/Item Relationship Test 11: Item is Default<T> and not in set. T is a reference type [Fact] public static void ICollectionAdd_Test11() { Item x = null; Item item1 = new Item(3); Item item2 = new Item(-3); HashSet<Item> hashSet = new HashSet<Item>(new ItemEqualityComparer()); hashSet.Add(item1); hashSet.Add(item2); Item item = x; ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { item, new Item(3), new Item(-3) }, hashSet.Comparer); } //Test 12: Set/Item Relationship Test 12: Item is equal to an item in set but different [Fact] public static void ICollectionAdd_Test12() { Item x1 = new Item(1); Item x2 = new Item(1); Item item1 = new Item(2); Item item2 = new Item(3); HashSet<Item> hashSet = new HashSet<Item>(new ItemEqualityComparer()); hashSet.Add(x1); hashSet.Add(item1); hashSet.Add(item2); Item item = x2; ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { item, new Item(3), new Item(2) }, hashSet.Comparer); } //Test 13: Set/Item Relationship Test 13: Item shares hash value with unequal item in set [Fact] public static void ICollectionAdd_Test13() { Item x1 = new Item(1); Item x2 = new Item(-1); Item item1 = new Item(2); Item item2 = new Item(3); HashSet<Item> hashSet = new HashSet<Item>(new ItemAbsoluteEqualityComparer()); hashSet.Add(x1); hashSet.Add(item1); hashSet.Add(item2); Item item = x2; ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { item, new Item(3), new Item(2), new Item(1) }, hashSet.Comparer); } //Test 14: Set/Item Relationship Test 14: Item was previously in set but not currently [Fact] public static void ICollectionAdd_Test14() { Item x1 = new Item(1); Item item1 = new Item(2); Item item2 = new Item(3); HashSet<Item> hashSet = new HashSet<Item>(new ItemEqualityComparer()); hashSet.Add(x1); hashSet.Add(item1); hashSet.Add(item2); hashSet.Remove(x1); Item item = x1; ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { item, new Item(3), new Item(2) }, hashSet.Comparer); } //Test 15: Set/Item Relationship Test 15: Item was previously removed from set but in it currently [Fact] public static void ICollectionAdd_Test15() { Item x1 = new Item(1); Item item1 = new Item(2); Item item2 = new Item(3); HashSet<Item> hashSet = new HashSet<Item>(new ItemEqualityComparer()); hashSet.Add(x1); hashSet.Add(item1); hashSet.Add(item2); hashSet.Remove(x1); hashSet.Add(x1); Item item = x1; ((ICollection<Item>)hashSet).Add(item); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { item, new Item(3), new Item(2) }, hashSet.Comparer); } #endregion #region Set/Item Comparer Tests (Tests 16-20 ) //Test 16: Set/Item Comparer Test 1: item same as element in set by default comparer, different by sets comparer - set contains item that is equal by sets comparer [Fact] public static void ICollectionAdd_Test16() { HashSet<ValueItem> hashSet; ValueItem item; SetItemComparerTests.SetupTest1(out hashSet, out item); ((ICollection<ValueItem>)hashSet).Add(item); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item, new ValueItem(5, 4), new ValueItem(5, -5) }, hashSet.Comparer); } //Test 17: Set/Item Comparer Test 2: item same as element in set by default comparer, different by sets comparer - set does not contain item that is equal by sets comparer [Fact] public static void ICollectionAdd_Test17() { HashSet<ValueItem> hashSet; ValueItem item; SetItemComparerTests.SetupTest2(out hashSet, out item); ((ICollection<ValueItem>)hashSet).Add(item); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item, new ValueItem(5, 4), new ValueItem(5, -5), new ValueItem(-20, -20) }, hashSet.Comparer); } //Test 18: Set/Item Comparer Test 3: item same as element in set by sets comparer, different by default comparer - set contains item that is equal by default comparer [Fact] public static void ICollectionAdd_Test18() { HashSet<ValueItem> hashSet; ValueItem item; SetItemComparerTests.SetupTest3(out hashSet, out item); ((ICollection<ValueItem>)hashSet).Add(item); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item, new ValueItem(5, 4), new ValueItem(5, -5) }, hashSet.Comparer); } //Test 19: Set/Item Comparer Test 4: item same as element in set by sets comparer, different by default comparer - set does not contain item that is equal by default comparer [Fact] public static void ICollectionAdd_Test19() { HashSet<ValueItem> hashSet; ValueItem item; SetItemComparerTests.SetupTest4(out hashSet, out item); ((ICollection<ValueItem>)hashSet).Add(item); HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item, new ValueItem(5, 4), new ValueItem(5, -5) }, hashSet.Comparer); } //Test 20: Set/Item Comparer Test 5: item contains set and item in set with GetSetComparer<T> as comparer [Fact] public static void ICollectionAdd_Test20() { HashSet<HashSet<IEnumerable>> hashSet; HashSet<IEnumerable> item; ValueItem itemn4 = new ValueItem(-4, -4); ValueItem itemn3 = new ValueItem(-3, -3); ValueItem itemn2 = new ValueItem(-2, -2); ValueItem itemn1 = new ValueItem(-1, -1); ValueItem item1 = new ValueItem(1, 1); ValueItem item2 = new ValueItem(2, 2); ValueItem item3 = new ValueItem(3, 3); ValueItem item4 = new ValueItem(4, 4); HashSet<IEnumerable> itemhs1 = new HashSet<IEnumerable>(new ValueItem[] { item1, item2, item3, item4 }); HashSet<IEnumerable> itemhs2 = new HashSet<IEnumerable>(new ValueItem[] { itemn1, itemn2, itemn3, itemn4 }); SetItemComparerTests.SetupTest5(out hashSet, out item); ((ICollection<HashSet<IEnumerable>>)hashSet).Add(item); HashSet<IEnumerable>[] expected = new HashSet<IEnumerable>[] { itemhs1, itemhs2, item }; HashSet<IEnumerable>[] actual = new HashSet<IEnumerable>[3]; hashSet.CopyTo(actual, 0, 3); Assert.Equal(3, hashSet.Count); //"Expect them to be equal." HashSetTestSupport.HashSetContains(actual, expected); } #endregion //Test 21: Add multiple items [Fact] public static void ICollectionAdd_Test21() { HashSet<int> hashSet = new HashSet<int>(); ((ICollection<int>)hashSet).Add(3); ((ICollection<int>)hashSet).Add(-3); ((ICollection<int>)hashSet).Add(-42); ((ICollection<int>)hashSet).Add(int.MinValue); ((ICollection<int>)hashSet).Add(int.MaxValue); ((ICollection<int>)hashSet).Add(0); HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { int.MinValue, -42, -3, 0, 3, int.MaxValue }, EqualityComparer<int>.Default); } //Test 22: Add many items with the same hash value [Fact] public static void ICollectionAdd_Test22() { HashSet<Item> hashSet = new HashSet<Item>(new HashAlwaysZeroItemComparer()); ((ICollection<Item>)hashSet).Add(new Item(3)); ((ICollection<Item>)hashSet).Add(new Item(-3)); ((ICollection<Item>)hashSet).Add(new Item(-42)); ((ICollection<Item>)hashSet).Add(new Item(int.MinValue)); ((ICollection<Item>)hashSet).Add(new Item(int.MaxValue)); ((ICollection<Item>)hashSet).Add(new Item(0)); HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(int.MinValue), new Item(-42), new Item(-3), new Item(0), new Item(3), new Item(int.MaxValue) }, hashSet.Comparer); } } namespace HashSet_HashSet_ICollectionT_Add_T { #region Helper Classes public class HashAlwaysZeroItemComparer : IEqualityComparer<Item> { public bool Equals(Item x, Item y) { if ((x != null) & (y != null)) return (x.x == y.x); else return ((y == null) & (x == null)); } public int GetHashCode(Item x) { return 0; } } } #endregion }
// ***************************************************************************** // // (c) Crownwood Consulting Limited 2002-2003 // All rights reserved. The software and associated documentation // supplied hereunder are the proprietary information of Crownwood Consulting // Limited, Crownwood, Bracknell, Berkshire, England and are supplied subject // to licence terms. // // Magic Version 1.7.4.0 www.dotnetmagic.com // ***************************************************************************** using System; using System.IO; using System.Xml; using System.Text; using System.Data; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Crownwood.Magic.Win32; using Crownwood.Magic.Common; using Crownwood.Magic.Controls; namespace Crownwood.Magic.Controls { [ToolboxBitmap(typeof(TabbedGroups))] public class TabbedGroups : UserControl, ISupportInitialize, IMessageFilter { public class DragProvider { protected object _tag; public DragProvider() { _tag = null; } public DragProvider(object tag) { _tag = tag; } public object Tag { get { return _tag; } set { _tag = value; } } } public enum DisplayTabModes { HideAll, ShowAll, ShowActiveLeaf, ShowMouseOver, ShowActiveAndMouseOver } public enum CompactFlags { RemoveEmptyTabLeaf = 1, RemoveEmptyTabSequence = 2, ReduceSingleEntries = 4, ReduceSameDirection = 8, All = 15 } // Instance fields protected int _numLeafs; protected int _defMinWidth; protected int _defMinHeight; protected int _resizeBarVector; protected int _suspendLeafCount; protected string _closeMenuText; protected string _prominentMenuText; protected string _rebalanceMenuText; protected string _movePreviousMenuText; protected string _moveNextMenuText; protected string _newVerticalMenuText; protected string _newHorizontalMenuText; protected ImageList _imageList; protected bool _dirty; protected bool _autoCalculateDirty; protected bool _saveControls; protected bool _initializing; protected bool _atLeastOneLeaf; protected bool _autoCompact; protected bool _compacting; protected bool _resizeBarLock; protected bool _layoutLock; protected bool _pageCloseWhenEmpty; protected Color _resizeBarColor; protected Shortcut _closeShortcut; protected Shortcut _prominentShortcut; protected Shortcut _rebalanceShortcut; protected Shortcut _movePreviousShortcut; protected Shortcut _moveNextShortcut; protected Shortcut _splitVerticalShortcut; protected Shortcut _splitHorizontalShortcut; protected Shortcut _nextTabShortcut; protected CompactFlags _compactOptions; protected DisplayTabModes _displayTabMode; protected TabGroupLeaf _prominentLeaf; protected TabGroupLeaf _activeLeaf; protected TabGroupSequence _root; protected VisualStyle _style; // Delegates for events public delegate void TabControlCreatedHandler(TabbedGroups tg, Controls.TabControl tc); public delegate void PageCloseRequestHandler(TabbedGroups tg, TGCloseRequestEventArgs e); public delegate void PageContextMenuHandler(TabbedGroups tg, TGContextMenuEventArgs e); public delegate void GlobalSavingHandler(TabbedGroups tg, XmlTextWriter xmlOut); public delegate void GlobalLoadingHandler(TabbedGroups tg, XmlTextReader xmlIn); public delegate void PageSavingHandler(TabbedGroups tg, TGPageSavingEventArgs e); public delegate void PageLoadingHandler(TabbedGroups tg, TGPageLoadingEventArgs e); public delegate void ExternalDropHandler(TabbedGroups tg, TabGroupLeaf tgl, Controls.TabControl tc, DragProvider dp); // Instance events public event TabControlCreatedHandler TabControlCreated; public event PageCloseRequestHandler PageCloseRequest; public event PageContextMenuHandler PageContextMenu; public event GlobalSavingHandler GlobalSaving; public event GlobalLoadingHandler GlobalLoading; public event PageSavingHandler PageSaving; public event PageLoadingHandler PageLoading; public event EventHandler ProminentLeafChanged; public event EventHandler ActiveLeafChanged; public event EventHandler DirtyChanged; public event ExternalDropHandler ExternalDrop; public TabbedGroups() { InternalConstruct(VisualStyle.IDE); } public TabbedGroups(VisualStyle style) { InternalConstruct(style); } protected void InternalConstruct(VisualStyle style) { // Prevent flicker with double buffering and all painting inside WM_PAINT SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true); // We want to act as a drop target this.AllowDrop = true; // Remember parameters _style = style; // Define initial state _numLeafs = 0; _compacting = false; _initializing = false; _suspendLeafCount = 0; // Create the root sequence that always exists _root = new TabGroupSequence(this); // Define default settings ResetProminentLeaf(); ResetResizeBarVector(); ResetResizeBarColor(); ResetResizeBarLock(); ResetLayoutLock(); ResetCompactOptions(); ResetDefaultGroupMinimumWidth(); ResetDefaultGroupMinimumHeight(); ResetActiveLeaf(); ResetAutoCompact(); ResetAtLeastOneLeaf(); ResetCloseMenuText(); ResetProminentMenuText(); ResetRebalanceMenuText(); ResetMovePreviousMenuText(); ResetMoveNextMenuText(); ResetNewVerticalMenuText(); ResetNewHorizontalMenuText(); ResetCloseShortcut(); ResetProminentShortcut(); ResetRebalanceShortcut(); ResetMovePreviousShortcut(); ResetMoveNextShortcut(); ResetSplitVerticalShortcut(); ResetSplitHorizontalShortcut(); ResetImageList(); ResetDisplayTabMode(); ResetSaveControls(); ResetAutoCalculateDirty(); ResetDirty(); ResetPageCloseWhenEmpty(); // Add ourself to the application filtering list // (to snoop for shortcut combinations) Application.AddMessageFilter(this); } protected override void Dispose( bool disposing ) { if (disposing) { // Remove message filter to remove circular reference Application.RemoveMessageFilter(this); } base.Dispose(disposing); } [Category("TabbedGroups")] [DefaultValue(typeof(VisualStyle), "IDE")] public VisualStyle Style { get { return _style; } set { if (_style != value) { _style = value; // Propogate to all children Notify(TabGroupBase.NotifyCode.StyleChanged); } } } public void ResetStyle() { Style = VisualStyle.IDE; } [Browsable(false)] public TabGroupSequence RootSequence { get { return _root; } } [Category("TabbedGroups")] [DefaultValue(-1)] public int ResizeBarVector { get { return _resizeBarVector; } set { if (_resizeBarVector != value) { _resizeBarVector = value; // Propogate to all children Notify(TabGroupBase.NotifyCode.ResizeBarVectorChanged); } } } public void ResetResizeBarVector() { ResizeBarVector = -1; } [Category("TabbedGroups")] public Color ResizeBarColor { get { return _resizeBarColor; } set { if (!_resizeBarColor.Equals(value)) { _resizeBarColor = value; // Propogate to all children Notify(TabGroupBase.NotifyCode.ResizeBarColorChanged); } } } protected bool ShouldSerializeResizeBackColor() { return _resizeBarColor != base.BackColor; } public void ResetResizeBarColor() { ResizeBarColor = base.BackColor; } [Category("TabbedGroups")] [DefaultValue(false)] public bool ResizeBarLock { get { return _resizeBarLock; } set { _resizeBarLock = value; } } public void ResetResizeBarLock() { ResizeBarLock = false; } [Category("TabbedGroups")] [DefaultValue(false)] public bool LayoutLock { get { return _layoutLock; } set { _layoutLock = value; } } public void ResetLayoutLock() { LayoutLock = false; } [Category("TabbedGroups")] public TabGroupLeaf ProminentLeaf { get { return _prominentLeaf; } set { if (_prominentLeaf != value) { _prominentLeaf = value; // Mark layout as dirty if (_autoCalculateDirty) _dirty = true; // Propogate to all children Notify(TabGroupBase.NotifyCode.ProminentChanged); OnProminentLeafChanged(EventArgs.Empty); } } } public void ResetProminentLeaf() { ProminentLeaf = null; } [Category("TabbedGroups")] [DefaultValue(typeof(CompactFlags), "All")] public CompactFlags CompactOptions { get { return _compactOptions; } set { _compactOptions = value; } } public void ResetCompactOptions() { CompactOptions = CompactFlags.All; } [Category("TabbedGroups")] [DefaultValue(4)] public int DefaultGroupMinimumWidth { get { return _defMinWidth; } set { if (_defMinWidth != value) { _defMinWidth = value; // Propogate to all children Notify(TabGroupBase.NotifyCode.MinimumSizeChanged); } } } public void ResetDefaultGroupMinimumWidth() { DefaultGroupMinimumWidth = 4; } [Category("TabbedGroups")] [DefaultValue(4)] public int DefaultGroupMinimumHeight { get { return _defMinHeight; } set { if (_defMinHeight != value) { _defMinHeight = value; // Propogate to all children Notify(TabGroupBase.NotifyCode.MinimumSizeChanged); } } } public void ResetDefaultGroupMinimumHeight() { DefaultGroupMinimumHeight = 4; } [Localizable(true)] [Category("Text String")] [DefaultValue("&Close")] public string CloseMenuText { get { return _closeMenuText; } set { _closeMenuText = value; } } public void ResetCloseMenuText() { CloseMenuText = "&Close"; } [Localizable(true)] [Category("Text String")] [DefaultValue("Pro&minent")] public string ProminentMenuText { get { return _prominentMenuText; } set { _prominentMenuText = value; } } public void ResetProminentMenuText() { ProminentMenuText = "Pro&minent"; } [Localizable(true)] [Category("Text String")] [DefaultValue("&Rebalance")] public string RebalanceMenuText { get { return _rebalanceMenuText; } set { _rebalanceMenuText = value; } } public void ResetRebalanceMenuText() { RebalanceMenuText = "&Rebalance"; } [Localizable(true)] [Category("Text String")] [DefaultValue("Move to &Previous Tab Group")] public string MovePreviousMenuText { get { return _movePreviousMenuText; } set { _movePreviousMenuText = value; } } public void ResetMovePreviousMenuText() { MovePreviousMenuText = "Move to &Previous Tab Group"; } [Localizable(true)] [Category("Text String")] [DefaultValue("Move to &Next Tab Group")] public string MoveNextMenuText { get { return _moveNextMenuText; } set { _moveNextMenuText = value; } } public void ResetMoveNextMenuText() { MoveNextMenuText = "Move to &Next Tab Group"; } [Localizable(true)] [Category("Text String")] [DefaultValue("New &Vertical Tab Group")] public string NewVerticalMenuText { get { return _newVerticalMenuText; } set { _newVerticalMenuText = value; } } public void ResetNewVerticalMenuText() { NewVerticalMenuText = "New &Vertical Tab Group"; } [Localizable(true)] [Category("Text String")] [DefaultValue("New &Horizontal Tab Group")] public string NewHorizontalMenuText { get { return _newHorizontalMenuText; } set { _newHorizontalMenuText = value; } } public void ResetNewHorizontalMenuText() { NewHorizontalMenuText = "New &Horizontal Tab Group"; } [Category("Shortcuts")] public Shortcut CloseShortcut { get { return _closeShortcut; } set { _closeShortcut = value; } } protected bool ShouldSerializeCloseShortcut() { return !_closeShortcut.Equals(Shortcut.CtrlShiftC); } public void ResetCloseShortcut() { CloseShortcut = Shortcut.CtrlShiftC; } [Category("Shortcuts")] public Shortcut ProminentShortcut { get { return _prominentShortcut; } set { _prominentShortcut = value; } } protected bool ShouldSerializeProminentShortcut() { return !_prominentShortcut.Equals(Shortcut.CtrlShiftT); } public void ResetProminentShortcut() { ProminentShortcut = Shortcut.CtrlShiftT; } [Category("Shortcuts")] public Shortcut RebalanceShortcut { get { return _rebalanceShortcut; } set { _rebalanceShortcut = value; } } protected bool ShouldSerializeRebalanceShortcut() { return !_rebalanceShortcut.Equals(Shortcut.CtrlShiftR); } public void ResetRebalanceShortcut() { RebalanceShortcut = Shortcut.CtrlShiftR; } [Category("Shortcuts")] public Shortcut MovePreviousShortcut { get { return _movePreviousShortcut; } set { _movePreviousShortcut = value; } } protected bool ShouldSerializeMovePreviousShortcut() { return !_movePreviousShortcut.Equals(Shortcut.CtrlShiftP); } public void ResetMovePreviousShortcut() { MovePreviousShortcut = Shortcut.CtrlShiftP; } [Category("Shortcuts")] public Shortcut MoveNextShortcut { get { return _moveNextShortcut; } set { _moveNextShortcut = value; } } protected bool ShouldSerializeMoveNextShortcut() { return !_moveNextShortcut.Equals(Shortcut.CtrlShiftN); } public void ResetMoveNextShortcut() { MoveNextShortcut = Shortcut.CtrlShiftN; } [Category("Shortcuts")] public Shortcut SplitVerticalShortcut { get { return _splitVerticalShortcut; } set { _splitVerticalShortcut = value; } } protected bool ShouldSerializeSplitVerticalShortcut() { return !_splitVerticalShortcut.Equals(Shortcut.CtrlShiftV); } public void ResetSplitVerticalShortcut() { SplitVerticalShortcut = Shortcut.CtrlShiftV; } [Category("Shortcuts")] public Shortcut SplitHorizontalShortcut { get { return _splitHorizontalShortcut; } set { _splitHorizontalShortcut = value; } } protected bool ShouldSerializeSplitHorizontalShortcut() { return !_splitHorizontalShortcut.Equals(Shortcut.CtrlShiftH); } public void ResetSplitHorizontalShortcut() { SplitHorizontalShortcut = Shortcut.CtrlShiftH; } [Category("TabbedGroups")] public ImageList ImageList { get { return _imageList; } set { if (_imageList != value) { // Propogate to all children Notify(TabGroupBase.NotifyCode.ImageListChanging); _imageList = value; // Propogate to all children Notify(TabGroupBase.NotifyCode.ImageListChanged); } } } protected bool ShouldSerializeImageList() { return _imageList != null; } public void ResetImageList() { ImageList = null; } [Category("TabbedGroups")] [DefaultValue(typeof(DisplayTabModes), "ShowAll")] public DisplayTabModes DisplayTabMode { get { return _displayTabMode; } set { if (_displayTabMode != value) { _displayTabMode = value; // Propogate to all children Notify(TabGroupBase.NotifyCode.DisplayTabMode); } } } public void ResetDisplayTabMode() { DisplayTabMode = DisplayTabModes.ShowAll; } [Category("TabbedGroups")] [DefaultValue(true)] public bool SaveControls { get { return _saveControls; } set { _saveControls = value; } } public void ResetSaveControls() { SaveControls = true; } [Category("TabbedGroups")] public bool Dirty { get { return _dirty; } set { if (_dirty != value) { _dirty = value; OnDirtyChanged(EventArgs.Empty); } } } protected bool ShouldSerializeDirty() { return false; } public void ResetDirty() { Dirty = false; } [Category("TabbedGroups")] [DefaultValue(false)] public bool PageCloseWhenEmpty { get { return _pageCloseWhenEmpty; } set { _pageCloseWhenEmpty = value; } } public void ResetPageCloseWhenEmpty() { PageCloseWhenEmpty = false; } [Category("TabbedGroups")] [DefaultValue(true)] public bool AutoCalculateDirty { get { return _autoCalculateDirty; } set { _autoCalculateDirty = value; } } public void ResetAutoCalculateDirty() { AutoCalculateDirty = true; } [Category("TabbedGroups")] public TabGroupLeaf ActiveLeaf { get { return _activeLeaf; } set { try{ //Resolution d'un bug qui fait planter la fonction if (_activeLeaf != value) { // Cannot get rid of the active leaf when there must be one if (_atLeastOneLeaf && (value == null)) return; // Mark layout as dirty if (_autoCalculateDirty) _dirty = true; // Remove selection highlight from old leaf if (_activeLeaf != null) { // Get access to the contained tab control TabControl tc = _activeLeaf.GroupControl as Controls.TabControl; // Remove bold text for the selected page tc.BoldSelectedPage = false; _activeLeaf = null; } // Set selection highlight on new active leaf if (value != null) { // Get access to the contained tab control TabControl tc = value.GroupControl as Controls.TabControl; // Remove bold text for the selected page tc.BoldSelectedPage = true; _activeLeaf = value; } // Is the tab mode dependant on the active leaf value if ((_displayTabMode == DisplayTabModes.ShowActiveLeaf) || (_displayTabMode == DisplayTabModes.ShowActiveAndMouseOver)) { // Yes, better notify a change in value so it can be applied Notify(TabGroupBase.NotifyCode.DisplayTabMode); } OnActiveLeafChanged(EventArgs.Empty); } }catch{} } } public void ResetActiveLeaf() { ActiveLeaf = null; } private bool ShouldSerializeActiveLeaf() { // Never persist this information return false; } [Category("TabbedGroups")] public bool AtLeastOneLeaf { get { return _atLeastOneLeaf; } set { if (_atLeastOneLeaf != value) { _atLeastOneLeaf = value; // Do always need at least one leaf? if (_atLeastOneLeaf) { // Is there at least one? if (_numLeafs == 0) { // No, create a default entry for the root sequence _root.AddNewLeaf(); // Update the active leaf ActiveLeaf = FirstLeaf(); // Mark layout as dirty if (_autoCalculateDirty) _dirty = true; } } else { // Are there some potential leaves not needed if (_numLeafs > 0) { // Use compaction so only needed ones are retained if (_autoCompact) Compact(); } } } } } public void ResetAtLeastOneLeaf() { AtLeastOneLeaf = true; } [Category("TabbedGroups")] [DefaultValue(true)] public bool AutoCompact { get { return _autoCompact; } set { _autoCompact = value; } } public void ResetAutoCompact() { _autoCompact = true; } public void Rebalance() { _root.Rebalance(true); } public void Rebalance(bool recurse) { _root.Rebalance(recurse); } public void Compact() { Compact(_compactOptions); } public void Compact(CompactFlags flags) { // When entries are removed because of compacting this may cause the container object // to start a compacting request. Prevent this recursion by using a simple varible. if (!_compacting) { // We never compact when loading/initializing the contents if (!_initializing) { _compacting = true; _root.Compact(flags); _compacting = false; EnforceAtLeastOneLeaf(); } } } public TabGroupLeaf FirstLeaf() { return RecursiveFindLeafInSequence(_root, true); } public TabGroupLeaf LastLeaf() { return RecursiveFindLeafInSequence(_root, false); } public TabGroupLeaf NextLeaf(TabGroupLeaf current) { // Get parent of the provided leaf TabGroupSequence tgs = current.Parent as TabGroupSequence; // Must have a valid parent sequence if (tgs != null) return RecursiveFindLeafInSequence(tgs, current, true); else return null; } public TabGroupLeaf PreviousLeaf(TabGroupLeaf current) { // Get parent of the provided leaf TabGroupSequence tgs = current.Parent as TabGroupSequence; // Must have a valid parent sequence if (tgs != null) return RecursiveFindLeafInSequence(tgs, current, false); else return null; } internal void MoveActiveToNearestFromLeaf(TabGroupBase oldLeaf) { // Must have a reference to begin movement if (oldLeaf != null) { // Find the parent sequence of leaf, remember that a // leaf must be contained within a sequence instance TabGroupSequence tgs = oldLeaf.Parent as TabGroupSequence; // Must be valid, but had better check anyway if (tgs != null) { // Move relative to given base in the sequence MoveActiveInSequence(tgs, oldLeaf); } } } internal void MoveActiveToNearestFromSequence(TabGroupSequence tgs) { // Is active leaf being moved from root sequence if (_root == tgs) { // Then make nothing active ActiveLeaf = null; } else { // Find the parent sequence of given sequence TabGroupSequence tgsParent = tgs.Parent as TabGroupSequence; // Must be valid, but had better check anyway if (tgs != null) { // Move relative to given base in the sequence MoveActiveInSequence(tgsParent, tgs); } } } public virtual void OnTabControlCreated(Controls.TabControl tc) { // Only modify leaf count when not suspended if (_suspendLeafCount == 0) { // Remember how many leafs there are _numLeafs++; } // Define default values tc.Appearance = Magic.Controls.TabControl.VisualAppearance.MultiDocument; tc.BoldSelectedPage = false; tc.DragOverSelect = false; tc.IDEPixelBorder = true; tc.ImageList = _imageList; tc.Style = _style; // Apply the current display tab mode setting switch(_displayTabMode) { case TabbedGroups.DisplayTabModes.ShowAll: tc.HideTabsMode = Magic.Controls.TabControl.HideTabsModes.ShowAlways; break; case TabbedGroups.DisplayTabModes.HideAll: tc.HideTabsMode = Magic.Controls.TabControl.HideTabsModes.HideAlways; break; } // Has anyone registered for the event? if (TabControlCreated != null) TabControlCreated(this, tc); } public virtual void OnPageCloseRequested(TGCloseRequestEventArgs e) { // Has anyone registered for the event? if (PageCloseRequest != null) PageCloseRequest(this, e); } public virtual void OnPageContextMenu(TGContextMenuEventArgs e) { // Has anyone registered for the event? if (PageContextMenu != null) PageContextMenu(this, e); } public virtual void OnGlobalSaving(XmlTextWriter xmlOut) { // Has anyone registered for the event? if (GlobalSaving != null) GlobalSaving(this, xmlOut); } public virtual void OnGlobalLoading(XmlTextReader xmlIn) { // Has anyone registered for the event? if (GlobalLoading != null) GlobalLoading(this, xmlIn); } public virtual void OnPageSaving(TGPageSavingEventArgs e) { // Has anyone registered for the event? if (PageSaving != null) PageSaving(this, e); } public virtual void OnPageLoading(TGPageLoadingEventArgs e) { // Has anyone registered for the event? if (PageLoading != null) PageLoading(this, e); } public virtual void OnProminentLeafChanged(EventArgs e) { // Has anyone registered for the event? if (ProminentLeafChanged != null) ProminentLeafChanged(this, e); } public virtual void OnActiveLeafChanged(EventArgs e) { // Has anyone registered for the event? if (ActiveLeafChanged != null) ActiveLeafChanged(this, e); } public virtual void OnDirtyChanged(EventArgs e) { // Has anyone registered for the event? if (DirtyChanged != null) DirtyChanged(this, e); } public virtual void OnExternalDrop(TabGroupLeaf tgl, Controls.TabControl tc, DragProvider dp) { // Has anyone registered for the event? if (ExternalDrop != null) ExternalDrop(this, tgl, tc, dp); } public void BeginInit() { _initializing = true; } public void EndInit() { _initializing = false; // If don't need a default leaf then compact to get rid of extras if (AtLeastOneLeaf == false) Compact(); // Inform the root sequence to reposition itself _root.Reposition(); } public bool Initializing { get { return _initializing; } } public byte[] SaveConfigToArray() { return SaveConfigToArray(Encoding.Unicode); } public byte[] SaveConfigToArray(Encoding encoding) { // Create a memory based stream MemoryStream ms = new MemoryStream(); // Save into the file stream SaveConfigToStream(ms, encoding); // Must remember to close ms.Close(); // Return an array of bytes that contain the streamed XML return ms.GetBuffer(); } public void SaveConfigToFile(string filename) { SaveConfigToFile(filename, Encoding.Unicode); } public void SaveConfigToFile(string filename, Encoding encoding) { // Create/Overwrite existing file FileStream fs = new FileStream(filename, FileMode.Create); // Save into the file stream SaveConfigToStream(fs, encoding); // Must remember to close fs.Close(); } public void SaveConfigToStream(Stream stream, Encoding encoding) { XmlTextWriter xmlOut = new XmlTextWriter(stream, encoding); // Use indenting for readability xmlOut.Formatting = Formatting.Indented; // Always begin file with identification and warning xmlOut.WriteStartDocument(); xmlOut.WriteComment(" Magic, The User Interface library for .NET (www.dotnetmagic.com) "); xmlOut.WriteComment(" Modifying this generated file will probably render it invalid "); // Associate a version number with the root element so that future version of the code // will be able to be backwards compatible or at least recognise out of date versions xmlOut.WriteStartElement("TabbedGroups"); xmlOut.WriteAttributeString("FormatVersion", "1"); if (_activeLeaf != null) xmlOut.WriteAttributeString("ActiveLeaf", _activeLeaf.Unique.ToString()); else xmlOut.WriteAttributeString("ActiveLeaf", "-1"); // Give handlers chance to embed custom data xmlOut.WriteStartElement("CustomGlobalData"); OnGlobalSaving(xmlOut); xmlOut.WriteEndElement(); // Save the root sequence _root.SaveToXml(xmlOut); // Terminate the root element and document xmlOut.WriteEndElement(); xmlOut.WriteEndDocument(); // This should flush all actions and close the file xmlOut.Close(); // Saved, so cannot be dirty any more if (_autoCalculateDirty) _dirty = false; } public void LoadConfigFromArray(byte[] buffer) { // Create a memory based stream MemoryStream ms = new MemoryStream(buffer); // Save into the file stream LoadConfigFromStream(ms); // Must remember to close ms.Close(); } public void LoadConfigFromFile(string filename) { // Open existing file FileStream fs = new FileStream(filename, FileMode.Open); // Load from the file stream LoadConfigFromStream(fs); // Must remember to close fs.Close(); } public void LoadConfigFromStream(Stream stream) { XmlTextReader xmlIn = new XmlTextReader(stream); // Ignore whitespace, not interested xmlIn.WhitespaceHandling = WhitespaceHandling.None; // Moves the reader to the root element. xmlIn.MoveToContent(); // Double check this has the correct element name if (xmlIn.Name != "TabbedGroups") throw new ArgumentException("Root element must be 'TabbedGroups'"); // Load the format version number string version = xmlIn.GetAttribute(0); string rawActiveLeaf = xmlIn.GetAttribute(1); // Convert format version from string to double int formatVersion = (int)Convert.ToDouble(version); int activeLeaf = Convert.ToInt32(rawActiveLeaf); // We can only load 1 upward version formats if (formatVersion < 1) throw new ArgumentException("Can only load Version 1 and upwards TabbedGroups Configuration files"); try { // Prevent compacting and reposition of children BeginInit(); // Remove all existing contents _root.Clear(); // Read to custom data element if (!xmlIn.Read()) throw new ArgumentException("An element was expected but could not be read in"); if (xmlIn.Name != "CustomGlobalData") throw new ArgumentException("Expected 'CustomData' element was not found"); bool finished = xmlIn.IsEmptyElement; // Give handlers chance to reload custom saved data OnGlobalLoading(xmlIn); // Read everything until we get the end of custom data marker while(!finished) { // Check it has the expected name if (xmlIn.NodeType == XmlNodeType.EndElement) finished = (xmlIn.Name == "CustomGlobalData"); if (!finished) { if (!xmlIn.Read()) throw new ArgumentException("An element was expected but could not be read in"); } } // Read the next well known lement if (!xmlIn.Read()) throw new ArgumentException("An element was expected but could not be read in"); // Is it the expected element? if (xmlIn.Name != "Sequence") throw new ArgumentException("Element 'Sequence' was expected but not found"); // Reload the root sequence _root.LoadFromXml(xmlIn); // Move past the end element if (!xmlIn.Read()) throw new ArgumentException("Could not read in next expected node"); // Check it has the expected name if (xmlIn.NodeType != XmlNodeType.EndElement) throw new ArgumentException("EndElement expected but not found"); } finally { TabGroupLeaf newActive = null; // Reset the active leaf correctly TabGroupLeaf current = FirstLeaf(); while(current != null) { // Default to the first leaf if we cannot find a match if (newActive == null) newActive = current; // Find an exact match? if (current.Unique == activeLeaf) { newActive = current; break; } current = NextLeaf(current); } // Reinstate the active leaf indication if (newActive != null) ActiveLeaf = newActive; // Allow normal operation EndInit(); } xmlIn.Close(); // Just loaded, so cannot be dirty if (_autoCalculateDirty) _dirty = false; } protected TabGroupLeaf RecursiveFindLeafInSequence(TabGroupSequence tgs, bool forwards) { int count = tgs.Count; for(int i=0; i<count; i++) { // Index depends on which direction we are processing int index = (forwards == true) ? i : (tgs.Count - i - 1); // Is this the needed leaf node? if (tgs[index].IsLeaf) return tgs[index] as TabGroupLeaf; else { // Need to make a recursive check inside group TabGroupLeaf leaf = RecursiveFindLeafInSequence(tgs[index] as TabGroupSequence, forwards); if (leaf != null) return leaf; } } // Still no luck return null; } protected TabGroupLeaf RecursiveFindLeafInSequence(TabGroupSequence tgs, TabGroupBase tgb, bool forwards) { int count = tgs.Count; int index = tgs.IndexOf(tgb); // Are we look for entries after the provided one? if (forwards) { for(int i=index+1; i<count; i++) { // Is this the needed leaf node? if (tgs[i].IsLeaf) return tgs[i] as TabGroupLeaf; else { TabGroupLeaf leaf = RecursiveFindLeafInSequence(tgs[i] as TabGroupSequence, forwards); if (leaf != null) return leaf; } } } else { // Now try each entry before that given for(int i=index-1; i>=0; i--) { // Is this the needed leaf node? if (tgs[i].IsLeaf) return tgs[i] as TabGroupLeaf; else { TabGroupLeaf leaf = RecursiveFindLeafInSequence(tgs[i] as TabGroupSequence, forwards); if (leaf != null) return leaf; } } } // Still no luck, try our own parent if (tgs.Parent != null) return RecursiveFindLeafInSequence(tgs.Parent as TabGroupSequence, tgs, forwards); else return null; } protected void MoveActiveInSequence(TabGroupSequence tgs, TabGroupBase child) { int count = tgs.Count; int index = tgs.IndexOf(child); // First try each entry after that given for(int i=index+1; i<count; i++) { // Is this the needed leaf node? if (tgs[i].IsLeaf) { // Make it active, and finish ActiveLeaf = tgs[i] as TabGroupLeaf; return; } else { // Need to make a recursive check inside group if (RecursiveActiveInSequence(tgs[i] as TabGroupSequence, true)) return; } } // Now try each entry before that given for(int i=index-1; i>=0; i--) { // Is this the needed leaf node? if (tgs[i].IsLeaf) { // Make it active, and finish ActiveLeaf = tgs[i] as TabGroupLeaf; return; } else { // Need to make a recursive check inside group if (RecursiveActiveInSequence(tgs[i] as TabGroupSequence, false)) return; } } // Still no luck, try our own parent if (tgs.Parent != null) MoveActiveInSequence(tgs.Parent as TabGroupSequence, tgs); } protected bool RecursiveActiveInSequence(TabGroupSequence tgs, bool forwards) { int count = tgs.Count; for(int i=0; i<count; i++) { // Index depends on which direction we are processing int index = (forwards == true) ? i : (tgs.Count - i - 1); // Is this the needed leaf node? if (tgs[index].IsLeaf) { // Make it active, and finish ActiveLeaf = tgs[index] as TabGroupLeaf; return true; } else { // Need to make a recursive check inside group if (RecursiveActiveInSequence(tgs[index] as TabGroupSequence, forwards)) return true; } } // Still no luck return false; } protected void Notify(TabGroupBase.NotifyCode notifyCode) { // Propogate change notification only is we have a root sequence if (_root != null) _root.Notify(notifyCode); } internal void SuspendLeafCount() { _suspendLeafCount++; } internal void ResumeLeafCount(int adjust) { _suspendLeafCount--; // Apply adjustment factor _numLeafs += adjust; } internal void EnforceAtLeastOneLeaf() { // Should not add items during compacting operation if (!_compacting) { // Ensure we enfore policy of at least one leaf if (_atLeastOneLeaf) { // Is there at least one? if (_numLeafs == 0) { // No, create a default entry for the root sequence _root.AddNewLeaf(); // Update the active leaf ActiveLeaf = FirstLeaf(); // Mark layout as dirty if (_autoCalculateDirty) _dirty = true; } } } } internal void GroupRemoved(TabGroupBase tgb) { // Only modify leaf count when not suspended if (_suspendLeafCount == 0) { // Decrease count of leafs entries for each leaf that exists // which in the hierarchy that is being removed if (tgb.IsLeaf) { _numLeafs--; // Was last leaf removed? if (_numLeafs == 0) { // If at least one leaf then set the value manually so that when the // new one is created and set as active it does not try to process the // old value that has already been destroyed. if (_atLeastOneLeaf) { // Need to get rid of active leaf value ActiveLeaf = null; } } } else { TabGroupSequence tgs = tgb as TabGroupSequence; // Recurse into processing each child item for(int i=0; i<tgs.Count; i++) GroupRemoved(tgs[i]); } // Mark layout as dirty if (_autoCalculateDirty) _dirty = true; } } internal void SetRootSequence(TabGroupSequence tgs) { // Use the new sequence as the root _root = tgs; } public bool PreFilterMessage(ref Message msg) { Form parentForm = this.FindForm(); // Only interested if the Form we are on is activate (i.e. contains focus) if ((parentForm != null) && (parentForm == Form.ActiveForm) && parentForm.ContainsFocus) { switch(msg.Msg) { case (int)Win32.Msgs.WM_KEYDOWN: // Ignore keyboard input if the control is disabled if (this.Enabled) { // Find up/down state of shift and control keys ushort shiftKey = User32.GetKeyState((int)Win32.VirtualKeys.VK_SHIFT); ushort controlKey = User32.GetKeyState((int)Win32.VirtualKeys.VK_CONTROL); // Basic code we are looking for is the key pressed int code = (int)msg.WParam; // Is SHIFT pressed? bool shiftPressed = (((int)shiftKey & 0x00008000) != 0); // Is CONTROL pressed? bool controlPressed = (((int)controlKey & 0x00008000) != 0); // Was the TAB key pressed? if ((code == (int)Win32.VirtualKeys.VK_TAB) && controlPressed) { if (shiftPressed) return SelectPreviousTab(); else return SelectNextTab(); } else { // Plus the modifier for SHIFT... if (shiftPressed) code += 0x00010000; // Plus the modifier for CONTROL if (controlPressed) code += 0x00020000; // Construct shortcut from keystate and keychar Shortcut sc = (Shortcut)(code); // Search for a matching command return TestShortcut(sc); } } break; case (int)Win32.Msgs.WM_SYSKEYDOWN: // Ignore keyboard input if the control is disabled if (this.Enabled) { if ((int)msg.WParam != (int)Win32.VirtualKeys.VK_MENU) { // Construct shortcut from ALT + keychar Shortcut sc = (Shortcut)(0x00040000 + (int)msg.WParam); // Search for a matching command return TestShortcut(sc); } } break; default: break; } } return false; } protected bool TestShortcut(Shortcut sc) { bool result = false; try{ // Must have an active leaf for shortcuts to operate against if (_activeLeaf != null) { Controls.TabControl tc = _activeLeaf.GroupControl as Controls.TabControl; // Must have an active tab for these shortcuts to work against if (tc.SelectedTab != null) { // Close selected page requested? if (sc.Equals(_closeShortcut)) { _activeLeaf.OnClose(_activeLeaf, EventArgs.Empty); result = true; } // Toggle the prominence state? if (sc.Equals(_prominentShortcut)) { _activeLeaf.OnToggleProminent(_activeLeaf, EventArgs.Empty); result = true; } // Move page to the next group? if (sc.Equals(_moveNextShortcut)) { _activeLeaf.OnMoveNext(_activeLeaf, EventArgs.Empty); result = true; } // Move page to the previous group? if (sc.Equals(_movePreviousShortcut)) { _activeLeaf.OnMovePrevious(_activeLeaf, EventArgs.Empty); result = true; } // Cannot split a group unless at least two entries exist if (tc.TabPages.Count > 1) { bool allowVert = false; bool allowHorz = false; if (_root.Count <= 1) { allowVert = true; allowHorz = true; } else { if (_root.Direction == Direction.Vertical) allowVert = true; else allowHorz = true; } // Create two vertical groups if (allowHorz && sc.Equals(_splitVerticalShortcut)) { _activeLeaf.NewHorizontalGroup(_activeLeaf, false); result = true; } // Create two horizontal groups if (allowVert && sc.Equals(_splitHorizontalShortcut)) { _activeLeaf.NewVerticalGroup(_activeLeaf, false); result = true; } } } // Request to rebalance all spacing if (sc.Equals(_rebalanceShortcut)) { _activeLeaf.OnRebalance(_activeLeaf, EventArgs.Empty); result = true; } } }catch{} return result; } protected bool SelectNextTab() { // If no active leaf... if (_activeLeaf == null) SelectFirstPage(); else { bool selectFirst = false; TabGroupLeaf startLeaf = _activeLeaf; TabGroupLeaf thisLeaf = startLeaf; do { // Access to the embedded tab control Controls.TabControl tc = thisLeaf.GroupControl as Controls.TabControl; // Does it have any pages? if (tc.TabPages.Count > 0) { // Are we allowed to select the first page? if (selectFirst) { // Do it and exit loop tc.SelectedIndex = 0; // Must ensure this becomes the active leaf if (thisLeaf != _activeLeaf) ActiveLeaf = thisLeaf; break; } else { // Is there another page after the selected one? if (tc.SelectedIndex < tc.TabPages.Count - 1) { // Select new page and exit loop tc.SelectedIndex = tc.SelectedIndex + 1; break; } } } selectFirst = true; // Find the next leaf in sequence thisLeaf = NextLeaf(thisLeaf); // No more leafs, wrap back to first if (thisLeaf == null) thisLeaf = FirstLeaf(); // Back at starting leaf? if (thisLeaf == startLeaf) { // If it was not the first page that we started from if (tc.SelectedIndex > 0) { // Then we have circles all the way around, select first page tc.SelectedIndex = 0; } } } while(thisLeaf != startLeaf); } return true; } protected bool SelectPreviousTab() { // If no active leaf... if (_activeLeaf == null) SelectLastPage(); else { bool selectLast = false; TabGroupLeaf startLeaf = _activeLeaf; TabGroupLeaf thisLeaf = startLeaf; do { // Access to the embedded tab control Controls.TabControl tc = thisLeaf.GroupControl as Controls.TabControl; // Does it have any pages? if (tc.TabPages.Count > 0) { // Are we allowed to select the last page? if (selectLast) { // Do it and exit loop tc.SelectedIndex = tc.TabPages.Count - 1; // Must ensure this becomes the active leaf if (thisLeaf != _activeLeaf) ActiveLeaf = thisLeaf; break; } else { // Is there another page before the selected one? if (tc.SelectedIndex > 0) { // Select previous page and exit loop tc.SelectedIndex = tc.SelectedIndex - 1; break; } } } selectLast = true; // Find the previous leaf in sequence thisLeaf = PreviousLeaf(thisLeaf); // No more leafs, wrap back to first if (thisLeaf == null) thisLeaf = LastLeaf(); // Back at starting leaf? if (thisLeaf == startLeaf) { // If it was not the first page that we started from if (tc.SelectedIndex == 0) { // Then we have circles all the way around, select last page tc.SelectedIndex = tc.TabPages.Count - 1; } } } while(thisLeaf != startLeaf); } return true; } protected void SelectFirstPage() { // Find the first leaf ActiveLeaf = FirstLeaf(); // Did we find a leaf? if (_activeLeaf != null) { // Is there a page that can be selected? if (_activeLeaf.TabPages.Count > 0) _activeLeaf.TabPages[0].Selected = true; } } protected void SelectLastPage() { // Find the first leaf ActiveLeaf = LastLeaf(); // Did we find a leaf? if (_activeLeaf != null) { // Is there a page that can be selected? if (_activeLeaf.TabPages.Count > 0) _activeLeaf.TabPages[_activeLeaf.TabPages.Count - 1].Selected = true; } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Application.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows { public partial class Application : System.Windows.Threading.DispatcherObject, System.Windows.Markup.IHaveResources, System.Windows.Markup.IQueryAmbient { #region Methods and constructors public Application() { } public Object FindResource(Object resourceKey) { return default(Object); } public static System.Windows.Resources.StreamResourceInfo GetContentStream(Uri uriContent) { return default(System.Windows.Resources.StreamResourceInfo); } public static string GetCookie(Uri uri) { return default(string); } public static System.Windows.Resources.StreamResourceInfo GetRemoteStream(Uri uriRemote) { return default(System.Windows.Resources.StreamResourceInfo); } public static System.Windows.Resources.StreamResourceInfo GetResourceStream(Uri uriResource) { return default(System.Windows.Resources.StreamResourceInfo); } public static Object LoadComponent(Uri resourceLocator) { Contract.Requires(resourceLocator != null); Contract.Requires(resourceLocator.OriginalString != null); Contract.Requires(!resourceLocator.IsAbsoluteUri); Contract.Ensures(Contract.Result<Object>() != null); return default(Object); } public static void LoadComponent(Object component, Uri resourceLocator) { Contract.Requires(component != null); Contract.Requires(resourceLocator != null); Contract.Requires(resourceLocator.OriginalString != null); Contract.Requires(!resourceLocator.IsAbsoluteUri); } protected virtual new void OnActivated(EventArgs e) { } protected virtual new void OnDeactivated(EventArgs e) { } protected virtual new void OnExit(ExitEventArgs e) { } protected virtual new void OnFragmentNavigation(System.Windows.Navigation.FragmentNavigationEventArgs e) { } protected virtual new void OnLoadCompleted(System.Windows.Navigation.NavigationEventArgs e) { } protected virtual new void OnNavigated(System.Windows.Navigation.NavigationEventArgs e) { } protected virtual new void OnNavigating(System.Windows.Navigation.NavigatingCancelEventArgs e) { } protected virtual new void OnNavigationFailed(System.Windows.Navigation.NavigationFailedEventArgs e) { } protected virtual new void OnNavigationProgress(System.Windows.Navigation.NavigationProgressEventArgs e) { } protected virtual new void OnNavigationStopped(System.Windows.Navigation.NavigationEventArgs e) { } protected virtual new void OnSessionEnding(SessionEndingCancelEventArgs e) { } protected virtual new void OnStartup(StartupEventArgs e) { } public int Run(Window window) { return default(int); } public int Run() { return default(int); } public static void SetCookie(Uri uri, string value) { } public void Shutdown(int exitCode) { } public void Shutdown() { } bool System.Windows.Markup.IQueryAmbient.IsAmbientPropertyAvailable(string propertyName) { return default(bool); } public Object TryFindResource(Object resourceKey) { return default(Object); } #endregion #region Properties and indexers public static System.Windows.Application Current { get { // May return null if called from non-WPF application (e.g. WinForms app with embedded WPF controls). return default(System.Windows.Application); } } public Window MainWindow { get { return default(Window); } set { } } public System.Collections.IDictionary Properties { get { Contract.Ensures(Contract.Result<System.Collections.IDictionary>() != null); return default(System.Collections.IDictionary); } } public static System.Reflection.Assembly ResourceAssembly { get { Contract.Ensures(Contract.Result<System.Reflection.Assembly>() != null); return default(System.Reflection.Assembly); } set { } } public ResourceDictionary Resources { get { Contract.Ensures(Contract.Result<System.Windows.ResourceDictionary>() != null); return default(ResourceDictionary); } set { } } public ShutdownMode ShutdownMode { get { return default(ShutdownMode); } set { } } public Uri StartupUri { get { return default(Uri); } set { } } ResourceDictionary System.Windows.Markup.IHaveResources.Resources { get { return default(ResourceDictionary); } set { } } public WindowCollection Windows { get { Contract.Ensures(Contract.Result<System.Windows.WindowCollection>() != null); return default(WindowCollection); } } #endregion #region Events public event EventHandler Activated { add { } remove { } } public event EventHandler Deactivated { add { } remove { } } public event System.Windows.Threading.DispatcherUnhandledExceptionEventHandler DispatcherUnhandledException { add { } remove { } } public event ExitEventHandler Exit { add { } remove { } } public event System.Windows.Navigation.FragmentNavigationEventHandler FragmentNavigation { add { } remove { } } public event System.Windows.Navigation.LoadCompletedEventHandler LoadCompleted { add { } remove { } } public event System.Windows.Navigation.NavigatedEventHandler Navigated { add { } remove { } } public event System.Windows.Navigation.NavigatingCancelEventHandler Navigating { add { } remove { } } public event System.Windows.Navigation.NavigationFailedEventHandler NavigationFailed { add { } remove { } } public event System.Windows.Navigation.NavigationProgressEventHandler NavigationProgress { add { } remove { } } public event System.Windows.Navigation.NavigationStoppedEventHandler NavigationStopped { add { } remove { } } public event SessionEndingCancelEventHandler SessionEnding { add { } remove { } } public event StartupEventHandler Startup { add { } remove { } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Bookz.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
namespace android.gesture { [global::MonoJavaBridge.JavaClass()] public partial class GestureOverlayView : android.widget.FrameLayout { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static GestureOverlayView() { InitJNI(); } protected GestureOverlayView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.gesture.GestureOverlayView.OnGestureListener_))] public interface OnGestureListener : global::MonoJavaBridge.IJavaObject { void onGestureStarted(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1); void onGesture(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1); void onGestureEnded(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1); void onGestureCancelled(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.gesture.GestureOverlayView.OnGestureListener))] public sealed partial class OnGestureListener_ : java.lang.Object, OnGestureListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnGestureListener_() { InitJNI(); } internal OnGestureListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onGestureStarted2973; void android.gesture.GestureOverlayView.OnGestureListener.onGestureStarted(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGestureListener_._onGestureStarted2973, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, global::android.gesture.GestureOverlayView.OnGestureListener_._onGestureStarted2973, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onGesture2974; void android.gesture.GestureOverlayView.OnGestureListener.onGesture(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGestureListener_._onGesture2974, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, global::android.gesture.GestureOverlayView.OnGestureListener_._onGesture2974, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onGestureEnded2975; void android.gesture.GestureOverlayView.OnGestureListener.onGestureEnded(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGestureListener_._onGestureEnded2975, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, global::android.gesture.GestureOverlayView.OnGestureListener_._onGestureEnded2975, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onGestureCancelled2976; void android.gesture.GestureOverlayView.OnGestureListener.onGestureCancelled(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGestureListener_._onGestureCancelled2976, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, global::android.gesture.GestureOverlayView.OnGestureListener_._onGestureCancelled2976, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/gesture/GestureOverlayView$OnGestureListener")); global::android.gesture.GestureOverlayView.OnGestureListener_._onGestureStarted2973 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, "onGestureStarted", "(Landroid/gesture/GestureOverlayView;Landroid/view/MotionEvent;)V"); global::android.gesture.GestureOverlayView.OnGestureListener_._onGesture2974 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, "onGesture", "(Landroid/gesture/GestureOverlayView;Landroid/view/MotionEvent;)V"); global::android.gesture.GestureOverlayView.OnGestureListener_._onGestureEnded2975 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, "onGestureEnded", "(Landroid/gesture/GestureOverlayView;Landroid/view/MotionEvent;)V"); global::android.gesture.GestureOverlayView.OnGestureListener_._onGestureCancelled2976 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, "onGestureCancelled", "(Landroid/gesture/GestureOverlayView;Landroid/view/MotionEvent;)V"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.gesture.GestureOverlayView.OnGesturePerformedListener_))] public interface OnGesturePerformedListener : global::MonoJavaBridge.IJavaObject { void onGesturePerformed(android.gesture.GestureOverlayView arg0, android.gesture.Gesture arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.gesture.GestureOverlayView.OnGesturePerformedListener))] public sealed partial class OnGesturePerformedListener_ : java.lang.Object, OnGesturePerformedListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnGesturePerformedListener_() { InitJNI(); } internal OnGesturePerformedListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onGesturePerformed2977; void android.gesture.GestureOverlayView.OnGesturePerformedListener.onGesturePerformed(android.gesture.GestureOverlayView arg0, android.gesture.Gesture arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGesturePerformedListener_._onGesturePerformed2977, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGesturePerformedListener_.staticClass, global::android.gesture.GestureOverlayView.OnGesturePerformedListener_._onGesturePerformed2977, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.gesture.GestureOverlayView.OnGesturePerformedListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/gesture/GestureOverlayView$OnGesturePerformedListener")); global::android.gesture.GestureOverlayView.OnGesturePerformedListener_._onGesturePerformed2977 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.OnGesturePerformedListener_.staticClass, "onGesturePerformed", "(Landroid/gesture/GestureOverlayView;Landroid/gesture/Gesture;)V"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.gesture.GestureOverlayView.OnGesturingListener_))] public interface OnGesturingListener : global::MonoJavaBridge.IJavaObject { void onGesturingStarted(android.gesture.GestureOverlayView arg0); void onGesturingEnded(android.gesture.GestureOverlayView arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.gesture.GestureOverlayView.OnGesturingListener))] public sealed partial class OnGesturingListener_ : java.lang.Object, OnGesturingListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnGesturingListener_() { InitJNI(); } internal OnGesturingListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onGesturingStarted2978; void android.gesture.GestureOverlayView.OnGesturingListener.onGesturingStarted(android.gesture.GestureOverlayView arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGesturingListener_._onGesturingStarted2978, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGesturingListener_.staticClass, global::android.gesture.GestureOverlayView.OnGesturingListener_._onGesturingStarted2978, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onGesturingEnded2979; void android.gesture.GestureOverlayView.OnGesturingListener.onGesturingEnded(android.gesture.GestureOverlayView arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGesturingListener_._onGesturingEnded2979, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.OnGesturingListener_.staticClass, global::android.gesture.GestureOverlayView.OnGesturingListener_._onGesturingEnded2979, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.gesture.GestureOverlayView.OnGesturingListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/gesture/GestureOverlayView$OnGesturingListener")); global::android.gesture.GestureOverlayView.OnGesturingListener_._onGesturingStarted2978 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.OnGesturingListener_.staticClass, "onGesturingStarted", "(Landroid/gesture/GestureOverlayView;)V"); global::android.gesture.GestureOverlayView.OnGesturingListener_._onGesturingEnded2979 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.OnGesturingListener_.staticClass, "onGesturingEnded", "(Landroid/gesture/GestureOverlayView;)V"); } } internal static global::MonoJavaBridge.MethodId _clear2980; public virtual void clear(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._clear2980, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._clear2980, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _draw2981; public override void draw(android.graphics.Canvas arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._draw2981, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._draw2981, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDetachedFromWindow2982; protected override void onDetachedFromWindow() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._onDetachedFromWindow2982); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._onDetachedFromWindow2982); } internal static global::MonoJavaBridge.MethodId _dispatchTouchEvent2983; public override bool dispatchTouchEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._dispatchTouchEvent2983, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._dispatchTouchEvent2983, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOrientation2984; public virtual void setOrientation(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setOrientation2984, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setOrientation2984, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getOrientation2985; public virtual int getOrientation() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getOrientation2985); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getOrientation2985); } internal static global::MonoJavaBridge.MethodId _getCurrentStroke2986; public virtual global::java.util.ArrayList getCurrentStroke() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getCurrentStroke2986)) as java.util.ArrayList; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getCurrentStroke2986)) as java.util.ArrayList; } internal static global::MonoJavaBridge.MethodId _setGestureColor2987; public virtual void setGestureColor(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setGestureColor2987, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setGestureColor2987, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setUncertainGestureColor2988; public virtual void setUncertainGestureColor(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setUncertainGestureColor2988, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setUncertainGestureColor2988, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getUncertainGestureColor2989; public virtual int getUncertainGestureColor() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getUncertainGestureColor2989); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getUncertainGestureColor2989); } internal static global::MonoJavaBridge.MethodId _getGestureColor2990; public virtual int getGestureColor() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getGestureColor2990); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getGestureColor2990); } internal static global::MonoJavaBridge.MethodId _getGestureStrokeWidth2991; public virtual float getGestureStrokeWidth() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getGestureStrokeWidth2991); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getGestureStrokeWidth2991); } internal static global::MonoJavaBridge.MethodId _setGestureStrokeWidth2992; public virtual void setGestureStrokeWidth(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setGestureStrokeWidth2992, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setGestureStrokeWidth2992, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getGestureStrokeType2993; public virtual int getGestureStrokeType() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getGestureStrokeType2993); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getGestureStrokeType2993); } internal static global::MonoJavaBridge.MethodId _setGestureStrokeType2994; public virtual void setGestureStrokeType(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setGestureStrokeType2994, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setGestureStrokeType2994, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getGestureStrokeLengthThreshold2995; public virtual float getGestureStrokeLengthThreshold() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getGestureStrokeLengthThreshold2995); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getGestureStrokeLengthThreshold2995); } internal static global::MonoJavaBridge.MethodId _setGestureStrokeLengthThreshold2996; public virtual void setGestureStrokeLengthThreshold(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setGestureStrokeLengthThreshold2996, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setGestureStrokeLengthThreshold2996, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getGestureStrokeSquarenessTreshold2997; public virtual float getGestureStrokeSquarenessTreshold() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getGestureStrokeSquarenessTreshold2997); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getGestureStrokeSquarenessTreshold2997); } internal static global::MonoJavaBridge.MethodId _setGestureStrokeSquarenessTreshold2998; public virtual void setGestureStrokeSquarenessTreshold(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setGestureStrokeSquarenessTreshold2998, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setGestureStrokeSquarenessTreshold2998, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getGestureStrokeAngleThreshold2999; public virtual float getGestureStrokeAngleThreshold() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getGestureStrokeAngleThreshold2999); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getGestureStrokeAngleThreshold2999); } internal static global::MonoJavaBridge.MethodId _setGestureStrokeAngleThreshold3000; public virtual void setGestureStrokeAngleThreshold(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setGestureStrokeAngleThreshold3000, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setGestureStrokeAngleThreshold3000, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isEventsInterceptionEnabled3001; public virtual bool isEventsInterceptionEnabled() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._isEventsInterceptionEnabled3001); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._isEventsInterceptionEnabled3001); } internal static global::MonoJavaBridge.MethodId _setEventsInterceptionEnabled3002; public virtual void setEventsInterceptionEnabled(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setEventsInterceptionEnabled3002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setEventsInterceptionEnabled3002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isFadeEnabled3003; public virtual bool isFadeEnabled() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._isFadeEnabled3003); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._isFadeEnabled3003); } internal static global::MonoJavaBridge.MethodId _setFadeEnabled3004; public virtual void setFadeEnabled(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setFadeEnabled3004, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setFadeEnabled3004, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getGesture3005; public virtual global::android.gesture.Gesture getGesture() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getGesture3005)) as android.gesture.Gesture; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getGesture3005)) as android.gesture.Gesture; } internal static global::MonoJavaBridge.MethodId _setGesture3006; public virtual void setGesture(android.gesture.Gesture arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setGesture3006, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setGesture3006, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getGesturePath3007; public virtual global::android.graphics.Path getGesturePath() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getGesturePath3007)) as android.graphics.Path; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getGesturePath3007)) as android.graphics.Path; } internal static global::MonoJavaBridge.MethodId _getGesturePath3008; public virtual global::android.graphics.Path getGesturePath(android.graphics.Path arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getGesturePath3008, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Path; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getGesturePath3008, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Path; } internal static global::MonoJavaBridge.MethodId _isGestureVisible3009; public virtual bool isGestureVisible() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._isGestureVisible3009); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._isGestureVisible3009); } internal static global::MonoJavaBridge.MethodId _setGestureVisible3010; public virtual void setGestureVisible(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setGestureVisible3010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setGestureVisible3010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getFadeOffset3011; public virtual long getFadeOffset() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._getFadeOffset3011); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._getFadeOffset3011); } internal static global::MonoJavaBridge.MethodId _setFadeOffset3012; public virtual void setFadeOffset(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._setFadeOffset3012, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._setFadeOffset3012, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _addOnGestureListener3013; public virtual void addOnGestureListener(android.gesture.GestureOverlayView.OnGestureListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._addOnGestureListener3013, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._addOnGestureListener3013, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _removeOnGestureListener3014; public virtual void removeOnGestureListener(android.gesture.GestureOverlayView.OnGestureListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._removeOnGestureListener3014, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._removeOnGestureListener3014, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _removeAllOnGestureListeners3015; public virtual void removeAllOnGestureListeners() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._removeAllOnGestureListeners3015); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._removeAllOnGestureListeners3015); } internal static global::MonoJavaBridge.MethodId _addOnGesturePerformedListener3016; public virtual void addOnGesturePerformedListener(android.gesture.GestureOverlayView.OnGesturePerformedListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._addOnGesturePerformedListener3016, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._addOnGesturePerformedListener3016, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _removeOnGesturePerformedListener3017; public virtual void removeOnGesturePerformedListener(android.gesture.GestureOverlayView.OnGesturePerformedListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._removeOnGesturePerformedListener3017, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._removeOnGesturePerformedListener3017, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _removeAllOnGesturePerformedListeners3018; public virtual void removeAllOnGesturePerformedListeners() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._removeAllOnGesturePerformedListeners3018); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._removeAllOnGesturePerformedListeners3018); } internal static global::MonoJavaBridge.MethodId _addOnGesturingListener3019; public virtual void addOnGesturingListener(android.gesture.GestureOverlayView.OnGesturingListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._addOnGesturingListener3019, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._addOnGesturingListener3019, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _removeOnGesturingListener3020; public virtual void removeOnGesturingListener(android.gesture.GestureOverlayView.OnGesturingListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._removeOnGesturingListener3020, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._removeOnGesturingListener3020, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _removeAllOnGesturingListeners3021; public virtual void removeAllOnGesturingListeners() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._removeAllOnGesturingListeners3021); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._removeAllOnGesturingListeners3021); } internal static global::MonoJavaBridge.MethodId _isGesturing3022; public virtual bool isGesturing() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._isGesturing3022); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._isGesturing3022); } internal static global::MonoJavaBridge.MethodId _cancelClearAnimation3023; public virtual void cancelClearAnimation() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._cancelClearAnimation3023); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._cancelClearAnimation3023); } internal static global::MonoJavaBridge.MethodId _cancelGesture3024; public virtual void cancelGesture() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView._cancelGesture3024); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._cancelGesture3024); } internal static global::MonoJavaBridge.MethodId _GestureOverlayView3025; public GestureOverlayView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._GestureOverlayView3025, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GestureOverlayView3026; public GestureOverlayView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._GestureOverlayView3026, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GestureOverlayView3027; public GestureOverlayView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._GestureOverlayView3027, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } public static int GESTURE_STROKE_TYPE_SINGLE { get { return 0; } } public static int GESTURE_STROKE_TYPE_MULTIPLE { get { return 1; } } public static int ORIENTATION_HORIZONTAL { get { return 0; } } public static int ORIENTATION_VERTICAL { get { return 1; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.gesture.GestureOverlayView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/gesture/GestureOverlayView")); global::android.gesture.GestureOverlayView._clear2980 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "clear", "(Z)V"); global::android.gesture.GestureOverlayView._draw2981 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "draw", "(Landroid/graphics/Canvas;)V"); global::android.gesture.GestureOverlayView._onDetachedFromWindow2982 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "onDetachedFromWindow", "()V"); global::android.gesture.GestureOverlayView._dispatchTouchEvent2983 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "dispatchTouchEvent", "(Landroid/view/MotionEvent;)Z"); global::android.gesture.GestureOverlayView._setOrientation2984 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setOrientation", "(I)V"); global::android.gesture.GestureOverlayView._getOrientation2985 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getOrientation", "()I"); global::android.gesture.GestureOverlayView._getCurrentStroke2986 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getCurrentStroke", "()Ljava/util/ArrayList;"); global::android.gesture.GestureOverlayView._setGestureColor2987 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setGestureColor", "(I)V"); global::android.gesture.GestureOverlayView._setUncertainGestureColor2988 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setUncertainGestureColor", "(I)V"); global::android.gesture.GestureOverlayView._getUncertainGestureColor2989 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getUncertainGestureColor", "()I"); global::android.gesture.GestureOverlayView._getGestureColor2990 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getGestureColor", "()I"); global::android.gesture.GestureOverlayView._getGestureStrokeWidth2991 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getGestureStrokeWidth", "()F"); global::android.gesture.GestureOverlayView._setGestureStrokeWidth2992 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setGestureStrokeWidth", "(F)V"); global::android.gesture.GestureOverlayView._getGestureStrokeType2993 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getGestureStrokeType", "()I"); global::android.gesture.GestureOverlayView._setGestureStrokeType2994 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setGestureStrokeType", "(I)V"); global::android.gesture.GestureOverlayView._getGestureStrokeLengthThreshold2995 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getGestureStrokeLengthThreshold", "()F"); global::android.gesture.GestureOverlayView._setGestureStrokeLengthThreshold2996 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setGestureStrokeLengthThreshold", "(F)V"); global::android.gesture.GestureOverlayView._getGestureStrokeSquarenessTreshold2997 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getGestureStrokeSquarenessTreshold", "()F"); global::android.gesture.GestureOverlayView._setGestureStrokeSquarenessTreshold2998 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setGestureStrokeSquarenessTreshold", "(F)V"); global::android.gesture.GestureOverlayView._getGestureStrokeAngleThreshold2999 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getGestureStrokeAngleThreshold", "()F"); global::android.gesture.GestureOverlayView._setGestureStrokeAngleThreshold3000 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setGestureStrokeAngleThreshold", "(F)V"); global::android.gesture.GestureOverlayView._isEventsInterceptionEnabled3001 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "isEventsInterceptionEnabled", "()Z"); global::android.gesture.GestureOverlayView._setEventsInterceptionEnabled3002 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setEventsInterceptionEnabled", "(Z)V"); global::android.gesture.GestureOverlayView._isFadeEnabled3003 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "isFadeEnabled", "()Z"); global::android.gesture.GestureOverlayView._setFadeEnabled3004 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setFadeEnabled", "(Z)V"); global::android.gesture.GestureOverlayView._getGesture3005 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getGesture", "()Landroid/gesture/Gesture;"); global::android.gesture.GestureOverlayView._setGesture3006 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setGesture", "(Landroid/gesture/Gesture;)V"); global::android.gesture.GestureOverlayView._getGesturePath3007 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getGesturePath", "()Landroid/graphics/Path;"); global::android.gesture.GestureOverlayView._getGesturePath3008 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getGesturePath", "(Landroid/graphics/Path;)Landroid/graphics/Path;"); global::android.gesture.GestureOverlayView._isGestureVisible3009 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "isGestureVisible", "()Z"); global::android.gesture.GestureOverlayView._setGestureVisible3010 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setGestureVisible", "(Z)V"); global::android.gesture.GestureOverlayView._getFadeOffset3011 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "getFadeOffset", "()J"); global::android.gesture.GestureOverlayView._setFadeOffset3012 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "setFadeOffset", "(J)V"); global::android.gesture.GestureOverlayView._addOnGestureListener3013 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "addOnGestureListener", "(Landroid/gesture/GestureOverlayView$OnGestureListener;)V"); global::android.gesture.GestureOverlayView._removeOnGestureListener3014 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "removeOnGestureListener", "(Landroid/gesture/GestureOverlayView$OnGestureListener;)V"); global::android.gesture.GestureOverlayView._removeAllOnGestureListeners3015 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "removeAllOnGestureListeners", "()V"); global::android.gesture.GestureOverlayView._addOnGesturePerformedListener3016 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "addOnGesturePerformedListener", "(Landroid/gesture/GestureOverlayView$OnGesturePerformedListener;)V"); global::android.gesture.GestureOverlayView._removeOnGesturePerformedListener3017 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "removeOnGesturePerformedListener", "(Landroid/gesture/GestureOverlayView$OnGesturePerformedListener;)V"); global::android.gesture.GestureOverlayView._removeAllOnGesturePerformedListeners3018 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "removeAllOnGesturePerformedListeners", "()V"); global::android.gesture.GestureOverlayView._addOnGesturingListener3019 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "addOnGesturingListener", "(Landroid/gesture/GestureOverlayView$OnGesturingListener;)V"); global::android.gesture.GestureOverlayView._removeOnGesturingListener3020 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "removeOnGesturingListener", "(Landroid/gesture/GestureOverlayView$OnGesturingListener;)V"); global::android.gesture.GestureOverlayView._removeAllOnGesturingListeners3021 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "removeAllOnGesturingListeners", "()V"); global::android.gesture.GestureOverlayView._isGesturing3022 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "isGesturing", "()Z"); global::android.gesture.GestureOverlayView._cancelClearAnimation3023 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "cancelClearAnimation", "()V"); global::android.gesture.GestureOverlayView._cancelGesture3024 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "cancelGesture", "()V"); global::android.gesture.GestureOverlayView._GestureOverlayView3025 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "<init>", "(Landroid/content/Context;)V"); global::android.gesture.GestureOverlayView._GestureOverlayView3026 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.gesture.GestureOverlayView._GestureOverlayView3027 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); } } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2010-11-01 * */ using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Util; namespace Amazon.CloudFront_2012_03_15.Model { /// <summary> /// The CloudFrontDistributionConfig complex type describes a distribution's configuration information. /// It is used as a request element in Create a Distribution and Set a Distribution's Configuration. /// It is used as a response element in Get a Distribution's Information and Get a Distribution's /// Configuration. /// <para>A distribution configuration objects consists of the following items: /// <list type="number"> /// <item>Caller Reference</item> /// <item>Origin S3 Bucket</item> /// <item>Comment</item> /// <item>A list of CNAMEs for the distribution</item> /// <item>Enabled flag</item> /// <item>Bucket Logging details</item> /// <item>CloudFront Origin Access Identity associated with the distribution. /// This is a virtual identity you use to let CloudFront fetch private content /// from your bucket.</item> /// <item>The AWS Accounts that have URL signing privileges for Private Content.</item> /// </list> /// </para> /// For more information, please visit: /// <see href="http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DistributionConfigDatatype.html"/> /// </summary> [Serializable()] public class CloudFrontDistributionConfig : CloudFrontDistributionConfigBase { #region Private Members CustomOrigin _customOrigin; List<Protocol> requiredProtocols; string defaultRootObject; #endregion #region Public Methods /// <summary> /// Creates an XML representation of the CloudFront /// distribution configuration. The resulting XML /// can be sent to CloudFront when creating or updating /// a distribution. /// </summary> /// <returns> /// XML representation of the distribution's configuration /// </returns> public override string ToString() { StringBuilder sb = new StringBuilder(1024); sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><DistributionConfig "); sb.Append("xmlns=\"http://cloudfront.amazonaws.com/doc/2010-11-01/\">"); sb.Append(base.ToString()); // Represent RequiredProtocols in the xml if (IsSetRequiredProtocols()) { sb.Append("<RequiredProtocols>"); foreach (Protocol reqProt in RequiredProtocols) { sb.Append(String.Concat("<Protocol>", reqProt, "</Protocol>")); } sb.Append("</RequiredProtocols>"); } if (IsDefaultRootObjectSet()) { sb.Append(String.Concat("<DefaultRootObject>", this.DefaultRootObject, "</DefaultRootObject>")); } if(this.IsSetCustomOrigin()) { sb.Append(this.CustomOrigin.ToString()); } sb.Append("</DistributionConfig>"); return sb.ToString(); } #endregion #region Fluid API /// <summary> /// Sets the Origin property. /// </summary> /// <param name="origin">Origin property</param> /// <returns>this instance</returns> [Obsolete("This property has been obsoleted in favor of the WithS3Origin method.")] public CloudFrontDistributionConfig WithOrigin(string origin) { #pragma warning disable 0618 Origin = origin; #pragma warning restore 0618 return this; } /// <summary> /// Sets the Comment property. /// </summary> /// <param name="comment">Comment property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CloudFrontDistributionConfig WithComment(string comment) { this.Comment = comment; return this; } /// <summary> /// Sets the CallerReference property /// </summary> /// <param name="callerReference">CallerReference property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CloudFrontDistributionConfig WithCallerReference(string callerReference) { this.CallerReference = callerReference; return this; } /// <summary> /// Sets the CNAME property. If you set more than 10 CNAME aliases for a distribution, /// a <code>TooManyDistributionCNAMEs</code> exception will be returned by CloudFront. /// </summary> /// <param name="cnames">CNAME property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CloudFrontDistributionConfig WithCNames(params string[] cnames) { foreach (string cname in cnames) { CNAME.Add(cname); } return this; } /// <summary> /// Sets the Enabled property /// </summary> /// <param name="enabled">Enabled property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CloudFrontDistributionConfig WithEnabled(bool enabled) { this.Enabled = enabled; return this; } /// <summary> /// Sets the OriginAccessIdentity property. /// </summary> /// <param name="identity">OriginAccessIdentity property</param> /// <returns>this instance</returns> [Obsolete("This property has been obsoleted in favor of the WithS3Origin method.")] public CloudFrontDistributionConfig WithOriginAccessIdentity(CloudFrontOriginAccessIdentity identity) { #pragma warning disable 0618 OriginAccessIdentity = identity; #pragma warning restore 0618 return this; } /// <summary> /// Sets the TrustedSigners property. /// This specifies any AWS accounts you want to permit to create signed URLs for private content. /// </summary> /// <param name="signers">TrustedSigners property is set to this value</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CloudFrontDistributionConfig WithTrustedSigners(UrlTrustedSigners signers) { this.TrustedSigners = signers; return this; } /// <summary> /// Gets and sets the CustomOrigin property. /// The CustomOrigin contains the information for a non Amazon S3 Bucket origin. /// </summary> public CustomOrigin CustomOrigin { get { return this._customOrigin; } set { this._customOrigin = value; } } /// <summary> /// Sets the CustomOrigin property. /// The CustomOrigin contains the information for a non Amazon S3 Bucket origin. /// This instance is returned to allow method chaining. /// </summary> /// <param name="customOrigin">CustomOrigin property is set to this value.</param> /// <returns>This instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CloudFrontDistributionConfig WithCustomOrigin(CustomOrigin customOrigin) { this.CustomOrigin = customOrigin; return this; } internal bool IsSetCustomOrigin() { return this._customOrigin != null; } #endregion #region Logging /// <summary> /// Sets the Logging property. /// </summary> /// <param name="bucket">The bucket into which logs will be put</param> /// <param name="prefix">The prefix for the log files</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CloudFrontDistributionConfig WithLogging(string bucket, string prefix) { if (String.IsNullOrEmpty(bucket)) { throw new ArgumentNullException( "bucket", "The bucket specified as part of the Logging Config is null or the empty string" ); } Logging = new Tuple<string, string>(bucket, prefix); return this; } #endregion #region RequiredProtocols /// <summary> /// Gets and sets the RequiredProtocols property. /// Defines the protocols required for your distribution. Use this element to restrict /// access to your distribution solely to HTTPS requests. Without this element, /// CloudFront can use any available protocol to serve the request. /// For a list of possible protocol values, refer /// <see cref="T:Amazon.CloudFront.Model.Protocol"/>. /// </summary> [XmlElementAttribute(ElementName = "Protocol")] public List<Protocol> RequiredProtocols { get { if (this.requiredProtocols == null) { this.requiredProtocols = new List<Protocol>(); } return this.requiredProtocols; } set { this.requiredProtocols = value; } } /// <summary> /// Checks if RequiredProtocols property is set. /// </summary> /// <returns>true if RequiredProtocols property is set.</returns> internal bool IsSetRequiredProtocols() { return (RequiredProtocols.Count > 0); } /// <summary> /// Sets the RequiredProtocols property. /// Defines the protocols required for your distribution. Use this element to restrict /// access to your distribution solely to HTTPS requests. Without this element, /// CloudFront can use any available protocol to serve the request. /// For a list of possible protocol values, refer /// <see cref="T:Amazon.CloudFront.Model.Protocol"/>. /// </summary> /// <param name="protocols">RequiredProtocols property is set to this value</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CloudFrontDistributionConfig WithRequiredProtocols(params Protocol[] protocols) { foreach (Protocol prot in protocols) { RequiredProtocols.Add(prot); } return this; } #endregion #region DefaultRootObject /// <summary> /// Gets and sets the DefaultRootObject property. /// Defines the object that will be returned for requests made to the root URL of /// the distribution. /// </summary> public string DefaultRootObject { get { return this.defaultRootObject; } set { this.defaultRootObject = value; } } /// <summary> /// Sets the DefaultRootObject property. /// </summary> /// <param name="rootObject">The name of the default root object.</param> /// <returns>This instance.</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CloudFrontDistributionConfig WithDefaultRootObject(string rootObject) { this.defaultRootObject = rootObject; return this; } /// <summary> /// Checks to see if the DefaultRootObject property is set. /// </summary> /// <returns>True if DefaultRootObject is set. False otherwise.</returns> internal bool IsDefaultRootObjectSet() { return this.defaultRootObject != null; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** Purpose: This class will encapsulate an unsigned long and ** provide an Object representation of it. ** ** ===========================================================*/ using System.Globalization; using System; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System { // Wrapper for unsigned 64 bit integers. [Serializable] [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct UInt64 : IComparable, IFormattable, IConvertible , IComparable<UInt64>, IEquatable<UInt64> { private ulong m_value; public const ulong MaxValue = (ulong)0xffffffffffffffffL; public const ulong MinValue = 0x0; // 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 UInt64, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is UInt64) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. ulong i = (ulong)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(Environment.GetResourceString("Arg_MustBeUInt64")); } public int CompareTo(UInt64 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 UInt64)) { return false; } return m_value == ((UInt64)obj).m_value; } [System.Runtime.Versioning.NonVersionable] public bool Equals(UInt64 obj) { return m_value == obj; } // The value of the lower 32 bits XORed with the uppper 32 bits. public override int GetHashCode() { return ((int)m_value) ^ (int)(m_value >> 32); } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt64(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt64(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt64(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt64(m_value, format, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static ulong Parse(String s) { return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static ulong Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseUInt64(s, style, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static ulong Parse(string s, IFormatProvider provider) { return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static ulong Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseUInt64(s, style, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static Boolean TryParse(String s, out UInt64 result) { return Number.TryParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } [CLSCompliant(false)] public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt64 result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseUInt64(s, style, NumberFormatInfo.GetInstance(provider), out result); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.UInt64; } /// <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 Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return 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(Environment.GetResourceString("InvalidCast_FromTo", "UInt64", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// // DaapService.cs // // Authors: // Alexander Hixon <[email protected]> // // Copyright (C) 2008 Alexander Hixon // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using Mono.Unix; using NativeDaap = Daap; using Daap; using Gtk; using Hyena; using Banshee.Collection; using Banshee.Gui; using Banshee.Sources; using Banshee.ServiceStack; namespace Banshee.Daap { public class DaapService : IExtensionService, IDisposable, IDelayedInitializeService { private ServiceLocator locator; private DateTime locator_started; private static DaapProxyWebServer proxy_server; private DaapContainerSource container; private Dictionary<string, DaapSource> source_map; internal static DaapProxyWebServer ProxyServer { get { return proxy_server; } } void IExtensionService.Initialize () { } public void Dispose () { if (locator != null) { locator.Stop (); locator.Found -= OnServiceFound; locator.Removed -= OnServiceRemoved; locator = null; } if (proxy_server != null) { proxy_server.Stop (); proxy_server = null; } // Dispose any remaining child sources if (source_map != null) { foreach (KeyValuePair <string, DaapSource> kv in source_map) { if (kv.Value != null) { kv.Value.Disconnect (true); kv.Value.Dispose (); } } source_map.Clear (); } if (container != null) { ServiceManager.SourceManager.RemoveSource (container, true); container = null; } } private void OnServiceFound (object o, ServiceArgs args) { AddDaapServer (args.Service); } private void AddDaapServer (Service service) { ThreadAssist.ProxyToMain (delegate { DaapSource source = new DaapSource (service); string key = String.Format ("{0}:{1}", service.Name, service.Port); if (source_map.Count == 0) { ServiceManager.SourceManager.AddSource (container); } if (source_map.ContainsKey (key)) { // Received new connection info for service container.RemoveChildSource (source_map [key]); source_map [key] = source; } else { // New service information source_map.Add (key, source); } container.AddChildSource (source); // Don't flash shares we find on startup (well, within 5s of startup) if ((DateTime.Now - locator_started).TotalSeconds > 5) { source.NotifyUser (); } }); } private void OnServiceRemoved (object o, ServiceArgs args) { ThreadAssist.ProxyToMain (delegate { string key = String.Format ("{0}:{1}", args.Service.Name, args.Service.Port); DaapSource source = source_map [key]; source.Disconnect (true); container.RemoveChildSource (source); source_map.Remove (key); if (source_map.Count == 0) { ServiceManager.SourceManager.RemoveSource (container); } }); } public void DelayedInitialize () { ThreadAssist.SpawnFromMain (ThreadedInitialize); } public void ThreadedInitialize () { // Add the source, even though its empty, so that the user sees the // plugin is enabled, just no child sources yet. source_map = new Dictionary<string, DaapSource> (); container = new DaapContainerSource (); try { // Now start looking for services. // We do this after creating the source because if we do it before // there's a race condition where we get a service before the source // is added. locator = new ServiceLocator (); locator.Found += OnServiceFound; locator.Removed += OnServiceRemoved; locator.ShowLocalServices = true; locator_started = DateTime.Now; locator.Start (); proxy_server = new DaapProxyWebServer (); proxy_server.Start (); } catch (Exception e) { Log.Exception ("Failed to start DAAP client", e); } var uia_service = ServiceManager.Get<InterfaceActionService> (); uia_service.GlobalActions.Add ( new ActionEntry ("AddRemoteDaapServerAction", Stock.Add, Catalog.GetString ("Add Remote DAAP Server"), null, Catalog.GetString ("Add a new remote DAAP server"), OnAddRemoteServer) ); uia_service.UIManager.AddUiFromResource ("GlobalUI.xml"); } private void OnAddRemoteServer (object o, EventArgs args) { ResponseType response; string s_address; ushort port; using (OpenRemoteServer dialog = new OpenRemoteServer ()) { response = (ResponseType) dialog.Run (); s_address = dialog.Address; port = (ushort) dialog.Port; dialog.Destroy (); } if (response != ResponseType.Ok) return; Log.DebugFormat ("Trying to add DAAP server on {0}:{1}", s_address, port); IPHostEntry hostEntry = null; try { hostEntry = Dns.GetHostEntry (s_address); } catch (SocketException) { Log.Warning ("Unable to resolve host " + s_address); return; } IPAddress address = hostEntry.AddressList[0]; foreach (IPAddress curAdd in hostEntry.AddressList) { if (curAdd.AddressFamily == AddressFamily.InterNetwork) { address = curAdd; } } Log.DebugFormat (String.Format("Resolved {0} to {1}", s_address, address)); Log.Debug ("Spawning daap resolving thread"); DaapResolverJob job = new DaapResolverJob(s_address, address, port); job.Finished += delegate { Service service = job.DaapService; if (service != null) { AddDaapServer (service); Log.DebugFormat ("Created server {0}", service.Name); } else { Log.DebugFormat ("Unable to create service for {0}", s_address); } }; ServiceManager.JobScheduler.Add (job); } string IService.ServiceName { get { return "DaapService"; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// This is the base class for all controllers. Controllers are used to pull a single scalar /// piece of data from a data group, to be used to modify or trigger objects in the scene. /// </summary> public abstract class VisBaseController : MonoBehaviour, IVisManagerTarget { #region Defaults Static Class /// <summary> /// This internal class holds all of the defaults of the VisBaseController class. /// </summary> public static class Defaults { public static int controllerNameCounter = 0; public const string controllerName = "Default"; public const bool limitIncreaseRate = false; public const float increaseRate = 1.0f; public const bool limitDecreaseRate = true; public const float decreaseRate = 1.0f; } #endregion #region Constants /// <summary> /// This is the amount of time that the input values should act /// as if they changed in. For instance, if the value went up /// 0.1f in 0.05f seconds, the following would be the used value: /// adjustedChange = ((1.0f / 0.05f) * 0.1f) / mc_fTargetAdjustedDifferenceTime /// </summary> public const float mc_fTargetAdjustedDifferenceTime = 1.0f / 60.0f; #endregion #region IVisManagerTarget Implementation /// <summary> /// This is the vis manager that this modifier is targeting. /// </summary> //[HideInInspector()] [SerializeField()] private VisManager m_oVisManager = null; /// <summary> /// This is the name of the last manager that was set to this base modifier /// </summary> [HideInInspector()] [SerializeField()] private string m_szLastVisManagerName = null; /// <summary> /// This property gets/sets the target manager for this modifier. /// </summary> public VisManager Manager { get { return m_oVisManager; } set { if (m_oVisManager != null) m_oVisManager.RemoveController(this); if (value != null) value.AddController(this); m_oVisManager = value; if (m_oVisManager != null) m_szLastVisManagerName = m_oVisManager.name; else m_szLastVisManagerName = null; } } /// <summary> /// This gets the name of the last manager that was set to this target. /// </summary> public string LastManagerName { get { return m_szLastVisManagerName; } } #endregion #region Public Member Variables /// <summary> /// This is the name of this controller. /// </summary> //[HideInInspector()] public string controllerName = ""; /// <summary> /// This indicates if the increase rate of this controllers values should be limited. /// </summary> //[HideInInspector()] public bool limitIncreaseRate = Defaults.limitIncreaseRate; /// <summary> /// This is the rate at which the value of this controller can increase per second. /// </summary> //[HideInInspector()] public float increaseRate = Defaults.increaseRate; /// <summary> /// This indicates if the decrease rate of this controllers values should be limited. /// </summary> //[HideInInspector()] public bool limitDecreaseRate = Defaults.limitDecreaseRate; /// <summary> /// This is the rate at which the value of this controller can decrease per second. /// </summary> //[HideInInspector()] public float decreaseRate = Defaults.decreaseRate; #endregion #region Protected Member Variables /// <summary> /// This is the value of this controller from the previous frame. /// </summary> protected float m_fPreviousValue = 0.0f; /// <summary> /// This is the current value of this controller. /// </summary> protected float m_fValue = 0.0f; /// <summary> /// This is the difference of the current value and the previous value. /// </summary> protected float m_fValueDifference = 0.0f; /// <summary> /// This is the ADJUSTED difference of the current value and the previous value. /// The adjusted value is the change of the value as if it took place over a /// certain time period, controlled by mc_fTargetAdjustedDifferenceTime. The /// default of this essientially indicates a frame rate of 60 fps to determine /// the adjusted difference. This should be used for almost all difference /// calculations, as it is NOT frame rate dependent. /// </summary> protected float m_fAdjustedValueDifference = 0.0f; #endregion #region Private Member Variables /// <summary> /// This is the minimum value that this controller has ever been set to. /// </summary> private float m_fMinValue = 0.0f; /// <summary> /// This is the maximum value that this controller has ever beens set to. /// </summary> private float m_fMaxValue = 1.0f; #endregion #region Properties /// <summary> /// This gets the minimum value that this controller has ever been set to. /// </summary> public float MinValue { get { return m_fMinValue; } } /// <summary> /// This gets the maximum value that this controller has ever been set to. /// </summary> public float MaxValue { get { return m_fMaxValue; } } #endregion #region Init/Deinit Functions /// <summary> /// This function resets this controller to default values /// </summary> public virtual void Reset() { controllerName = Defaults.controllerName + (++Defaults.controllerNameCounter).ToString(); limitIncreaseRate = Defaults.limitIncreaseRate; increaseRate = Defaults.increaseRate; limitDecreaseRate = Defaults.limitDecreaseRate; decreaseRate = Defaults.decreaseRate; } /// <summary> /// This is called when this component is woken up. /// </summary> public virtual void Awake() { //make sure to restore the targets if needed VisManager.RestoreVisManagerTarget(this); //check if there is already a vis manager assigned to this data group if (m_oVisManager == null) { //try to grab a vis manager that belongs to this game object. m_oVisManager = GetComponent<VisManager>(); //check if a vis manager was found if (m_oVisManager == null) { //find all game objects with vis managers Object[] visManagers = GameObject.FindObjectsOfType(typeof(VisManager)); for (int i = 0; i < visManagers.Length; i++) { //get this manager and check if it is enabled VisManager manager = visManagers[i] as VisManager; if (manager.enabled) { //assign this vis manager m_oVisManager = manager; break; } } } } //validate manager ValidateManager(true); //make sure this data group is registered with it vis manager EnsureRegistered(); //log an error if no vis manager is assigned if (m_oVisManager == null) { Debug.LogError("This Controller does not have a VisManager assigned to it, nor could it find an active VisManager. In order to function, this Controller needs a VisManager!"); } } /// <summary> /// The main start function. /// </summary> public virtual void Start() { increaseRate = VisHelper.Validate(increaseRate, 0.00001f, 10000.0f, Defaults.increaseRate, this, "increaseRate", false); decreaseRate = VisHelper.Validate(decreaseRate, 0.00001f, 10000.0f, Defaults.decreaseRate, this, "decreaseRate", false); } /// <summary> /// This is called when this controller is destroyed. /// </summary> public virtual void OnDestroy() { if (m_oVisManager != null) m_oVisManager.RemoveController(this); } /// <summary> /// This validates the manager for this controller, ensuring it is in the same game object as this one. /// </summary> /// <param name="displayWarning">Indicates if a warning should be displayed.</param> /// <returns>Returns whether or not the manager is valid</returns> public bool ValidateManager(bool displayWarning) { if (m_oVisManager != null && m_oVisManager.gameObject != this.gameObject) { if (displayWarning) { Debug.LogWarning("This Controller (" + controllerName + ") is in a different Game Object than it's Manager (" + m_oVisManager.name + "). Please make sure it is attached to the same Game Object to prevent issues.", this); } return false; } return true; } /// <summary> /// This function makes sure that this controller is registered with its vis manager. /// </summary> public void EnsureRegistered() { if (m_oVisManager != null) m_oVisManager.AddController(this); } #endregion #region Update Functions /// <summary> /// This updates this controller. This should not be overridden! To implement custom controller functionality, override GetCustomControllerValue(). /// </summary> public void Update() { //set previous value m_fPreviousValue = m_fValue; //get the target value from the custom controller. float targetValue = GetCustomControllerValue(); //aproach target value if (targetValue < m_fValue && limitDecreaseRate) m_fValue = Mathf.MoveTowards(m_fValue, targetValue, decreaseRate * Time.deltaTime); else if (targetValue > m_fValue && limitIncreaseRate) m_fValue = Mathf.MoveTowards(m_fValue, targetValue, increaseRate * Time.deltaTime); else m_fValue = targetValue; //update value difference m_fValueDifference = m_fValue - m_fPreviousValue; //calculate adjusted value difference if (Mathf.Abs(m_fValueDifference) <= float.Epsilon) m_fAdjustedValueDifference = 0.0f; else m_fAdjustedValueDifference = ((1.0f / Mathf.Clamp(Time.deltaTime, 0.0001f, 0.5f)) * m_fValueDifference) / (1.0f / mc_fTargetAdjustedDifferenceTime); //update min/max values if (m_fValue < m_fMinValue) m_fMinValue = m_fValue; if (m_fValue > m_fMaxValue) m_fMaxValue = m_fValue; } #endregion #region Accessor Functions /// <summary> /// This function returns the current value for this controller. /// TO IMPLEMENT A CUSTOM CONTROLLER, override this function /// to return the current target value. /// </summary> /// <returns> /// The custom controller value. /// </returns> public virtual float GetCustomControllerValue() { return 0.0f; } /// <summary> /// This gets the current value of this controller. /// </summary> /// <returns> /// The current value. /// </returns> public float GetCurrentValue() { return m_fValue; } /// <summary> /// This gets the previous value of this controller. /// </summary> /// <returns> /// The previous value. /// </returns> public float GetPreviousValue() { return m_fPreviousValue; } /// <summary> /// This gets the value difference of this controller. /// </summary> /// <returns> /// The value difference. /// </returns> public float GetValueDifference() { return m_fValueDifference; } /// <summary> /// This gets the adjusted value difference of this controller. /// </summary> /// <returns> /// The adjusted value difference. /// </returns> public float GetAdjustedValueDifference() { return m_fAdjustedValueDifference; } #endregion #region Debug Functions /// <summary> /// This displays the debug information of this controller. /// </summary> /// <param name="x"> /// The x location to display this data group. /// </param> /// <param name="y"> /// The y location to display this data group. /// </param> /// <param name="barWidth"> /// This is the width in pixels of the debug bars. /// </param> /// <param name="barHeight"> /// This is the height in pixels of the debug bars. /// </param> /// <param name="separation"> /// This is the separation in pixels of the debug bars. /// </param> /// <param name="debugTexture"> /// This is the texture used to display the debug information. /// </param> /// <returns> /// This is the rect of the of the debug information that was displayed. /// </returns> public virtual Rect DisplayDebugGUI(int x, int y, int barWidth, int barHeight, int separation, Texture debugTexture) { //make sure there is a debug texture set if (debugTexture != null) { //calcuate initial vars int labelWidth = 150; int labelHeight = 20; int padding = 5; int frameWidth = Mathf.Max(barWidth, labelWidth) + padding * 2; int frameHeight = padding * 2 + labelHeight * 2 + barHeight; Rect frameRect = new Rect(x - padding, y - padding, frameWidth, frameHeight); //begin group and display labels GUI.BeginGroup(frameRect); GUI.color = new Color(0, 0, 0, 0.5f); GUI.DrawTexture(new Rect(0, 0, frameRect.width, frameRect.height), debugTexture); GUI.color = Color.white; GUI.Label(new Rect(padding, padding, labelWidth, labelHeight + 3), "Controller: \"" + controllerName + "\""); GUI.Label(new Rect(padding, padding + labelHeight, labelWidth, labelHeight + 3), "VALUE: " + GetCurrentValue().ToString("F4")); //draw data bar float perc = ((m_fValue - m_fMinValue) / (m_fMaxValue - m_fMinValue)) * 0.975f + 0.025f; GUI.DrawTexture(new Rect(padding, padding + labelHeight * 2, (int)(((float)barWidth)*perc), barHeight), debugTexture); //draw frame and end group GUI.color = Color.white; GUI.DrawTexture(new Rect(0, 0, frameWidth, 1), debugTexture); GUI.DrawTexture(new Rect(0, frameHeight - 1, frameWidth, 1), debugTexture); GUI.DrawTexture(new Rect(0, 0, 1, frameHeight), debugTexture); GUI.DrawTexture(new Rect(frameWidth - 1, 0, 1, frameHeight), debugTexture); GUI.EndGroup(); //return the rect of the frame that was drawn return frameRect; } return new Rect(0,0,0,0); } #endregion #region Object Class Functions /// <summary> /// This gets the string representation of this controller. /// </summary> /// <returns> /// The string of this data group. /// </returns> public override string ToString () { return "VisBaseController \"" + controllerName + "\""; } #endregion #region Target Restore Functions /// <summary> /// This attempts to restore the last set controller on the target. /// </summary> /// <param name="target">The target to restore.</param> /// <returns>Whether or not the target was restored.</returns> public static bool RestoreVisBaseControllerTarget(IVisBaseControllerTarget target) { //make sure the controller is set, and if not, check if there //is a name set and try and find that object as the controller if (target.Controller == null && target.LastControllerName != null && target.LastControllerName.Length > 0) { //try to get the manager for this target VisManager manager = null; if (target is IVisManagerTarget) manager = (target as IVisManagerTarget).Manager; //make sure a manager was found if (manager != null) { //loop through all controllers and make sure it was found for (int i = 0; i < manager.Controllers.Count; i++) { if (manager.Controllers[i].controllerName == target.LastControllerName) { target.Controller = manager.Controllers[i]; return true; } } } } return false; } #endregion } /// <summary> /// This interface is used to mark a class as being able to target a controller. /// </summary> public interface IVisBaseControllerTarget { /// <summary> /// This gets/sets the controller. /// </summary> VisBaseController Controller { get; set; } /// <summary> /// This gets the name of the last controller that was set to this target. /// </summary> string LastControllerName { get; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// JobOperations operations. /// </summary> internal partial class JobOperations : IServiceOperations<DataLakeAnalyticsJobManagementClient>, IJobOperations { /// <summary> /// Tests the existence of job information for the specified job ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// JobInfo ID to test the existence of. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<bool>> ExistsWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (this.Client.AdlaJobDnsSuffix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); tracingParameters.Add("jobIdentity", jobIdentity); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}"; _url = _url.Replace("{accountName}", accountName); _url = _url.Replace("{adlaJobDnsSuffix}", this.Client.AdlaJobDnsSuffix); _url = _url.Replace("{jobIdentity}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(jobIdentity, this.Client.SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("JobNotFound", StringComparison.OrdinalIgnoreCase)) { var _toReturn = new AzureOperationResponse<bool>(); _toReturn.Request = _httpRequest; _toReturn.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); _toReturn.Body = false; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _toReturn); } return _toReturn; } } } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<bool>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _result.Body = true; } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using XenAPI; using XenAdmin.Actions; using XenAdmin.Network; using XenAdmin.Core; namespace XenAdmin.Dialogs { public partial class RoleElevationDialog : XenDialogBase { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public Session elevatedSession = null; public string elevatedPassword; public string elevatedUsername; public string originalUsername; public string originalPassword; private List<Role> authorizedRoles; /// <summary> /// Displays a dialog informing the user they need a different role to complete the task, and offers the chance to switch user. Optionally logs /// out the elevated session. If successful exposes the elevated session, password and username as fields. /// </summary> /// <param name="connection">The current server connection with the role information</param> /// <param name="session">The session on which we have been denied access</param> /// <param name="authorizedRoles">A list of roles that are able to complete the task</param> /// <param name="actionTitle">A description of the current action, if null or empty will not be displayed</param> public RoleElevationDialog(IXenConnection connection, Session session, List<Role> authorizedRoles, string actionTitle) { InitializeComponent(); Image icon = SystemIcons.Exclamation.ToBitmap(); pictureBox1.Image = icon; pictureBox1.Width = icon.Width; pictureBox1.Height = icon.Height; this.connection = connection; UserDetails ud = session.CurrentUserDetails; labelCurrentUserValue.Text = ud.UserDisplayName ?? ud.UserName ?? Messages.UNKNOWN_AD_USER; labelCurrentRoleValue.Text = Role.FriendlyCSVRoleList(session.Roles); authorizedRoles.Sort((r1, r2) => r2.CompareTo(r1)); labelRequiredRoleValue.Text = Role.FriendlyCSVRoleList(authorizedRoles); labelServerValue.Text = Helpers.GetName(connection); labelServer.Text = Helpers.IsPool(connection) ? Messages.POOL_COLON : Messages.SERVER_COLON; originalUsername = session.Connection.Username; originalPassword = session.Connection.Password; if (string.IsNullOrEmpty(actionTitle)) { labelCurrentAction.Visible = false; labelCurrentActionValue.Visible = false; } else { labelCurrentActionValue.Text = actionTitle; } this.authorizedRoles = authorizedRoles; } private void buttonAuthorize_Click(object sender, EventArgs e) { try { Exception delegateException = null; log.Debug("Testing logging in with the new credentials"); DelegatedAsyncAction loginAction = new DelegatedAsyncAction(connection, Messages.AUTHORIZING_USER, Messages.CREDENTIALS_CHECKING, Messages.CREDENTIALS_CHECK_COMPLETE, delegate { try { elevatedSession = connection.ElevatedSession(TextBoxUsername.Text.Trim(), TextBoxPassword.Text); } catch (Exception ex) { delegateException = ex; } }); using (var dlg = new ActionProgressDialog(loginAction, ProgressBarStyle.Marquee, false)) dlg.ShowDialog(this); // The exception would have been handled by the action progress dialog, just return the user to the sudo dialog if (loginAction.Exception != null) return; if(HandledAnyDelegateException(delegateException)) return; if (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession)) { elevatedUsername = TextBoxUsername.Text.Trim(); elevatedPassword = TextBoxPassword.Text; DialogResult = DialogResult.OK; Close(); return; } ShowNotAuthorisedDialog(); return; } catch (Exception ex) { log.DebugFormat("Exception when attempting to sudo action: {0} ", ex); using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, String.Format(Messages.USER_AUTHORIZATION_FAILED, TextBoxUsername.Text), Messages.XENCENTER))) { dlg.ShowDialog(Parent); } } finally { // Check whether we have a successful elevated session and whether we have been asked to log it out // If non successful (most likely the new subject is not authorized) then log it out anyway. if (elevatedSession != null && DialogResult != DialogResult.OK) { elevatedSession.Connection.Logout(elevatedSession); elevatedSession = null; } } } private bool HandledAnyDelegateException(Exception delegateException) { if (delegateException != null) { Failure f = delegateException as Failure; if (f != null && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) { ShowNotAuthorisedDialog(); return true; } throw delegateException; } return false; } private void ShowNotAuthorisedDialog() { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, Messages.USER_NOT_AUTHORIZED, Messages.PERMISSION_DENIED))) { dlg.ShowDialog(this); } } private bool SessionAuthorized(Session s) { UserDetails ud = s.CurrentUserDetails; foreach (Role r in s.Roles) { if (authorizedRoles.Contains(r)) { log.DebugFormat("Subject '{0}' is authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid); return true; } } log.DebugFormat("Subject '{0}' is not authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid); return false; } private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void UpdateButtons() { buttonAuthorize.Enabled = TextBoxUsername.Text.Trim() != "" && TextBoxPassword.Text != ""; } private void TextBoxUsername_TextChanged(object sender, EventArgs e) { UpdateButtons(); } private void TextBoxPassword_TextChanged(object sender, EventArgs e) { UpdateButtons(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using DotVVM.Framework.Compilation.Parser.Binding.Tokenizer; using DotVVM.Framework.Compilation.Parser.Dothtml.Parser; using System.Reflection; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace DotVVM.Framework.Compilation.Parser.Binding.Parser { public class BindingParser : ParserBase<BindingToken, BindingTokenType> { public BindingParser() : base(BindingTokenType.WhiteSpace) { } public BindingParserNode ReadDirectiveValue() { var startIndex = CurrentIndex; var first = ReadNamespaceOrTypeName(); if (Peek() != null) { var @operator = PeekOrFail().Type; if (@operator == BindingTokenType.AssignOperator) { Read(); var second = ReadNamespaceOrTypeName(); if (first is SimpleNameBindingParserNode) { return CreateNode(new BinaryOperatorBindingParserNode(first, second, @operator), startIndex); } else { first.NodeErrors.Add("Only simple name is allowed as alias."); } } else { first.NodeErrors.Add($"Unexpected operator: {@operator}, expecting assignment (=)."); } } return first; } public BindingParserNode ReadDirectiveTypeName() { var startIndex = CurrentIndex; var typeName = ReadNamespaceOrTypeName(); if (PeekType() == BindingTokenType.Comma) { Read(); var assemblyName = ReadNamespaceOrTypeName(); // SimpleNameBinding means that assembly name does not contain dots // MemberAccessBinding means that assembly name is complex (multiple identifiers delimited with dots) if (!(assemblyName is SimpleNameBindingParserNode || assemblyName is MemberAccessBindingParserNode)) { assemblyName.NodeErrors.Add($"Expected assembly name but instead got {assemblyName.GetType().Name}."); } else if (assemblyName is MemberAccessBindingParserNode) { // Make sure there is no GenericNameBinding within assemblyName var assemblyBinding = assemblyName; while (assemblyBinding is MemberAccessBindingParserNode assemblyMemberBinding) { var memberExprType = assemblyMemberBinding.MemberNameExpression.GetType(); var targetExprType = assemblyMemberBinding.TargetExpression.GetType(); if (memberExprType == typeof(GenericTypeReferenceBindingParserNode) || targetExprType == typeof(GenericTypeReferenceBindingParserNode)) { assemblyName.NodeErrors.Add($"Generic identifier name is not allowed in an assembly name."); break; } assemblyBinding = assemblyMemberBinding.TargetExpression; } } return new AssemblyQualifiedNameBindingParserNode(typeName, assemblyName); } else if (Peek() is BindingToken token) { typeName.NodeErrors.Add($"Unexpected operator: {token.Type}, expecting `,` or end."); } return typeName; } public BindingParserNode ReadNamespaceOrTypeName() { return ReadIdentifierExpression(true); } public BindingParserNode ReadMultiExpression() { var startIndex = CurrentIndex; var expressions = new List<BindingParserNode>(); expressions.Add(ReadExpression()); int lastIndex = -1; while (!OnEnd()) { if (lastIndex == CurrentIndex) { var extraToken = Read()!; expressions.Add(CreateNode(new LiteralExpressionBindingParserNode(extraToken.Text), lastIndex, "Unexpected token")); } lastIndex = CurrentIndex; var extraNode = ReadExpression(); extraNode.NodeErrors.Add("Operator expected before this expression."); expressions.Add(extraNode); } return CreateNode(new MultiExpressionBindingParserNode(expressions), startIndex, Peek() is BindingToken token ? $"Unexpected token: {token.Text}" : null); } public BindingParserNode ReadExpression() { var startIndex = CurrentIndex; SkipWhiteSpace(); return CreateNode(ReadSemicolonSeparatedExpression(), startIndex); } public bool OnEnd() { return CurrentIndex >= Tokens.Count; } private BindingParserNode ReadSemicolonSeparatedExpression() { var startFirstIndex = CurrentIndex; var first = ReadUnsupportedOperatorExpression(); if (Peek() is BindingToken operatorToken && operatorToken.Type == BindingTokenType.Semicolon) { first = CreateVoidBlockIfBlankIdentifier(first, startFirstIndex); Read(); var secondStartIndex = CurrentIndex; var second = Peek() == null ? CreateNode(new VoidBindingParserNode(), secondStartIndex) : ReadSemicolonSeparatedExpression(); second = CreateVoidBlockIfBlankIdentifier(second, secondStartIndex); first = CreateNode(new BlockBindingParserNode(first, second), startFirstIndex); } return first; } private BindingParserNode CreateVoidBlockIfBlankIdentifier(BindingParserNode originalNode, int startIndex) { if (IsBlankIdentifier(originalNode)) { originalNode = CreateNode(new VoidBindingParserNode(), startIndex); } return originalNode; } private bool IsBlankIdentifier(BindingParserNode second) => second is IdentifierNameBindingParserNode identifier && identifier.Name.Length == 0; private BindingParserNode ReadUnsupportedOperatorExpression() { var startIndex = CurrentIndex; var first = ReadAssignmentExpression(); if (Peek() is BindingToken operatorToken && operatorToken.Type == BindingTokenType.UnsupportedOperator) { Read(); var second = ReadUnsupportedOperatorExpression(); first = CreateNode(new BinaryOperatorBindingParserNode(first, second, BindingTokenType.UnsupportedOperator), startIndex, $"Unsupported operator: {operatorToken.Text}"); } return first; } private BindingParserNode ReadAssignmentExpression() { var startIndex = CurrentIndex; var first = ReadConditionalExpression(); if (Peek() is BindingToken operatorToken && operatorToken.Type == BindingTokenType.AssignOperator) { Read(); var second = ReadAssignmentExpression(); return CreateNode(new BinaryOperatorBindingParserNode(first, second, BindingTokenType.AssignOperator), startIndex); } else return first; } private BindingParserNode ReadConditionalExpression() { var startIndex = CurrentIndex; var first = ReadNullCoalescingExpression(); if (Peek() is BindingToken operatorToken && operatorToken.Type == BindingTokenType.QuestionMarkOperator) { Read(); var second = ReadConditionalExpression(); var error = IsCurrentTokenIncorrect(BindingTokenType.ColonOperator); Read(); var third = ReadConditionalExpression(); return CreateNode(new ConditionalExpressionBindingParserNode(first, second, third), startIndex, error ? "The ':' was expected." : null); } else { return first; } } private BindingParserNode ReadNullCoalescingExpression() { var startIndex = CurrentIndex; var first = ReadOrElseExpression(); while (Peek() is BindingToken operatorToken && operatorToken.Type == BindingTokenType.NullCoalescingOperator) { Read(); var second = ReadOrElseExpression(); first = CreateNode(new BinaryOperatorBindingParserNode(first, second, BindingTokenType.NullCoalescingOperator), startIndex); } return first; } private BindingParserNode ReadOrElseExpression() { var startIndex = CurrentIndex; var first = ReadAndAlsoExpression(); while (Peek() is BindingToken operatorToken && operatorToken.Type == BindingTokenType.OrElseOperator) { Read(); var second = ReadAndAlsoExpression(); first = CreateNode(new BinaryOperatorBindingParserNode(first, second, BindingTokenType.OrElseOperator), startIndex); } return first; } private BindingParserNode ReadAndAlsoExpression() { var startIndex = CurrentIndex; var first = ReadOrExpression(); while (Peek() is BindingToken operatorToken && operatorToken.Type == BindingTokenType.AndAlsoOperator) { Read(); var second = ReadOrElseExpression(); first = CreateNode(new BinaryOperatorBindingParserNode(first, second, BindingTokenType.AndAlsoOperator), startIndex); } return first; } private BindingParserNode ReadOrExpression() { var startIndex = CurrentIndex; var first = ReadAndExpression(); while (Peek() is BindingToken operatorToken && operatorToken.Type == BindingTokenType.OrOperator) { Read(); var second = ReadAndExpression(); first = CreateNode(new BinaryOperatorBindingParserNode(first, second, BindingTokenType.OrOperator), startIndex); } return first; } private BindingParserNode ReadAndExpression() { var startIndex = CurrentIndex; var first = ReadEqualityExpression(); while (Peek() is BindingToken operatorToken && operatorToken.Type == BindingTokenType.AndOperator) { Read(); var second = ReadEqualityExpression(); first = CreateNode(new BinaryOperatorBindingParserNode(first, second, BindingTokenType.AndOperator), startIndex); } return first; } private BindingParserNode ReadEqualityExpression() { var startIndex = CurrentIndex; var first = ReadComparisonExpression(); while (Peek() is BindingToken operatorToken) { var @operator = operatorToken.Type; if (@operator == BindingTokenType.EqualsEqualsOperator || @operator == BindingTokenType.NotEqualsOperator) { Read(); var second = ReadComparisonExpression(); first = CreateNode(new BinaryOperatorBindingParserNode(first, second, @operator), startIndex); } else break; } return first; } private BindingParserNode ReadComparisonExpression() { var startIndex = CurrentIndex; var first = ReadAdditiveExpression(); while (Peek() is BindingToken operatorToken) { var @operator = operatorToken.Type; if (@operator == BindingTokenType.LessThanEqualsOperator || @operator == BindingTokenType.LessThanOperator || @operator == BindingTokenType.GreaterThanEqualsOperator || @operator == BindingTokenType.GreaterThanOperator) { Read(); var second = ReadAdditiveExpression(); first = CreateNode(new BinaryOperatorBindingParserNode(first, second, @operator), startIndex); } else break; } return first; } private BindingParserNode ReadAdditiveExpression() { var startIndex = CurrentIndex; var first = ReadMultiplicativeExpression(); while (Peek() is BindingToken operatorToken) { var @operator = operatorToken.Type; if (@operator == BindingTokenType.AddOperator || @operator == BindingTokenType.SubtractOperator) { Read(); var second = ReadMultiplicativeExpression(); first = CreateNode(new BinaryOperatorBindingParserNode(first, second, @operator), startIndex); } else break; } return first; } private BindingParserNode ReadMultiplicativeExpression() { var startIndex = CurrentIndex; var first = ReadUnaryExpression(); while (Peek() is BindingToken operatorToken) { var @operator = operatorToken.Type; if (@operator == BindingTokenType.MultiplyOperator || @operator == BindingTokenType.DivideOperator || @operator == BindingTokenType.ModulusOperator) { Read(); var second = ReadUnaryExpression(); first = CreateNode(new BinaryOperatorBindingParserNode(first, second, @operator), startIndex); } else break; } return first; } private BindingParserNode ReadUnaryExpression() { var startIndex = CurrentIndex; SkipWhiteSpace(); if (Peek() is BindingToken operatorToken) { var @operator = operatorToken.Type; var isOperatorUnsupported = @operator == BindingTokenType.UnsupportedOperator; if (@operator == BindingTokenType.NotOperator || @operator == BindingTokenType.SubtractOperator || isOperatorUnsupported) { Read(); var target = ReadUnaryExpression(); return CreateNode(new UnaryOperatorBindingParserNode(target, @operator), startIndex, isOperatorUnsupported ? $"Unsupported operator {operatorToken.Text}" : null); } } return CreateNode(ReadLambdaExpression(), startIndex); } private BindingParserNode ReadLambdaExpression() { var startIndex = CurrentIndex; SetRestorePoint(); // Try to read lambda parameters if (!TryReadLambdaParametersExpression(out var parameters) || PeekType() != BindingTokenType.LambdaOperator) { // Fail - we should try to parse as an expression Restore(); return CreateNode(ReadIdentifierExpression(false), startIndex); } // Read lambda operator Read(); SkipWhiteSpace(); ClearRestorePoint(); // Read lambda body expression var body = ReadExpression(); return CreateNode(new LambdaBindingParserNode(parameters, body), startIndex); } private bool TryReadLambdaParametersExpression(out List<LambdaParameterBindingParserNode> parameters) { var startIndex = CurrentIndex; var waitingForParameter = false; parameters = new List<LambdaParameterBindingParserNode>(); if (PeekType() == BindingTokenType.OpenParenthesis) { // Begin parameters parsing - read opening parenthesis Read(); SkipWhiteSpace(); while (PeekType() != BindingTokenType.CloseParenthesis) { // Try read parameter definition (either implicitly defined type or explicitly) if (!TryReadLambdaParameterDefinition(out var typeDef, out var nameDef)) return false; parameters.Add(new LambdaParameterBindingParserNode(typeDef, nameDef!)); waitingForParameter = false; if (PeekType() == BindingTokenType.Comma) { Read(); SkipWhiteSpace(); waitingForParameter = true; } else { // If next is not comma then we must be finished break; } } // End parameters parsing - read closing parenthesis if (PeekType() != BindingTokenType.CloseParenthesis) return false; Read(); SkipWhiteSpace(); } else { // Support lambdas with single implicit parameter and no parentheses: arg => Method(arg) var parameter = ReadIdentifierExpression(false); if (parameter.HasNodeErrors) return false; parameters.Add(new LambdaParameterBindingParserNode(null, CreateNode(parameter, startIndex))); } if (waitingForParameter) return false; return true; } private bool TryReadLambdaParameterDefinition(out TypeReferenceBindingParserNode? type, out BindingParserNode? name) { name = null; type = null; if (PeekType() != BindingTokenType.Identifier) return false; if (!TryReadTypeReference(out type)) return false; SkipWhiteSpace(); if (PeekType() != BindingTokenType.Identifier) { name = type; type = null; return true; } else { name = ReadIdentifierExpression(true); } // Name must always be a simple name binding if (!(name is SimpleNameBindingParserNode)) return false; return true; } private bool TryReadTypeReference([NotNullWhen(returnValue: true)] out TypeReferenceBindingParserNode? typeNode) { typeNode = null; var startIndex = CurrentIndex; var expression = ReadIdentifierNameExpression() as BindingParserNode; var next = Peek(); int previousIndex = -1; while (next != null && previousIndex != CurrentIndex) { previousIndex = CurrentIndex; if (next.Type == BindingTokenType.Dot) { // Member access Read(); var member = ReadIdentifierNameExpression(); expression = CreateNode(new MemberAccessBindingParserNode(expression, member), startIndex); } else if (next.Type == BindingTokenType.LessThanOperator) { // Generic if (!TryReadGenericArguments(startIndex, expression, out var typeOrFunction)) return false; expression = typeOrFunction!.ToTypeReference(); } else if (next.Type == BindingTokenType.QuestionMarkOperator) { // Nullable Read(); var typeExpr = expression as TypeReferenceBindingParserNode ?? new ActualTypeReferenceBindingParserNode(expression); expression = CreateNode(new NullableTypeReferenceBindingParserNode(typeExpr), startIndex); } else if (next.Type == BindingTokenType.OpenArrayBrace) { // Array Read(); next = Peek(); if (next?.Type != BindingTokenType.CloseArrayBrace) return false; Read(); var typeExpr = expression as TypeReferenceBindingParserNode ?? new ActualTypeReferenceBindingParserNode(expression); expression = CreateNode(new ArrayTypeReferenceBindingParserNode(typeExpr), startIndex); } else { break; } next = Peek(); } typeNode = expression as TypeReferenceBindingParserNode ?? new ActualTypeReferenceBindingParserNode(expression); return true; } private BindingParserNode ReadIdentifierExpression(bool onlyTypeName) { var startIndex = CurrentIndex; BindingParserNode expression = onlyTypeName ? ReadIdentifierNameExpression() : ReadAtomicExpression(); var next = Peek(); int previousIndex = -1; while (next != null && previousIndex != CurrentIndex) { previousIndex = CurrentIndex; if (next.Type == BindingTokenType.Dot) { // member access Read(); var member = ReadIdentifierNameExpression(); if (expression is TypeOrFunctionReferenceBindingParserNode typeOrFunction) expression = typeOrFunction.ToTypeReference(); expression = CreateNode(new MemberAccessBindingParserNode(expression, member), startIndex); } else if (next.Type == BindingTokenType.LessThanOperator) { if (TryReadGenericArguments(startIndex, expression, out var typeOrFunction)) { // This is a generic identifier that can be either a type or a function expression = typeOrFunction; } } else if (!onlyTypeName && next.Type == BindingTokenType.OpenParenthesis) { if (expression is TypeOrFunctionReferenceBindingParserNode typeOrFunction) expression = typeOrFunction.ToFunctionReference(); expression = ReadFunctionCall(startIndex, expression); } else if (!onlyTypeName && next.Type == BindingTokenType.OpenArrayBrace) { expression = ReadArrayAccess(startIndex, expression); } else if (!onlyTypeName && next.Type == BindingTokenType.Identifier && expression is SimpleNameBindingParserNode keywordNameExpression) { // we have `identifier identifier` - the first one must be a KEYWORD USAGE var keyword = keywordNameExpression.Name; if (keyword == "var") { return ReadVariableExpression(startIndex); } else if (keyword == "val" || keyword == "let" || keyword == "const") { expression = CreateNode(expression, startIndex, $"Variable declaration using {keyword} is not supported. Did you intend to use the var keyword?"); } else { expression = CreateNode(expression, startIndex, $"Expression '{expression.ToDisplayString()}' cannot be followed by an identifier. Did you intent to declare a variable using the var keyword?"); } } else { break; } next = Peek(); } return expression; } private BindingParserNode ReadVariableExpression(int startIndex) { var variableName = ReadIdentifierNameExpression(); if (!(variableName is SimpleNameBindingParserNode)) { variableName = CreateNode(variableName, variableName.StartPosition, $"Variable name cannot be generic, please use the `var {variableName.Name} = X` syntax."); } var incorrectEquals = IsCurrentTokenIncorrect(BindingTokenType.AssignOperator); if (!incorrectEquals) { Read(); } var value = ReadSemicolonSeparatedExpression(); if (value is BlockBindingParserNode resultBlock) { return CreateNode( new BlockBindingParserNode(resultBlock.FirstExpression, resultBlock.SecondExpression, variableName), startIndex, !incorrectEquals ? null : $"Expected variable declaration `var {variableName.Name} = {resultBlock.FirstExpression}`"); } else { return CreateNode(value, startIndex, $"Variable declaration must be followed by a semicolon and another expression. Please add the return value after `var {variableName.Name} = {value}; ...` or remove the `var {variableName.Name} = ` in case you only want to invoke the expression."); } } private BindingParserNode ReadArrayAccess(int startIndex, BindingParserNode expression) { // array access Read(); var innerExpression = ReadExpression(); var error = IsCurrentTokenIncorrect(BindingTokenType.CloseArrayBrace); Read(); SkipWhiteSpace(); expression = CreateNode(new ArrayAccessBindingParserNode(expression, innerExpression), startIndex, error ? "The ']' was expected." : null); return expression; } private BindingParserNode ReadFunctionCall(int startIndex, BindingParserNode expression) { // function call Read(); var arguments = new List<BindingParserNode>(); int previousInnerIndex = -1; while (Peek() is BindingToken operatorToken && operatorToken.Type != BindingTokenType.CloseParenthesis && previousInnerIndex != CurrentIndex) { previousInnerIndex = CurrentIndex; if (arguments.Count > 0) { SkipWhiteSpace(); if (IsCurrentTokenIncorrect(BindingTokenType.Comma)) arguments.Add(CreateNode(new LiteralExpressionBindingParserNode(null), CurrentIndex, "The ',' was expected")); else Read(); } arguments.Add(ReadExpression()); } var error = IsCurrentTokenIncorrect(BindingTokenType.CloseParenthesis); Read(); SkipWhiteSpace(); expression = CreateNode(new FunctionCallBindingParserNode(expression, arguments), startIndex, error ? "The ')' was expected." : null); return expression; } private BindingParserNode ReadAtomicExpression() { var startIndex = CurrentIndex; SkipWhiteSpace(); var token = Peek(); if (token != null && token.Type == BindingTokenType.OpenParenthesis) { // parenthesized expression Read(); var innerExpression = ReadExpression(); var error = IsCurrentTokenIncorrect(BindingTokenType.CloseParenthesis); Read(); SkipWhiteSpace(); return CreateNode(new ParenthesizedExpressionBindingParserNode(innerExpression), startIndex, error ? "The ')' was expected." : null); } else if (token != null && token.Type == BindingTokenType.StringLiteralToken) { // string literal Read(); SkipWhiteSpace(); var node = CreateNode(new LiteralExpressionBindingParserNode(ParseStringLiteral(token.Text, out var error)), startIndex); if (error != null) { node.NodeErrors.Add(error); } return node; } else if (token != null && token.Type == BindingTokenType.InterpolatedStringToken) { // interpolated string Read(); SkipWhiteSpace(); var (format, arguments) = ParseInterpolatedString(token, out var error); var node = CreateNode(new InterpolatedStringBindingParserNode(format, arguments), startIndex); if (error != null) { node.NodeErrors.Add(error); } return node; } else { // identifier return CreateNode(ReadConstantExpression(), startIndex); } } private BindingParserNode ReadConstantExpression() { var startIndex = CurrentIndex; SkipWhiteSpace(); if (Peek() is BindingToken identifier && identifier.Type == BindingTokenType.Identifier) { if (identifier.Text == "true" || identifier.Text == "false") { Read(); SkipWhiteSpace(); return CreateNode(new LiteralExpressionBindingParserNode(identifier.Text == "true"), startIndex); } else if (identifier.Text == "null") { Read(); SkipWhiteSpace(); return CreateNode(new LiteralExpressionBindingParserNode(null), startIndex); } else if (Char.IsDigit(identifier.Text[0])) { // number value var number = ParseNumberLiteral(identifier.Text, out var error); Read(); SkipWhiteSpace(); var node = CreateNode(new LiteralExpressionBindingParserNode(number), startIndex); if (error is object) { node.NodeErrors.Add(error); } return node; } } return CreateNode(ReadIdentifierNameExpression(), startIndex); } private IdentifierNameBindingParserNode ReadIdentifierNameExpression() { var startIndex = CurrentIndex; SkipWhiteSpace(); if (Peek() is BindingToken identifier && identifier.Type == BindingTokenType.Identifier) { Read(); SkipWhiteSpace(); return CreateNode(new SimpleNameBindingParserNode(identifier), startIndex); } // create virtual empty identifier expression return CreateIdentifierExpected(startIndex); } private SimpleNameBindingParserNode CreateIdentifierExpected(int startIndex) { return CreateNode( new SimpleNameBindingParserNode("") { NodeErrors = { "Identifier name was expected!" } }, startIndex); } private bool TryReadGenericArguments(int startIndex, BindingParserNode type, [NotNullWhen(returnValue: true)] out TypeOrFunctionReferenceBindingParserNode? typeOrFunction) { Assert(BindingTokenType.LessThanOperator); SetRestorePoint(); var next = Read(); bool failure = false; var previousIndex = -1; var arguments = new List<TypeReferenceBindingParserNode>(); while (true) { if (previousIndex == CurrentIndex || next == null) { failure = true; break; } previousIndex = CurrentIndex; SkipWhiteSpace(); if (!TryReadTypeReference(out var argument)) failure = true; else arguments.Add(argument); SkipWhiteSpace(); if (PeekType() != BindingTokenType.Comma) { break; } Read(); } failure |= PeekType() != BindingTokenType.GreaterThanOperator; if (!failure) { Read(); ClearRestorePoint(); typeOrFunction = CreateNode(new TypeOrFunctionReferenceBindingParserNode(type, arguments), startIndex); return true; } Restore(); typeOrFunction = null; return false; } private BindingParserNode ReadFormattedExpression() { var startIndex = CurrentIndex; BindingParserNode? node; SkipWhiteSpace(); // 1) Parse expression if (Peek() is BindingToken operatorToken && operatorToken.Type == BindingTokenType.OpenParenthesis) { // Conditional expressions must be enclosed in parentheses Read(); SkipWhiteSpace(); node = ReadConditionalExpression(); SkipWhiteSpace(); if (IsCurrentTokenIncorrect(BindingTokenType.CloseParenthesis)) { node.NodeErrors.Add("Expected ')' after this expression."); } else { Read(); } } else { // If expression is not enclosed in parentheses, read null coalescing expression node = ReadNullCoalescingExpression(); } SkipWhiteSpace(); // 2) Parse formatting component (optional) if (Peek() is BindingToken delimitingToken && delimitingToken.Type == BindingTokenType.ColonOperator) { Read(); if (IsCurrentTokenIncorrect(BindingTokenType.Identifier)) { node.NodeErrors.Add("Expected an identifier after ':'. The identifier should specify formatting for the previous expression!"); } // Scan all remaining tokens BindingToken? currentToken; var formatTokens = new List<BindingToken>(); while ((currentToken = Read()) != null) formatTokens.Add(currentToken); var format = $"{{0:{string.Concat(formatTokens.Select(token => token.Text))}}}"; return CreateNode(new FormattedBindingParserNode(node, format), startIndex); } SkipWhiteSpace(); if (Peek() != null) { if (Peek()!.Type == BindingTokenType.QuestionMarkOperator) { // If it seems that user tried to use conditional expression, provide more concrete error message node.NodeErrors.Add("Conditional expression needs to be enclosed in parentheses."); } else { node.NodeErrors.Add($"Expected end of interpolated expression, but instead found {Peek()!.Type}"); } } return node; } private static object? ParseNumberLiteral(string text, out string? error) { text = text.ToLowerInvariant(); error = null; NumberLiteralSuffix type = NumberLiteralSuffix.None; var lastDigit = text[text.Length - 1]; if (ParseNumberLiteralSuffix(ref text, ref error, lastDigit, ref type)) return null; if (ParseNumberLiteralDoubleFloat(text, ref error, type, out var numberLiteral)) return numberLiteral; const NumberStyles integerStyle = NumberStyles.AllowLeadingSign; // try parse integral constant object? result = null; if (type == NumberLiteralSuffix.None) { result = TryParse<int>(int.TryParse, text, integerStyle) ?? TryParse<uint>(uint.TryParse, text, integerStyle) ?? TryParse<long>(long.TryParse, text, integerStyle) ?? TryParse<ulong>(ulong.TryParse, text, integerStyle); } else if (type == NumberLiteralSuffix.Unsigned) { result = TryParse<uint>(uint.TryParse, text, integerStyle) ?? TryParse<ulong>(ulong.TryParse, text, integerStyle); } else if (type == NumberLiteralSuffix.Long) { result = TryParse<long>(long.TryParse, text, integerStyle) ?? TryParse<ulong>(ulong.TryParse, text, integerStyle); } else if (type == NumberLiteralSuffix.UnsignedLong) { result = TryParse<ulong>(ulong.TryParse, text, integerStyle); } if (result != null) return result; // handle errors // if all are digits, or '0x' + hex digits => too large number if (text.All(char.IsDigit) || (text.StartsWith("0x", StringComparison.Ordinal) && text.Skip(2).All(c => char.IsDigit(c) || (c >= 'a' && c <= 'f')))) error = $"number number {text} is too large for integral literal, try to append 'd' to real number literal"; else error = $"could not parse {text} as numeric literal"; return null; } private static bool ParseNumberLiteralDoubleFloat(string text, ref string? error, NumberLiteralSuffix type, out object? numberLiteral) { numberLiteral = null; if (text.Contains(".") || text.Contains("e") || type == NumberLiteralSuffix.Float || type == NumberLiteralSuffix.Double) { const NumberStyles decimalStyle = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint; // real number switch (type) { case NumberLiteralSuffix.None: // double is default case NumberLiteralSuffix.Double: { numberLiteral = TryParse<double>(double.TryParse, text, out error, decimalStyle); return true; } case NumberLiteralSuffix.Float: { numberLiteral = TryParse<float>(float.TryParse, text, out error, decimalStyle); return true; } case NumberLiteralSuffix.Decimal: { numberLiteral = TryParse<decimal>(decimal.TryParse, text, out error, decimalStyle); return true; } default: error = $"could not parse real number of type {type}"; { return true; } } } return false; } private static bool ParseNumberLiteralSuffix(ref string text, ref string? error, char lastDigit, ref NumberLiteralSuffix type) { if (char.IsLetter(lastDigit)) { // number type suffix if (lastDigit == 'm') type = NumberLiteralSuffix.Decimal; else if (lastDigit == 'f') type = NumberLiteralSuffix.Float; else if (lastDigit == 'd') type = NumberLiteralSuffix.Double; else if (text.EndsWith("ul", StringComparison.Ordinal) || text.EndsWith("lu", StringComparison.Ordinal)) type = NumberLiteralSuffix.UnsignedLong; else if (lastDigit == 'u') type = NumberLiteralSuffix.Unsigned; else if (lastDigit == 'l') type = NumberLiteralSuffix.Long; else { error = "number literal type suffix not known"; return true; } if (type == NumberLiteralSuffix.UnsignedLong) text = text.Remove(text.Length - 2); // remove 2 last chars else text = text.Remove(text.Length - 1); // remove last char } return false; } private delegate bool TryParseDelegate<T>(string text, NumberStyles styles, IFormatProvider format, out T result); private static object? TryParse<T>(TryParseDelegate<T> method, string text, out string? error, NumberStyles styles) { error = null; if (method(text, styles, CultureInfo.InvariantCulture, out var result)) return result; error = $"could not parse { text } using { method.GetMethodInfo()?.DeclaringType?.FullName + "." + method.GetMethodInfo()?.Name }"; return null; } private static object? TryParse<T>(TryParseDelegate<T> method, string text, NumberStyles styles) { if (method(text, styles, CultureInfo.InvariantCulture, out var result)) return result; return null; } private static string ParseStringLiteral(string text, out string? error) { error = null; var sb = new StringBuilder(); var index = 1; while (index < text.Length - 1) { if (TryParseCharacter(text, ref index, out var character, out var innerError)) { sb.Append(character); } else { error = innerError; } } return sb.ToString(); } private static bool TryParseCharacter(string text, ref int index, out char character, out string? error) { var result = TryPeekCharacter(text, index, out var count, out character, out error); index += count; return result; } private static bool TryPeekCharacter(string text, int index, out int length, out char character, out string? error) { if (text[index] == '\\') { // handle escaped characters length = 2; index++; if (index == text.Length - 1) { error = "The escape character cannot be at the end of the string literal!"; character = default; return false; } else if (text[index] == '\'' || text[index] == '"' || text[index] == '\\') { character = text[index]; } else if (text[index] == 'n') { character = '\n'; } else if (text[index] == 'r') { character = '\r'; } else if (text[index] == 't') { character = '\t'; } else { error = "The escape sequence is either not valid or not supported in dotVVM bindings!"; character = default; return false; } error = default; return true; } else { character = text[index]; error = default; length = 1; return true; } } private static (string, List<BindingParserNode>) ParseInterpolatedString(BindingToken token, out string? error) { error = null; var sb = new StringBuilder(); var arguments = new List<BindingParserNode>(); var text = token.Text; var index = 2; while (index < text.Length - 1) { if (TryParseCharacter(text, ref index, out var current, out var innerError)) { var hasNext = TryPeekCharacter(text, index, out var length, out var next, out _); if (hasNext && current == next && (current == '{' || current == '}')) { // If encountered double '{' or '}' do not treat is as an control character sb.Append(current); index += length; } else if (current == '{') { if (!TryParseInterpolationExpression(text, index, token.StartPosition, out var end, out var argument, out innerError)) { arguments.Clear(); error = string.Concat(error, " Interpolation expression is malformed. ", innerError).TrimStart(); return (string.Empty, arguments); } arguments.Add(argument!); sb.Append("{" + (arguments.Count - 1).ToString() + "}"); index = end + 1; } else if (current == '}') { innerError = "Could not find matching opening character '{' for an interpolated expression."; error = string.Concat(error, " Interpolation expression is malformed. ", innerError).TrimStart(); return (string.Empty, arguments); } else { sb.Append(current); } } else { error = innerError; index++; } } return (sb.ToString(), arguments); } private static bool TryParseInterpolationExpression(string text, int positionInToken, int tokenPositionInBinding, out int end, out BindingParserNode? expression, out string? error) { var index = positionInToken; var foundEnd = false; var exprDepth = 0; while (index < text.Length) { var current = text[index++]; if (current == '{') { exprDepth++; } if (current == '}') { if (exprDepth == 0) { foundEnd = true; break; } exprDepth--; } } if (!foundEnd) { end = -1; expression = null; error = "Could not find matching closing character '}' for an interpolated expression."; return false; } end = index - 1; if (positionInToken == end) { // Provided expression is empty expression = null; error = "Expected expression, but instead found empty \"{}\"."; return false; } error = null; var rawExpression = text.Substring(positionInToken, end - positionInToken); var innerExpressionTokenizer = new BindingTokenizer(tokenPositionInBinding + positionInToken); innerExpressionTokenizer.Tokenize(rawExpression); var innerExpressionParser = new BindingParser() { Tokens = innerExpressionTokenizer.Tokens }; expression = innerExpressionParser.ReadFormattedExpression(); // For Visual Studio extension we need to know also leading whitespaces // Note that these are by default omitted by binding parser if (innerExpressionTokenizer.Tokens.FirstOrDefault()?.Type == BindingTokenType.WhiteSpace) { var token = innerExpressionTokenizer.Tokens.First(); expression.StartPosition -= token.Length; expression.Tokens.Insert(0, token); } if (expression.HasNodeErrors) { error = string.Join(" ", new[] { $"Error while parsing expression \"{rawExpression}\"." }.Concat(expression.NodeErrors)); return false; } return expression != null; } private T CreateNode<T>(T node, int startIndex, string? error = null) where T : BindingParserNode { node.Tokens.Clear(); node.Tokens.Capacity = CurrentIndex - startIndex + 1; for (int i = startIndex; i < CurrentIndex; i++) node.Tokens.Add(Tokens[i]); if (startIndex < Tokens.Count) { node.StartPosition = Tokens[startIndex].StartPosition; } else if (startIndex == Tokens.Count && Tokens.Count > 0) { node.StartPosition = Tokens[startIndex - 1].EndPosition; } var length = 0; foreach (var t in node.Tokens) length += t.Length; node.Length = length; if (error != null) { node.NodeErrors.Add(error); } return node; } /// <summary> /// Asserts that the current token is of a specified type. /// </summary> protected bool IsCurrentTokenIncorrect(BindingTokenType desiredType) { var token = Peek(); if (token == null || token.Type != desiredType) { return true; } return false; } } }
// Copyright 2014 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 UnityEngine; using System; using System.Collections.Generic; using Gvr.Internal; /// The GvrViewer object communicates with the head-mounted display. /// Is is repsonsible for: /// - Querying the device for viewing parameters /// - Retrieving the latest head tracking data /// - Providing the rendered scene to the device for distortion correction (optional) /// /// There should only be one of these in a scene. An instance will be generated automatically /// by this script at runtime, or you can add one via the Editor if you wish to customize /// its starting properties. [AddComponentMenu("GoogleVR/GvrViewer")] public class GvrViewer : MonoBehaviour { public const string GVR_SDK_VERSION = "1.0"; /// The singleton instance of the GvrViewer class. public static GvrViewer Instance { get { #if UNITY_EDITOR if (instance == null && !Application.isPlaying) { instance = UnityEngine.Object.FindObjectOfType<GvrViewer>(); } #endif if (instance == null) { Debug.LogError("No GvrViewer instance found. Ensure one exists in the scene, or call " + "GvrViewer.Create() at startup to generate one.\n" + "If one does exist but hasn't called Awake() yet, " + "then this error is due to order-of-initialization.\n" + "In that case, consider moving " + "your first reference to GvrViewer.Instance to a later point in time.\n" + "If exiting the scene, this indicates that the GvrViewer object has already " + "been destroyed."); } return instance; } } private static GvrViewer instance = null; /// Generate a GvrViewer instance. Takes no action if one already exists. public static void Create() { if (instance == null && UnityEngine.Object.FindObjectOfType<GvrViewer>() == null) { Debug.Log("Creating GvrViewer object"); var go = new GameObject("GvrViewer", typeof(GvrViewer)); go.transform.localPosition = Vector3.zero; // sdk will be set by Awake(). } } /// The StereoController instance attached to the main camera, or null if there is none. /// @note Cached for performance. public static StereoController Controller { get { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR Camera camera = Camera.main; // Cache for performance, if possible. if (camera != currentMainCamera || currentController == null) { currentMainCamera = camera; currentController = camera.GetComponent<StereoController>(); } return currentController; #else return null; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } } private static StereoController currentController; private static Camera currentMainCamera; /// Determine whether the scene renders in stereo or mono. /// Supported only for versions of Unity *without* the GVR integration. /// VRModeEnabled will be a no-op for versions of Unity with the GVR integration. /// _True_ means to render in stereo, and _false_ means to render in mono. public bool VRModeEnabled { get { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR return vrModeEnabled; #else return UnityEngine.VR.VRSettings.enabled; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } set { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR if (value != vrModeEnabled && device != null) { device.SetVRModeEnabled(value); } vrModeEnabled = value; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } } [SerializeField] private bool vrModeEnabled = true; /// Determines whether distortion correction is enabled. public bool DistortionCorrectionEnabled { get { return distortionCorrectionEnabled; } set { if (value != distortionCorrectionEnabled && device != null) { device.UpdateScreenData(); } distortionCorrectionEnabled = value; } } [SerializeField] private bool distortionCorrectionEnabled = true; /// The native SDK will apply a neck offset to the head tracking, resulting in /// a more realistic model of a person's head position. This control determines /// the scale factor of the offset. To turn off the neck model, set it to 0, and /// to turn it all on, set to 1. Intermediate values can be used to animate from /// on to off or vice versa. public float NeckModelScale { get { return neckModelScale; } set { value = Mathf.Clamp01(value); if (!Mathf.Approximately(value, neckModelScale) && device != null) { device.SetNeckModelScale(value); } neckModelScale = value; } } [SerializeField] private float neckModelScale = 0.0f; #if UNITY_EDITOR /// Restores level head tilt in when playing in the Unity Editor after you /// release the Ctrl key. public bool autoUntiltHead = true; /// @cond /// Use unity remote as the input source. public bool UseUnityRemoteInput = false; /// @endcond /// The screen size to emulate when testing in the Unity Editor. public GvrProfile.ScreenSizes ScreenSize { get { return screenSize; } set { if (value != screenSize) { screenSize = value; if (device != null) { device.UpdateScreenData(); } } } } [SerializeField] private GvrProfile.ScreenSizes screenSize = GvrProfile.ScreenSizes.Nexus5; /// The viewer type to emulate when testing in the Unity Editor. public GvrProfile.ViewerTypes ViewerType { get { return viewerType; } set { if (value != viewerType) { viewerType = value; if (device != null) { device.UpdateScreenData(); } } } } [SerializeField] private GvrProfile.ViewerTypes viewerType = GvrProfile.ViewerTypes.CardboardMay2015; #endif // The VR device that will be providing input data. private static BaseVRDevice device; /// Whether the VR device supports showing a native UI layer, for example for settings. public bool NativeUILayerSupported { get; private set; } /// Scales the resolution of the #StereoScreen. Set to less than 1.0 to increase /// rendering speed while decreasing sharpness, or greater than 1.0 to do the /// opposite. public float StereoScreenScale { get { return stereoScreenScale; } set { value = Mathf.Clamp(value, 0.1f, 10.0f); // Sanity. if (stereoScreenScale != value) { stereoScreenScale = value; StereoScreen = null; } } } [SerializeField] private float stereoScreenScale = 1; /// The texture that Unity renders the scene to. After the frame has been rendered, /// this texture is drawn to the screen with a lens distortion correction effect. /// The texture size is based on the size of the screen, the lens distortion /// parameters, and the #StereoScreenScale factor. public RenderTexture StereoScreen { get { // Don't need it except for distortion correction. if (!distortionCorrectionEnabled || !VRModeEnabled) { return null; } if (stereoScreen == null) { // Create on demand. StereoScreen = device.CreateStereoScreen(); // Note: uses set{} } return stereoScreen; } set { if (value == stereoScreen) { return; } if (stereoScreen != null) { stereoScreen.Release(); } stereoScreen = value; if (OnStereoScreenChanged != null) { OnStereoScreenChanged(stereoScreen); } } } private static RenderTexture stereoScreen = null; /// A callback for notifications that the StereoScreen property has changed. public delegate void StereoScreenChangeDelegate(RenderTexture newStereoScreen); /// Emitted when the StereoScreen property has changed. public event StereoScreenChangeDelegate OnStereoScreenChanged; /// Describes the current device, including phone screen. public GvrProfile Profile { get { return device.Profile; } } /// Returns true if GoogleVR is NOT supported natively. /// That is, this version of Unity does not have native integration but supports /// the GVR SDK (5.2, 5.3), or the current VR player is the in-editor emulator. public static bool NoNativeGVRSupport { get { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR return true; #else return false; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } } /// Distinguish the stereo eyes. public enum Eye { Left, ///< The left eye Right, ///< The right eye Center ///< The "center" eye (unused) } /// When retrieving the #Projection and #Viewport properties, specifies /// whether you want the values as seen through the viewer's lenses (`Distorted`) or /// as if no lenses were present (`Undistorted`). public enum Distortion { Distorted, ///< Viewing through the lenses Undistorted ///< No lenses } /// The transformation of head from origin in the tracking system. public Pose3D HeadPose { get { return device.GetHeadPose(); } } /// The transformation from head to eye. public Pose3D EyePose(Eye eye) { return device.GetEyePose(eye); } /// The projection matrix for a given eye. /// This matrix is an off-axis perspective projection with near and far /// clipping planes of 1m and 1000m, respectively. The GvrEye script /// takes care of adjusting the matrix for its particular camera. public Matrix4x4 Projection(Eye eye, Distortion distortion = Distortion.Distorted) { return device.GetProjection(eye, distortion); } /// The screen space viewport that the camera for the specified eye should render into. /// In the _Distorted_ case, this will be either the left or right half of the `StereoScreen` /// render texture. In the _Undistorted_ case, it refers to the actual rectangle on the /// screen that the eye can see. public Rect Viewport(Eye eye, Distortion distortion = Distortion.Distorted) { return device.GetViewport(eye, distortion); } /// The distance range from the viewer in user-space meters where objects may be viewed /// comfortably in stereo. If the center of interest falls outside this range, the stereo /// eye separation should be adjusted to keep the onscreen disparity within the limits set /// by this range. If native integration is not supported, or the current VR player is the /// in-editor emulator, StereoController will handle this if the _checkStereoComfort_ is /// enabled. public Vector2 ComfortableViewingRange { get { return defaultComfortableViewingRange; } } private readonly Vector2 defaultComfortableViewingRange = new Vector2(0.4f, 100000.0f); /// @cond // Optional. Set to a URI obtained from the Google Cardboard profile generator at // https://www.google.com/get/cardboard/viewerprofilegenerator/ // Example: Cardboard I/O 2015 viewer profile //public Uri DefaultDeviceProfile = new Uri("http://google.com/cardboard/cfg?p=CgZHb29nbGUSEkNhcmRib2FyZCBJL08gMjAxNR0J-SA9JQHegj0qEAAAcEIAAHBCAABwQgAAcEJYADUpXA89OghX8as-YrENP1AAYAM"); public Uri DefaultDeviceProfile = null; /// @endcond private void InitDevice() { if (device != null) { device.Destroy(); } device = BaseVRDevice.GetDevice(); device.Init(); List<string> diagnostics = new List<string>(); NativeUILayerSupported = device.SupportsNativeUILayer(diagnostics); if (diagnostics.Count > 0) { Debug.LogWarning("Built-in UI layer disabled. Causes: [" + String.Join("; ", diagnostics.ToArray()) + "]"); } if (DefaultDeviceProfile != null) { device.SetDefaultDeviceProfile(DefaultDeviceProfile); } device.SetNeckModelScale(neckModelScale); #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR device.SetVRModeEnabled(vrModeEnabled); #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR device.UpdateScreenData(); } /// @note Each scene load causes an OnDestroy of the current SDK, followed /// by and Awake of a new one. That should not cause the underlying native /// code to hiccup. Exception: developer may call Application.DontDestroyOnLoad /// on the SDK if they want it to survive across scene loads. void Awake() { if (instance == null) { instance = this; } if (instance != this) { Debug.LogError("There must be only one GvrViewer object in a scene."); UnityEngine.Object.DestroyImmediate(this); return; } #if UNITY_IOS Application.targetFrameRate = 60; #endif // Prevent the screen from dimming / sleeping Screen.sleepTimeout = SleepTimeout.NeverSleep; InitDevice(); StereoScreen = null; // Set up stereo pre- and post-render stages only for: // - Unity without the GVR native integration // - In-editor emulator when the current platform is Android or iOS. // Since GVR is the only valid VR SDK on Android or iOS, this prevents it from // interfering with VR SDKs on other platforms. #if !UNITY_HAS_GOOGLEVR || (UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)) AddPrePostRenderStages(); #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } void Start() { // Set up stereo controller only for: // - Unity without the GVR native integration // - In-editor emulator when the current platform is Android or iOS. // Since GVR is the only valid VR SDK on Android or iOS, this prevents it from // interfering with VR SDKs on other platforms. #if !UNITY_HAS_GOOGLEVR || (UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)) AddStereoControllerToCameras(); #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR void AddPrePostRenderStages() { var preRender = UnityEngine.Object.FindObjectOfType<GvrPreRender>(); if (preRender == null) { var go = new GameObject("PreRender", typeof(GvrPreRender)); go.SendMessage("Reset"); go.transform.parent = transform; } var postRender = UnityEngine.Object.FindObjectOfType<GvrPostRender>(); if (postRender == null) { var go = new GameObject("PostRender", typeof(GvrPostRender)); go.SendMessage("Reset"); go.transform.parent = transform; } } #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR /// Whether the viewer's trigger was pulled. True for exactly one complete frame /// after each pull. public bool Triggered { get; private set; } /// Whether the viewer was tilted on its side. True for exactly one complete frame /// after each tilt. Whether and how to respond to this event is up to the app. public bool Tilted { get; private set; } /// Whether the viewer profile has possibly changed. This is meant to indicate /// that a new QR code has been scanned, although currently it is actually set any time the /// application is unpaused, whether it was due to a profile change or not. True for one /// frame. public bool ProfileChanged { get; private set; } /// Whether the user has pressed the "VR Back Button", which on Android should be treated the /// same as the normal system Back Button, although you can respond to either however you want /// in your app. public bool BackButtonPressed { get; private set; } // Only call device.UpdateState() once per frame. private int updatedToFrame = 0; /// Reads the latest tracking data from the phone. This must be /// called before accessing any of the poses and matrices above. /// /// Multiple invocations per frame are OK: Subsequent calls merely yield the /// cached results of the first call. To minimize latency, it should be first /// called later in the frame (for example, in `LateUpdate`) if possible. public void UpdateState() { if (updatedToFrame != Time.frameCount) { updatedToFrame = Time.frameCount; device.UpdateState(); if (device.profileChanged && distortionCorrectionEnabled) { DistortionCorrectionEnabled = true; } DispatchEvents(); } } private void DispatchEvents() { // Update flags first by copying from device and other inputs. Triggered = Input.GetMouseButtonDown(0); #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) Triggered |= GvrController.ClickButtonDown; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) Tilted = device.tilted; ProfileChanged = device.profileChanged; BackButtonPressed = device.backButtonPressed || Input.GetKeyDown(KeyCode.Escape); // Reset device flags. device.tilted = false; device.profileChanged = false; device.backButtonPressed = false; } /// Resets the tracker so that the user's current direction becomes forward. public void Recenter() { device.Recenter(); } /// Launch the device pairing and setup dialog. public void ShowSettingsDialog() { device.ShowSettingsDialog(); } #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR /// Add a StereoController to any camera that does not have a Render Texture (meaning it is /// rendering to the screen). public static void AddStereoControllerToCameras() { for (int i = 0; i < Camera.allCameras.Length; i++) { Camera camera = Camera.allCameras[i]; if (camera.targetTexture == null && camera.cullingMask != 0 && camera.GetComponent<StereoController>() == null && camera.GetComponent<GvrEye>() == null && camera.GetComponent<GvrPreRender>() == null && camera.GetComponent<GvrPostRender>() == null) { camera.gameObject.AddComponent<StereoController>(); } } } #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR void OnEnable() { #if UNITY_EDITOR // This can happen if you edit code while the editor is in Play mode. if (device == null) { InitDevice(); } #endif device.OnPause(false); } void OnDisable() { device.OnPause(true); } void OnApplicationPause(bool pause) { device.OnPause(pause); } void OnApplicationFocus(bool focus) { device.OnFocus(focus); } void OnApplicationQuit() { device.OnApplicationQuit(); } void OnDestroy() { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR VRModeEnabled = false; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR if (device != null) { device.Destroy(); } if (instance == this) { instance = null; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net; using System.Text; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Client.VWoHTTP.ClientStack { class VWHClientView : IClientAPI { private Scene m_scene; public bool ProcessInMsg(OSHttpRequest req, OSHttpResponse resp) { // 0 1 2 3 // http://simulator.com:9000/vwohttp/sessionid/methodname/param string[] urlparts = req.Url.AbsolutePath.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries); UUID sessionID; // Check for session if (!UUID.TryParse(urlparts[1], out sessionID)) return false; // Check we match session if (sessionID != SessionId) return false; string method = urlparts[2]; string param = String.Empty; if (urlparts.Length > 3) param = urlparts[3]; bool found; switch (method.ToLower()) { case "textures": found = ProcessTextureRequest(param, resp); break; default: found = false; break; } return found; } private bool ProcessTextureRequest(string param, OSHttpResponse resp) { UUID assetID; if (!UUID.TryParse(param, out assetID)) return false; AssetBase asset = m_scene.AssetService.Get(assetID.ToString()); if (asset == null) return false; ManagedImage tmp; Image imgData; byte[] jpegdata; OpenJPEG.DecodeToImage(asset.Data, out tmp, out imgData); using (MemoryStream ms = new MemoryStream()) { imgData.Save(ms, ImageFormat.Jpeg); jpegdata = ms.GetBuffer(); } resp.ContentType = "image/jpeg"; resp.ContentLength = jpegdata.Length; resp.StatusCode = 200; resp.Body.Write(jpegdata, 0, jpegdata.Length); return true; } public VWHClientView(UUID sessionID, UUID agentID, string agentName, Scene scene) { m_scene = scene; } #region Implementation of IClientAPI public Vector3 StartPos { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public UUID AgentId { get { throw new System.NotImplementedException(); } } public UUID SessionId { get { throw new System.NotImplementedException(); } } public UUID SecureSessionId { get { throw new System.NotImplementedException(); } } public UUID ActiveGroupId { get { throw new System.NotImplementedException(); } } public string ActiveGroupName { get { throw new System.NotImplementedException(); } } public ulong ActiveGroupPowers { get { throw new System.NotImplementedException(); } } public ulong GetGroupPowers(UUID groupID) { throw new System.NotImplementedException(); } public bool IsGroupMember(UUID GroupID) { throw new System.NotImplementedException(); } public string FirstName { get { throw new System.NotImplementedException(); } } public string LastName { get { throw new System.NotImplementedException(); } } public IScene Scene { get { throw new System.NotImplementedException(); } } public int NextAnimationSequenceNumber { get { throw new System.NotImplementedException(); } } public string Name { get { throw new System.NotImplementedException(); } } public bool IsActive { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsLoggingOut { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool SendLogoutPacketWhenClosing { set { throw new System.NotImplementedException(); } } public uint CircuitCode { get { throw new System.NotImplementedException(); } } public IPEndPoint RemoteEndPoint { get { throw new System.NotImplementedException(); } } public event GenericMessage OnGenericMessage = delegate { }; public event ImprovedInstantMessage OnInstantMessage = delegate { }; public event ChatMessage OnChatFromClient = delegate { }; public event TextureRequest OnRequestTexture = delegate { }; public event RezObject OnRezObject = delegate { }; public event ModifyTerrain OnModifyTerrain = delegate { }; public event BakeTerrain OnBakeTerrain = delegate { }; public event EstateChangeInfo OnEstateChangeInfo = delegate { }; public event SetAppearance OnSetAppearance = delegate { }; public event AvatarNowWearing OnAvatarNowWearing = delegate { }; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv = delegate { return new UUID(); }; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv = delegate { }; public event UUIDNameRequest OnDetachAttachmentIntoInv = delegate { }; public event ObjectAttach OnObjectAttach = delegate { }; public event ObjectDeselect OnObjectDetach = delegate { }; public event ObjectDrop OnObjectDrop = delegate { }; public event StartAnim OnStartAnim = delegate { }; public event StopAnim OnStopAnim = delegate { }; public event LinkObjects OnLinkObjects = delegate { }; public event DelinkObjects OnDelinkObjects = delegate { }; public event RequestMapBlocks OnRequestMapBlocks = delegate { }; public event RequestMapName OnMapNameRequest = delegate { }; public event TeleportLocationRequest OnTeleportLocationRequest = delegate { }; public event DisconnectUser OnDisconnectUser = delegate { }; public event RequestAvatarProperties OnRequestAvatarProperties = delegate { }; public event SetAlwaysRun OnSetAlwaysRun = delegate { }; public event TeleportLandmarkRequest OnTeleportLandmarkRequest = delegate { }; public event DeRezObject OnDeRezObject = delegate { }; public event Action<IClientAPI> OnRegionHandShakeReply = delegate { }; public event GenericCall2 OnRequestWearables = delegate { }; public event GenericCall1 OnCompleteMovementToRegion = delegate { }; public event UpdateAgent OnPreAgentUpdate; public event UpdateAgent OnAgentUpdate = delegate { }; public event AgentRequestSit OnAgentRequestSit = delegate { }; public event AgentSit OnAgentSit = delegate { }; public event AvatarPickerRequest OnAvatarPickerRequest = delegate { }; public event Action<IClientAPI> OnRequestAvatarsData = delegate { }; public event AddNewPrim OnAddPrim = delegate { }; public event FetchInventory OnAgentDataUpdateRequest = delegate { }; public event TeleportLocationRequest OnSetStartLocationRequest = delegate { }; public event RequestGodlikePowers OnRequestGodlikePowers = delegate { }; public event GodKickUser OnGodKickUser = delegate { }; public event ObjectDuplicate OnObjectDuplicate = delegate { }; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay = delegate { }; public event GrabObject OnGrabObject = delegate { }; public event DeGrabObject OnDeGrabObject = delegate { }; public event MoveObject OnGrabUpdate = delegate { }; public event SpinStart OnSpinStart = delegate { }; public event SpinObject OnSpinUpdate = delegate { }; public event SpinStop OnSpinStop = delegate { }; public event UpdateShape OnUpdatePrimShape = delegate { }; public event ObjectExtraParams OnUpdateExtraParams = delegate { }; public event ObjectRequest OnObjectRequest = delegate { }; public event ObjectSelect OnObjectSelect = delegate { }; public event ObjectDeselect OnObjectDeselect = delegate { }; public event GenericCall7 OnObjectDescription = delegate { }; public event GenericCall7 OnObjectName = delegate { }; public event GenericCall7 OnObjectClickAction = delegate { }; public event GenericCall7 OnObjectMaterial = delegate { }; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily = delegate { }; public event UpdatePrimFlags OnUpdatePrimFlags = delegate { }; public event UpdatePrimTexture OnUpdatePrimTexture = delegate { }; public event UpdateVector OnUpdatePrimGroupPosition = delegate { }; public event UpdateVector OnUpdatePrimSinglePosition = delegate { }; public event UpdatePrimRotation OnUpdatePrimGroupRotation = delegate { }; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation = delegate { }; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition = delegate { }; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation = delegate { }; public event UpdateVector OnUpdatePrimScale = delegate { }; public event UpdateVector OnUpdatePrimGroupScale = delegate { }; public event StatusChange OnChildAgentStatus = delegate { }; public event GenericCall2 OnStopMovement = delegate { }; public event Action<UUID> OnRemoveAvatar = delegate { }; public event ObjectPermissions OnObjectPermissions = delegate { }; public event CreateNewInventoryItem OnCreateNewInventoryItem = delegate { }; public event LinkInventoryItem OnLinkInventoryItem = delegate { }; public event CreateInventoryFolder OnCreateNewInventoryFolder = delegate { }; public event UpdateInventoryFolder OnUpdateInventoryFolder = delegate { }; public event MoveInventoryFolder OnMoveInventoryFolder = delegate { }; public event FetchInventoryDescendents OnFetchInventoryDescendents = delegate { }; public event PurgeInventoryDescendents OnPurgeInventoryDescendents = delegate { }; public event FetchInventory OnFetchInventory = delegate { }; public event RequestTaskInventory OnRequestTaskInventory = delegate { }; public event UpdateInventoryItem OnUpdateInventoryItem = delegate { }; public event CopyInventoryItem OnCopyInventoryItem = delegate { }; public event MoveInventoryItem OnMoveInventoryItem = delegate { }; public event RemoveInventoryFolder OnRemoveInventoryFolder = delegate { }; public event RemoveInventoryItem OnRemoveInventoryItem = delegate { }; public event UDPAssetUploadRequest OnAssetUploadRequest = delegate { }; public event XferReceive OnXferReceive = delegate { }; public event RequestXfer OnRequestXfer = delegate { }; public event ConfirmXfer OnConfirmXfer = delegate { }; public event AbortXfer OnAbortXfer = delegate { }; public event RezScript OnRezScript = delegate { }; public event UpdateTaskInventory OnUpdateTaskInventory = delegate { }; public event MoveTaskInventory OnMoveTaskItem = delegate { }; public event RemoveTaskInventory OnRemoveTaskItem = delegate { }; public event RequestAsset OnRequestAsset = delegate { }; public event UUIDNameRequest OnNameFromUUIDRequest = delegate { }; public event ParcelAccessListRequest OnParcelAccessListRequest = delegate { }; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest = delegate { }; public event ParcelPropertiesRequest OnParcelPropertiesRequest = delegate { }; public event ParcelDivideRequest OnParcelDivideRequest = delegate { }; public event ParcelJoinRequest OnParcelJoinRequest = delegate { }; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest = delegate { }; public event ParcelSelectObjects OnParcelSelectObjects = delegate { }; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest = delegate { }; public event ParcelAbandonRequest OnParcelAbandonRequest = delegate { }; public event ParcelGodForceOwner OnParcelGodForceOwner = delegate { }; public event ParcelReclaim OnParcelReclaim = delegate { }; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest = delegate { }; public event ParcelDeedToGroup OnParcelDeedToGroup = delegate { }; public event RegionInfoRequest OnRegionInfoRequest = delegate { }; public event EstateCovenantRequest OnEstateCovenantRequest = delegate { }; public event FriendActionDelegate OnApproveFriendRequest = delegate { }; public event FriendActionDelegate OnDenyFriendRequest = delegate { }; public event FriendshipTermination OnTerminateFriendship = delegate { }; public event GrantUserFriendRights OnGrantUserRights = delegate { }; public event MoneyTransferRequest OnMoneyTransferRequest = delegate { }; public event EconomyDataRequest OnEconomyDataRequest = delegate { }; public event MoneyBalanceRequest OnMoneyBalanceRequest = delegate { }; public event UpdateAvatarProperties OnUpdateAvatarProperties = delegate { }; public event ParcelBuy OnParcelBuy = delegate { }; public event RequestPayPrice OnRequestPayPrice = delegate { }; public event ObjectSaleInfo OnObjectSaleInfo = delegate { }; public event ObjectBuy OnObjectBuy = delegate { }; public event BuyObjectInventory OnBuyObjectInventory = delegate { }; public event RequestTerrain OnRequestTerrain = delegate { }; public event RequestTerrain OnUploadTerrain = delegate { }; public event ObjectIncludeInSearch OnObjectIncludeInSearch = delegate { }; public event UUIDNameRequest OnTeleportHomeRequest = delegate { }; public event ScriptAnswer OnScriptAnswer = delegate { }; public event AgentSit OnUndo = delegate { }; public event AgentSit OnRedo = delegate { }; public event LandUndo OnLandUndo = delegate { }; public event ForceReleaseControls OnForceReleaseControls = delegate { }; public event GodLandStatRequest OnLandStatRequest = delegate { }; public event DetailedEstateDataRequest OnDetailedEstateDataRequest = delegate { }; public event SetEstateFlagsRequest OnSetEstateFlagsRequest = delegate { }; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture = delegate { }; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture = delegate { }; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights = delegate { }; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest = delegate { }; public event SetRegionTerrainSettings OnSetRegionTerrainSettings = delegate { }; public event EstateRestartSimRequest OnEstateRestartSimRequest = delegate { }; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest = delegate { }; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest = delegate { }; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest = delegate { }; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest = delegate { }; public event EstateDebugRegionRequest OnEstateDebugRegionRequest = delegate { }; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest = delegate { }; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest = delegate { }; public event UUIDNameRequest OnUUIDGroupNameRequest = delegate { }; public event RegionHandleRequest OnRegionHandleRequest = delegate { }; public event ParcelInfoRequest OnParcelInfoRequest = delegate { }; public event RequestObjectPropertiesFamily OnObjectGroupRequest = delegate { }; public event ScriptReset OnScriptReset = delegate { }; public event GetScriptRunning OnGetScriptRunning = delegate { }; public event SetScriptRunning OnSetScriptRunning = delegate { }; public event UpdateVector OnAutoPilotGo = delegate { }; public event TerrainUnacked OnUnackedTerrain = delegate { }; public event ActivateGesture OnActivateGesture = delegate { }; public event DeactivateGesture OnDeactivateGesture = delegate { }; public event ObjectOwner OnObjectOwner = delegate { }; public event DirPlacesQuery OnDirPlacesQuery = delegate { }; public event DirFindQuery OnDirFindQuery = delegate { }; public event DirLandQuery OnDirLandQuery = delegate { }; public event DirPopularQuery OnDirPopularQuery = delegate { }; public event DirClassifiedQuery OnDirClassifiedQuery = delegate { }; public event EventInfoRequest OnEventInfoRequest = delegate { }; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime = delegate { }; public event MapItemRequest OnMapItemRequest = delegate { }; public event OfferCallingCard OnOfferCallingCard = delegate { }; public event AcceptCallingCard OnAcceptCallingCard = delegate { }; public event DeclineCallingCard OnDeclineCallingCard = delegate { }; public event SoundTrigger OnSoundTrigger = delegate { }; public event StartLure OnStartLure = delegate { }; public event TeleportLureRequest OnTeleportLureRequest = delegate { }; public event NetworkStats OnNetworkStatsUpdate = delegate { }; public event ClassifiedInfoRequest OnClassifiedInfoRequest = delegate { }; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate = delegate { }; public event ClassifiedDelete OnClassifiedDelete = delegate { }; public event ClassifiedDelete OnClassifiedGodDelete = delegate { }; public event EventNotificationAddRequest OnEventNotificationAddRequest = delegate { }; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest = delegate { }; public event EventGodDelete OnEventGodDelete = delegate { }; public event ParcelDwellRequest OnParcelDwellRequest = delegate { }; public event UserInfoRequest OnUserInfoRequest = delegate { }; public event UpdateUserInfo OnUpdateUserInfo = delegate { }; public event RetrieveInstantMessages OnRetrieveInstantMessages = delegate { }; public event PickDelete OnPickDelete = delegate { }; public event PickGodDelete OnPickGodDelete = delegate { }; public event PickInfoUpdate OnPickInfoUpdate = delegate { }; public event AvatarNotesUpdate OnAvatarNotesUpdate = delegate { }; public event MuteListRequest OnMuteListRequest = delegate { }; public event AvatarInterestUpdate OnAvatarInterestUpdate = delegate { }; public event PlacesQuery OnPlacesQuery = delegate { }; public event FindAgentUpdate OnFindAgent = delegate { }; public event TrackAgentUpdate OnTrackAgent = delegate { }; public event NewUserReport OnUserReport = delegate { }; public event SaveStateHandler OnSaveState = delegate { }; public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest = delegate { }; public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest = delegate { }; public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest = delegate { }; public event FreezeUserUpdate OnParcelFreezeUser = delegate { }; public event EjectUserUpdate OnParcelEjectUser = delegate { }; public event ParcelBuyPass OnParcelBuyPass = delegate { }; public event ParcelGodMark OnParcelGodMark = delegate { }; public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest = delegate { }; public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest = delegate { }; public event SimWideDeletesDelegate OnSimWideDeletes = delegate { }; public event SendPostcard OnSendPostcard = delegate { }; public event MuteListEntryUpdate OnUpdateMuteListEntry = delegate { }; public event MuteListEntryRemove OnRemoveMuteListEntry = delegate { }; public event GodlikeMessage onGodlikeMessage = delegate { }; public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate = delegate { }; public void SetDebugPacketLevel(int newDebug) { throw new System.NotImplementedException(); } public void InPacket(object NewPack) { throw new System.NotImplementedException(); } public void ProcessInPacket(Packet NewPack) { throw new System.NotImplementedException(); } public void Close() { throw new System.NotImplementedException(); } public void Kick(string message) { throw new System.NotImplementedException(); } public void Start() { throw new System.NotImplementedException(); } public void Stop() { throw new System.NotImplementedException(); } public void SendWearables(AvatarWearable[] wearables, int serial) { throw new System.NotImplementedException(); } public void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { throw new System.NotImplementedException(); } public void SendStartPingCheck(byte seq) { throw new System.NotImplementedException(); } public void SendKillObject(ulong regionHandle, uint localID) { throw new System.NotImplementedException(); } public void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { throw new System.NotImplementedException(); } public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { throw new System.NotImplementedException(); } public void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { throw new System.NotImplementedException(); } public void SendInstantMessage(GridInstantMessage im) { throw new System.NotImplementedException(); } public void SendGenericMessage(string method, List<string> message) { } public void SendGenericMessage(string method, List<byte[]> message) { throw new System.NotImplementedException(); } public void SendLayerData(float[] map) { throw new System.NotImplementedException(); } public void SendLayerData(int px, int py, float[] map) { throw new System.NotImplementedException(); } public void SendWindData(Vector2[] windSpeeds) { throw new System.NotImplementedException(); } public void SendCloudData(float[] cloudCover) { throw new System.NotImplementedException(); } public void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { throw new System.NotImplementedException(); } public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { throw new System.NotImplementedException(); } public AgentCircuitData RequestClientInfo() { throw new System.NotImplementedException(); } public void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { throw new System.NotImplementedException(); } public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { throw new System.NotImplementedException(); } public void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { throw new System.NotImplementedException(); } public void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { throw new System.NotImplementedException(); } public void SendTeleportFailed(string reason) { throw new System.NotImplementedException(); } public void SendTeleportLocationStart() { throw new System.NotImplementedException(); } public void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance) { throw new System.NotImplementedException(); } public void SendPayPrice(UUID objectID, int[] payPrice) { throw new System.NotImplementedException(); } public void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) { throw new System.NotImplementedException(); } public void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID) { throw new System.NotImplementedException(); } public void SetChildAgentThrottle(byte[] throttle) { throw new System.NotImplementedException(); } public void SendAvatarDataImmediate(ISceneEntity avatar) { throw new System.NotImplementedException(); } public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { throw new System.NotImplementedException(); } public void ReprioritizeUpdates() { throw new System.NotImplementedException(); } public void FlushPrimUpdates() { throw new System.NotImplementedException(); } public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems) { throw new System.NotImplementedException(); } public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { throw new System.NotImplementedException(); } public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId) { throw new System.NotImplementedException(); } public void SendRemoveInventoryItem(UUID itemID) { throw new System.NotImplementedException(); } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { throw new System.NotImplementedException(); } public void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { throw new System.NotImplementedException(); } public void SendBulkUpdateInventory(InventoryNodeBase node) { throw new System.NotImplementedException(); } public void SendXferPacket(ulong xferID, uint packet, byte[] data) { throw new System.NotImplementedException(); } public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { throw new System.NotImplementedException(); } public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { throw new System.NotImplementedException(); } public void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { throw new System.NotImplementedException(); } public void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { throw new System.NotImplementedException(); } public void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { throw new System.NotImplementedException(); } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { throw new System.NotImplementedException(); } public void SendAttachedSoundGainChange(UUID objectID, float gain) { throw new System.NotImplementedException(); } public void SendNameReply(UUID profileId, string firstname, string lastname) { throw new System.NotImplementedException(); } public void SendAlertMessage(string message) { throw new System.NotImplementedException(); } public void SendAgentAlertMessage(string message, bool modal) { throw new System.NotImplementedException(); } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { throw new System.NotImplementedException(); } public void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { throw new System.NotImplementedException(); } public bool AddMoney(int debit) { throw new System.NotImplementedException(); } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition) { throw new System.NotImplementedException(); } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { throw new System.NotImplementedException(); } public void SendViewerTime(int phase) { throw new System.NotImplementedException(); } public UUID GetDefaultAnimation(string name) { throw new System.NotImplementedException(); } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { throw new System.NotImplementedException(); } public void SendScriptQuestion(UUID taskID, string taskName, string ownerName, UUID itemID, int question) { throw new System.NotImplementedException(); } public void SendHealth(float health) { throw new System.NotImplementedException(); } public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID) { throw new System.NotImplementedException(); } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { throw new System.NotImplementedException(); } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { throw new System.NotImplementedException(); } public void SendEstateCovenantInformation(UUID covenant) { throw new System.NotImplementedException(); } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner) { throw new System.NotImplementedException(); } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { throw new System.NotImplementedException(); } public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID) { throw new System.NotImplementedException(); } public void SendForceClientSelectObjects(List<uint> objectIDs) { throw new System.NotImplementedException(); } public void SendCameraConstraint(Vector4 ConstraintPlane) { } public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount) { throw new System.NotImplementedException(); } public void SendLandParcelOverlay(byte[] data, int sequence_id) { throw new System.NotImplementedException(); } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { throw new System.NotImplementedException(); } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { throw new System.NotImplementedException(); } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { throw new System.NotImplementedException(); } public void SendConfirmXfer(ulong xferID, uint PacketID) { throw new System.NotImplementedException(); } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { throw new System.NotImplementedException(); } public void SendInitiateDownload(string simFileName, string clientFileName) { throw new System.NotImplementedException(); } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { throw new System.NotImplementedException(); } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { throw new System.NotImplementedException(); } public void SendImageNotFound(UUID imageid) { throw new System.NotImplementedException(); } public void SendShutdownConnectionNotice() { throw new System.NotImplementedException(); } public void SendSimStats(SimStats stats) { throw new System.NotImplementedException(); } public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description) { throw new System.NotImplementedException(); } public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice) { throw new System.NotImplementedException(); } public void SendAgentOffline(UUID[] agentIDs) { throw new System.NotImplementedException(); } public void SendAgentOnline(UUID[] agentIDs) { throw new System.NotImplementedException(); } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { throw new System.NotImplementedException(); } public void SendAdminResponse(UUID Token, uint AdminLevel) { throw new System.NotImplementedException(); } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { throw new System.NotImplementedException(); } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { throw new System.NotImplementedException(); } public void SendJoinGroupReply(UUID groupID, bool success) { throw new System.NotImplementedException(); } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success) { throw new System.NotImplementedException(); } public void SendLeaveGroupReply(UUID groupID, bool success) { throw new System.NotImplementedException(); } public void SendCreateGroupReply(UUID groupID, bool success, string message) { throw new System.NotImplementedException(); } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { throw new System.NotImplementedException(); } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { throw new System.NotImplementedException(); } public void SendAsset(AssetRequestToClient req) { throw new System.NotImplementedException(); } public void SendTexture(AssetBase TextureAsset) { throw new System.NotImplementedException(); } public byte[] GetThrottlesPacked(float multiplier) { throw new System.NotImplementedException(); } public event ViewerEffectEventHandler OnViewerEffect; public event Action<IClientAPI> OnLogout; public event Action<IClientAPI> OnConnectionClosed; public void SendBlueBoxMessage(UUID FromAvatarID, string FromAvatarName, string Message) { throw new System.NotImplementedException(); } public void SendLogoutPacket() { throw new System.NotImplementedException(); } public EndPoint GetClientEP() { return null; } public ClientInfo GetClientInfo() { throw new System.NotImplementedException(); } public void SetClientInfo(ClientInfo info) { throw new System.NotImplementedException(); } public void SetClientOption(string option, string value) { throw new System.NotImplementedException(); } public string GetClientOption(string option) { throw new System.NotImplementedException(); } public void Terminate() { throw new System.NotImplementedException(); } public void SendSetFollowCamProperties(UUID objectID, SortedDictionary<int, float> parameters) { throw new System.NotImplementedException(); } public void SendClearFollowCamProperties(UUID objectID) { throw new System.NotImplementedException(); } public void SendRegionHandle(UUID regoinID, ulong handle) { throw new System.NotImplementedException(); } public void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { throw new System.NotImplementedException(); } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { throw new System.NotImplementedException(); } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { throw new System.NotImplementedException(); } public void SendEventInfoReply(EventData info) { throw new System.NotImplementedException(); } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { throw new System.NotImplementedException(); } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { throw new System.NotImplementedException(); } public void SendOfferCallingCard(UUID srcID, UUID transactionID) { throw new System.NotImplementedException(); } public void SendAcceptCallingCard(UUID transactionID) { throw new System.NotImplementedException(); } public void SendDeclineCallingCard(UUID transactionID) { throw new System.NotImplementedException(); } public void SendTerminateFriend(UUID exFriendID) { throw new System.NotImplementedException(); } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { throw new System.NotImplementedException(); } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { throw new System.NotImplementedException(); } public void SendAgentDropGroup(UUID groupID) { throw new System.NotImplementedException(); } public void RefreshGroupMembership() { throw new System.NotImplementedException(); } public void SendAvatarNotesReply(UUID targetID, string text) { throw new System.NotImplementedException(); } public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks) { throw new System.NotImplementedException(); } public void SendPickInfoReply(UUID pickID, UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { throw new System.NotImplementedException(); } public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds) { throw new System.NotImplementedException(); } public void SendAvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages) { throw new System.NotImplementedException(); } public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { throw new System.NotImplementedException(); } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { throw new System.NotImplementedException(); } public void SendUseCachedMuteList() { throw new System.NotImplementedException(); } public void SendMuteListUpdate(string filename) { throw new System.NotImplementedException(); } public void KillEndDone() { throw new System.NotImplementedException(); } public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { throw new System.NotImplementedException(); } #endregion public void SendRebakeAvatarTextures(UUID textureID) { } public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages) { } public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt) { } public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier) { } public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt) { } public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes) { } public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals) { } public void SendChangeUserRights(UUID agentID, UUID friendID, int rights) { } public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime; using System.ServiceModel.Channels; using System.Xml; namespace System.ServiceModel { public class EndpointAddress { private static Uri s_anonymousUri; private static Uri s_noneUri; private static EndpointAddress s_anonymousAddress; /* Conceptually, the agnostic EndpointAddress class represents all of UNION(v200408,v10) data thusly: - Address Uri (both versions - the Address) - AddressHeaderCollection (both versions - RefProp&RefParam both project into here) - PSP blob (200408 - this is PortType, ServiceName, Policy, it is not surfaced in OM) - metadata (both versions, but weird semantics in 200408) - identity (both versions, this is the one 'extension' that we know about) - extensions (both versions, the "any*" stuff at the end) When reading from 200408: - Address is projected into Uri - both RefProps and RefParams are projected into AddressHeaderCollection, they (internally) remember 'which kind' they are - PortType, ServiceName, Policy are projected into the (internal) PSP blob - if we see a wsx:metadata element next, we project that element and that element only into the metadata reader - we read the rest, recognizing and fishing out identity if there, projecting rest to extensions reader When reading from 10: - Address is projected into Uri - RefParams are projected into AddressHeaderCollection; they (internally) remember 'which kind' they are - nothing is projected into the (internal) PSP blob (it's empty) - if there's a wsa10:metadata element, everything inside it projects into metadatareader - we read the rest, recognizing and fishing out identity if there, projecting rest to extensions reader When writing to 200408: - Uri is written as Address - AddressHeaderCollection is written as RefProps & RefParams, based on what they internally remember selves to be - PSP blob is written out verbatim (will have: PortType?, ServiceName?, Policy?) - metadata reader is written out verbatim - identity is written out as extension - extension reader is written out verbatim When writing to 10: - Uri is written as Address - AddressHeaderCollection is all written as RefParams, regardless of what they internally remember selves to be - PSP blob is ignored - if metadata reader is non-empty, we write its value out verbatim inside a wsa10:metadata element - identity is written out as extension - extension reader is written out verbatim EndpointAddressBuilder: - you can set metadata to any value you like; we don't (cannot) validate because 10 allows anything - you can set any extensions you like Known Weirdnesses: - PSP blob does not surface in OM - it can only roundtrip 200408wire->OM->200408wire - RefProperty distinction does not surface in OM - it can only roundtrip 200408wire->OM->200408wire - regardless of what metadata in reader, when you roundtrip OM->200408wire->OM, only wsx:metadata as first element after PSP will stay in metadata, anything else gets dumped in extensions - PSP blob is lost when doing OM->10wire->OM - RefProps turn into RefParams when doing OM->10wire->OM - Identity is always shuffled to front of extensions when doing anyWire->OM->anyWire */ private AddressingVersion _addressingVersion; private AddressHeaderCollection _headers; private int _extensionSection; private int _metadataSection; private int _pspSection; private bool _isNone; // these are the element name/namespace for the dummy wrapper element that wraps each buffer section internal const string DummyName = "Dummy"; internal const string DummyNamespace = "http://Dummy"; private EndpointAddress(AddressingVersion version, Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlBuffer buffer, int metadataSection, int extensionSection, int pspSection) { Init(version, uri, identity, headers, buffer, metadataSection, extensionSection, pspSection); } public EndpointAddress(string uri) { if (uri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(uri)); } Uri u = new Uri(uri); Init(u, (EndpointIdentity)null, (AddressHeaderCollection)null, null, -1, -1, -1); } public EndpointAddress(Uri uri, params AddressHeader[] addressHeaders) : this(uri, (EndpointIdentity)null, addressHeaders) { } public EndpointAddress(Uri uri, EndpointIdentity identity, params AddressHeader[] addressHeaders) { if (uri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(uri)); } Init(uri, identity, addressHeaders); } internal EndpointAddress(Uri newUri, EndpointAddress oldEndpointAddress) { Init(oldEndpointAddress._addressingVersion, newUri, oldEndpointAddress.Identity, oldEndpointAddress._headers, oldEndpointAddress.Buffer, oldEndpointAddress._metadataSection, oldEndpointAddress._extensionSection, oldEndpointAddress._pspSection); } internal EndpointAddress(Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlDictionaryReader metadataReader, XmlDictionaryReader extensionReader, XmlDictionaryReader pspReader) { if (uri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(uri)); } XmlBuffer buffer = null; PossiblyPopulateBuffer(metadataReader, ref buffer, out _metadataSection); EndpointIdentity ident2; int extSection; buffer = ReadExtensions(extensionReader, null, buffer, out ident2, out extSection); if (identity != null && ident2 != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.MultipleIdentities, "extensionReader")); } PossiblyPopulateBuffer(pspReader, ref buffer, out _pspSection); if (buffer != null) { buffer.Close(); } Init(uri, identity ?? ident2, headers, buffer, _metadataSection, extSection, _pspSection); } private void Init(Uri uri, EndpointIdentity identity, AddressHeader[] headers) { if (headers == null || headers.Length == 0) { Init(uri, identity, (AddressHeaderCollection)null, null, -1, -1, -1); } else { Init(uri, identity, new AddressHeaderCollection(headers), null, -1, -1, -1); } } private void Init(Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlBuffer buffer, int metadataSection, int extensionSection, int pspSection) { Init(null, uri, identity, headers, buffer, metadataSection, extensionSection, pspSection); } private void Init(AddressingVersion version, Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlBuffer buffer, int metadataSection, int extensionSection, int pspSection) { if (!uri.IsAbsoluteUri) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("uri", SR.UriMustBeAbsolute); } _addressingVersion = version; Uri = uri; Identity = identity; _headers = headers; Buffer = buffer; _metadataSection = metadataSection; _extensionSection = extensionSection; _pspSection = pspSection; if (version != null) { IsAnonymous = uri == version.AnonymousUri; _isNone = uri == version.NoneUri; } else { IsAnonymous = object.ReferenceEquals(uri, AnonymousUri) || uri == AnonymousUri; _isNone = object.ReferenceEquals(uri, NoneUri) || uri == NoneUri; } if (IsAnonymous) { Uri = AnonymousUri; } if (_isNone) { Uri = NoneUri; } } internal static EndpointAddress AnonymousAddress { get { if (s_anonymousAddress == null) { s_anonymousAddress = new EndpointAddress(AnonymousUri); } return s_anonymousAddress; } } public static Uri AnonymousUri { get { if (s_anonymousUri == null) { s_anonymousUri = new Uri(AddressingStrings.AnonymousUri); } return s_anonymousUri; } } public static Uri NoneUri { get { if (s_noneUri == null) { s_noneUri = new Uri(AddressingStrings.NoneUri); } return s_noneUri; } } internal XmlBuffer Buffer { get; private set; } public AddressHeaderCollection Headers { get { if (_headers == null) { _headers = new AddressHeaderCollection(); } return _headers; } } public EndpointIdentity Identity { get; private set; } public bool IsAnonymous { get; private set; } public bool IsNone { get { return _isNone; } } public Uri Uri { get; private set; } public void ApplyTo(Message message) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(message)); } Uri uri = Uri; if (IsAnonymous) { if (message.Version.Addressing == AddressingVersion.WSAddressing10) { message.Headers.To = null; } else if (message.Version.Addressing == AddressingVersion.WSAddressingAugust2004) { message.Headers.To = message.Version.Addressing.AnonymousUri; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, message.Version.Addressing))); } } else if (IsNone) { message.Headers.To = message.Version.Addressing.NoneUri; } else { message.Headers.To = uri; } message.Properties.Via = message.Headers.To; if (_headers != null) { _headers.AddHeadersTo(message); } } // NOTE: UserInfo, Query, and Fragment are ignored when comparing Uris as addresses // this is the WCF logic for comparing Uris that represent addresses // this method must be kept in sync with UriGetHashCode internal static bool UriEquals(Uri u1, Uri u2, bool ignoreCase, bool includeHostInComparison) { return UriEquals(u1, u2, ignoreCase, includeHostInComparison, true); } internal static bool UriEquals(Uri u1, Uri u2, bool ignoreCase, bool includeHostInComparison, bool includePortInComparison) { // PERF: Equals compares everything but UserInfo and Fragments. It's more strict than // we are, and faster, so it is done first. if (u1.Equals(u2)) { return true; } if (u1.Scheme != u2.Scheme) // Uri.Scheme is always lowercase { return false; } if (includePortInComparison) { if (u1.Port != u2.Port) { return false; } } if (includeHostInComparison) { if (string.Compare(u1.Host, u2.Host, StringComparison.OrdinalIgnoreCase) != 0) { return false; } } if (string.Compare(u1.AbsolutePath, u2.AbsolutePath, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0) { return true; } // Normalize for trailing slashes string u1Path = u1.GetComponents(UriComponents.Path, UriFormat.Unescaped); string u2Path = u2.GetComponents(UriComponents.Path, UriFormat.Unescaped); int u1Len = (u1Path.Length > 0 && u1Path[u1Path.Length - 1] == '/') ? u1Path.Length - 1 : u1Path.Length; int u2Len = (u2Path.Length > 0 && u2Path[u2Path.Length - 1] == '/') ? u2Path.Length - 1 : u2Path.Length; if (u2Len != u1Len) { return false; } return string.Compare(u1Path, 0, u2Path, 0, u1Len, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0; } // this method must be kept in sync with UriEquals internal static int UriGetHashCode(Uri uri, bool includeHostInComparison) { return UriGetHashCode(uri, includeHostInComparison, true); } internal static int UriGetHashCode(Uri uri, bool includeHostInComparison, bool includePortInComparison) { UriComponents components = UriComponents.Scheme | UriComponents.Path; if (includePortInComparison) { components = components | UriComponents.Port; } if (includeHostInComparison) { components = components | UriComponents.Host; } // Normalize for trailing slashes string uriString = uri.GetComponents(components, UriFormat.Unescaped); if (uriString.Length > 0 && uriString[uriString.Length - 1] != '/') { uriString = string.Concat(uriString, "/"); } return StringComparer.OrdinalIgnoreCase.GetHashCode(uriString); } internal bool EndpointEquals(EndpointAddress endpointAddress) { if (endpointAddress == null) { return false; } if (object.ReferenceEquals(this, endpointAddress)) { return true; } Uri thisTo = Uri; Uri otherTo = endpointAddress.Uri; if (!UriEquals(thisTo, otherTo, false /* ignoreCase */, true /* includeHostInComparison */)) { return false; } if (Identity == null) { if (endpointAddress.Identity != null) { return false; } } else if (!Identity.Equals(endpointAddress.Identity)) { return false; } if (!Headers.IsEquivalent(endpointAddress.Headers)) { return false; } return true; } public override bool Equals(object obj) { if (object.ReferenceEquals(obj, this)) { return true; } if (obj == null) { return false; } EndpointAddress address = obj as EndpointAddress; if (address == null) { return false; } return EndpointEquals(address); } public override int GetHashCode() { return UriGetHashCode(Uri, true /* includeHostInComparison */); } // returns reader without starting dummy wrapper element internal XmlDictionaryReader GetReaderAtPsp() { return GetReaderAtSection(Buffer, _pspSection); } // returns reader without starting dummy wrapper element public XmlDictionaryReader GetReaderAtMetadata() { return GetReaderAtSection(Buffer, _metadataSection); } // returns reader without starting dummy wrapper element public XmlDictionaryReader GetReaderAtExtensions() { return GetReaderAtSection(Buffer, _extensionSection); } private static XmlDictionaryReader GetReaderAtSection(XmlBuffer buffer, int section) { if (buffer == null || section < 0) { return null; } XmlDictionaryReader reader = buffer.GetReader(section); reader.MoveToContent(); Fx.Assert(reader.Name == DummyName, "EndpointAddress: Expected dummy element not found"); reader.Read(); // consume the dummy wrapper element return reader; } private void PossiblyPopulateBuffer(XmlDictionaryReader reader, ref XmlBuffer buffer, out int section) { if (reader == null) { section = -1; } else { if (buffer == null) { buffer = new XmlBuffer(short.MaxValue); } section = buffer.SectionCount; XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas); writer.WriteStartElement(DummyName, DummyNamespace); Copy(writer, reader); buffer.CloseSection(); } } public static EndpointAddress ReadFrom(XmlDictionaryReader reader) { AddressingVersion dummyVersion; return ReadFrom(reader, out dummyVersion); } internal static EndpointAddress ReadFrom(XmlDictionaryReader reader, out AddressingVersion version) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(reader)); } reader.ReadFullStartElement(); reader.MoveToContent(); if (reader.IsNamespaceUri(AddressingVersion.WSAddressing10.DictionaryNamespace)) { version = AddressingVersion.WSAddressing10; } else if (reader.IsNamespaceUri(AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { version = AddressingVersion.WSAddressingAugust2004; } else if (reader.NodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( "reader", SR.CannotDetectAddressingVersion); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( "reader", SR.Format(SR.AddressingVersionNotSupported, reader.NamespaceURI)); } EndpointAddress ea = ReadFromDriver(version, reader); reader.ReadEndElement(); return ea; } public static EndpointAddress ReadFrom(AddressingVersion addressingVersion, XmlDictionaryReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(reader)); } if (addressingVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(addressingVersion)); } reader.ReadFullStartElement(); EndpointAddress ea = ReadFromDriver(addressingVersion, reader); reader.ReadEndElement(); return ea; } private static EndpointAddress ReadFromDriver(AddressingVersion addressingVersion, XmlDictionaryReader reader) { AddressHeaderCollection headers; EndpointIdentity identity; Uri uri; XmlBuffer buffer; bool isAnonymous; int extensionSection; int metadataSection; int pspSection = -1; if (addressingVersion == AddressingVersion.WSAddressing10) { isAnonymous = ReadContentsFrom10(reader, out uri, out headers, out identity, out buffer, out metadataSection, out extensionSection); } else if (addressingVersion == AddressingVersion.WSAddressingAugust2004) { isAnonymous = ReadContentsFrom200408(reader, out uri, out headers, out identity, out buffer, out metadataSection, out extensionSection, out pspSection); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion", SR.Format(SR.AddressingVersionNotSupported, addressingVersion)); } if (isAnonymous && headers == null && identity == null && buffer == null) { return AnonymousAddress; } else { return new EndpointAddress(addressingVersion, uri, identity, headers, buffer, metadataSection, extensionSection, pspSection); } } internal static XmlBuffer ReadExtensions(XmlDictionaryReader reader, AddressingVersion version, XmlBuffer buffer, out EndpointIdentity identity, out int section) { if (reader == null) { identity = null; section = -1; return buffer; } // EndpointIdentity and extensions identity = null; XmlDictionaryWriter bufferWriter = null; reader.MoveToContent(); while (reader.IsStartElement()) { if (reader.IsStartElement(XD.AddressingDictionary.Identity, XD.AddressingDictionary.IdentityExtensionNamespace)) { if (identity != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.UnexpectedDuplicateElement, XD.AddressingDictionary.Identity.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value))); } identity = EndpointIdentity.ReadIdentity(reader); } else if (version != null && reader.NamespaceURI == version.Namespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.AddressingExtensionInBadNS, reader.LocalName, reader.NamespaceURI))); } else { if (bufferWriter == null) { if (buffer == null) { buffer = new XmlBuffer(short.MaxValue); } bufferWriter = buffer.OpenSection(reader.Quotas); bufferWriter.WriteStartElement(DummyName, DummyNamespace); } bufferWriter.WriteNode(reader, true); } reader.MoveToContent(); } if (bufferWriter != null) { bufferWriter.WriteEndElement(); buffer.CloseSection(); section = buffer.SectionCount - 1; } else { section = -1; } return buffer; } private static bool ReadContentsFrom200408(XmlDictionaryReader reader, out Uri uri, out AddressHeaderCollection headers, out EndpointIdentity identity, out XmlBuffer buffer, out int metadataSection, out int extensionSection, out int pspSection) { buffer = null; headers = null; extensionSection = -1; metadataSection = -1; pspSection = -1; // Cache address string reader.MoveToContent(); if (!reader.IsStartElement(XD.AddressingDictionary.Address, AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.UnexpectedElementExpectingElement, reader.LocalName, reader.NamespaceURI, XD.AddressingDictionary.Address.Value, XD.Addressing200408Dictionary.Namespace.Value))); } string address = reader.ReadElementContentAsString(); // ReferenceProperites reader.MoveToContent(); if (reader.IsStartElement(XD.AddressingDictionary.ReferenceProperties, AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { headers = AddressHeaderCollection.ReadServiceParameters(reader, true); } // ReferenceParameters reader.MoveToContent(); if (reader.IsStartElement(XD.AddressingDictionary.ReferenceParameters, AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { if (headers != null) { List<AddressHeader> headerList = new List<AddressHeader>(); foreach (AddressHeader ah in headers) { headerList.Add(ah); } AddressHeaderCollection tmp = AddressHeaderCollection.ReadServiceParameters(reader); foreach (AddressHeader ah in tmp) { headerList.Add(ah); } headers = new AddressHeaderCollection(headerList); } else { headers = AddressHeaderCollection.ReadServiceParameters(reader); } } XmlDictionaryWriter bufferWriter = null; // PortType reader.MoveToContent(); if (reader.IsStartElement(XD.AddressingDictionary.PortType, AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { if (bufferWriter == null) { if (buffer == null) { buffer = new XmlBuffer(short.MaxValue); } bufferWriter = buffer.OpenSection(reader.Quotas); bufferWriter.WriteStartElement(DummyName, DummyNamespace); } bufferWriter.WriteNode(reader, true); } // ServiceName reader.MoveToContent(); if (reader.IsStartElement(XD.AddressingDictionary.ServiceName, AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { if (bufferWriter == null) { if (buffer == null) { buffer = new XmlBuffer(short.MaxValue); } bufferWriter = buffer.OpenSection(reader.Quotas); bufferWriter.WriteStartElement(DummyName, DummyNamespace); } bufferWriter.WriteNode(reader, true); } // Policy reader.MoveToContent(); while (reader.IsNamespaceUri(PolicyStrings.Namespace)) { if (bufferWriter == null) { if (buffer == null) { buffer = new XmlBuffer(short.MaxValue); } bufferWriter = buffer.OpenSection(reader.Quotas); bufferWriter.WriteStartElement(DummyName, DummyNamespace); } bufferWriter.WriteNode(reader, true); reader.MoveToContent(); } // Finish PSP if (bufferWriter != null) { bufferWriter.WriteEndElement(); buffer.CloseSection(); pspSection = buffer.SectionCount - 1; bufferWriter = null; } else { pspSection = -1; } // Metadata if (reader.IsStartElement(System.ServiceModel.Description.MetadataStrings.MetadataExchangeStrings.Metadata, System.ServiceModel.Description.MetadataStrings.MetadataExchangeStrings.Namespace)) { if (bufferWriter == null) { if (buffer == null) { buffer = new XmlBuffer(short.MaxValue); } bufferWriter = buffer.OpenSection(reader.Quotas); bufferWriter.WriteStartElement(DummyName, DummyNamespace); } bufferWriter.WriteNode(reader, true); } // Finish metadata if (bufferWriter != null) { bufferWriter.WriteEndElement(); buffer.CloseSection(); metadataSection = buffer.SectionCount - 1; bufferWriter = null; } else { metadataSection = -1; } // Extensions reader.MoveToContent(); buffer = ReadExtensions(reader, AddressingVersion.WSAddressingAugust2004, buffer, out identity, out extensionSection); // Finished reading if (buffer != null) { buffer.Close(); } // Process Address if (address == Addressing200408Strings.Anonymous) { uri = AddressingVersion.WSAddressingAugust2004.AnonymousUri; if (headers == null && identity == null) { return true; } } else { if (!Uri.TryCreate(address, UriKind.Absolute, out uri)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.InvalidUriValue, address, XD.AddressingDictionary.Address.Value, AddressingVersion.WSAddressingAugust2004.Namespace))); } } return false; } private static bool ReadContentsFrom10(XmlDictionaryReader reader, out Uri uri, out AddressHeaderCollection headers, out EndpointIdentity identity, out XmlBuffer buffer, out int metadataSection, out int extensionSection) { buffer = null; extensionSection = -1; metadataSection = -1; // Cache address string if (!reader.IsStartElement(XD.AddressingDictionary.Address, XD.Addressing10Dictionary.Namespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.UnexpectedElementExpectingElement, reader.LocalName, reader.NamespaceURI, XD.AddressingDictionary.Address.Value, XD.Addressing10Dictionary.Namespace.Value))); } string address = reader.ReadElementContentAsString(); // Headers if (reader.IsStartElement(XD.AddressingDictionary.ReferenceParameters, XD.Addressing10Dictionary.Namespace)) { headers = AddressHeaderCollection.ReadServiceParameters(reader); } else { headers = null; } // Metadata if (reader.IsStartElement(XD.Addressing10Dictionary.Metadata, XD.Addressing10Dictionary.Namespace)) { reader.ReadFullStartElement(); // the wsa10:Metadata element is never stored in the buffer buffer = new XmlBuffer(short.MaxValue); metadataSection = 0; XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas); writer.WriteStartElement(DummyName, DummyNamespace); while (reader.NodeType != XmlNodeType.EndElement && !reader.EOF) { writer.WriteNode(reader, true); } writer.Flush(); buffer.CloseSection(); reader.ReadEndElement(); } // Extensions buffer = ReadExtensions(reader, AddressingVersion.WSAddressing10, buffer, out identity, out extensionSection); if (buffer != null) { buffer.Close(); } // Process Address if (address == Addressing10Strings.Anonymous) { uri = AddressingVersion.WSAddressing10.AnonymousUri; if (headers == null && identity == null) { return true; } } else if (address == Addressing10Strings.NoneAddress) { uri = AddressingVersion.WSAddressing10.NoneUri; return false; } else { if (!Uri.TryCreate(address, UriKind.Absolute, out uri)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.InvalidUriValue, address, XD.AddressingDictionary.Address.Value, XD.Addressing10Dictionary.Namespace.Value))); } } return false; } private static XmlException CreateXmlException(XmlDictionaryReader reader, string message) { IXmlLineInfo lineInfo = reader as IXmlLineInfo; if (lineInfo != null) { return new XmlException(message, null, lineInfo.LineNumber, lineInfo.LinePosition); } return new XmlException(message); } // this function has a side-effect on the reader (MoveToContent) private static bool Done(XmlDictionaryReader reader) { reader.MoveToContent(); return (reader.NodeType == XmlNodeType.EndElement || reader.EOF); } // copy all of reader to writer static internal void Copy(XmlDictionaryWriter writer, XmlDictionaryReader reader) { while (!Done(reader)) { writer.WriteNode(reader, true); } } public override string ToString() { return Uri.ToString(); } public void WriteContentsTo(AddressingVersion addressingVersion, XmlDictionaryWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(writer)); } if (addressingVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(addressingVersion)); } if (addressingVersion == AddressingVersion.WSAddressing10) { WriteContentsTo10(writer); } else if (addressingVersion == AddressingVersion.WSAddressingAugust2004) { WriteContentsTo200408(writer); } else if (addressingVersion == AddressingVersion.None) { WriteContentsToNone(writer); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion", SR.Format(SR.AddressingVersionNotSupported, addressingVersion)); } } private void WriteContentsToNone(XmlDictionaryWriter writer) { writer.WriteString(Uri.AbsoluteUri); } private void WriteContentsTo200408(XmlDictionaryWriter writer) { // Address writer.WriteStartElement(XD.AddressingDictionary.Address, XD.Addressing200408Dictionary.Namespace); if (IsAnonymous) { writer.WriteString(XD.Addressing200408Dictionary.Anonymous); } else if (IsNone) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion", SR.Format(SR.SFxNone2004)); } else { writer.WriteString(Uri.AbsoluteUri); } writer.WriteEndElement(); // ReferenceProperties if (_headers != null && _headers.HasReferenceProperties) { writer.WriteStartElement(XD.AddressingDictionary.ReferenceProperties, XD.Addressing200408Dictionary.Namespace); _headers.WriteReferencePropertyContentsTo(writer); writer.WriteEndElement(); } // ReferenceParameters if (_headers != null && _headers.HasNonReferenceProperties) { writer.WriteStartElement(XD.AddressingDictionary.ReferenceParameters, XD.Addressing200408Dictionary.Namespace); _headers.WriteNonReferencePropertyContentsTo(writer); writer.WriteEndElement(); } // PSP (PortType, ServiceName, Policy) XmlDictionaryReader reader = null; if (_pspSection >= 0) { reader = GetReaderAtSection(Buffer, _pspSection); Copy(writer, reader); } // Metadata reader = null; if (_metadataSection >= 0) { reader = GetReaderAtSection(Buffer, _metadataSection); Copy(writer, reader); } // EndpointIdentity if (Identity != null) { Identity.WriteTo(writer); } // Extensions if (_extensionSection >= 0) { reader = GetReaderAtSection(Buffer, _extensionSection); while (reader.IsStartElement()) { if (reader.NamespaceURI == AddressingVersion.WSAddressingAugust2004.Namespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.AddressingExtensionInBadNS, reader.LocalName, reader.NamespaceURI))); } writer.WriteNode(reader, true); } } } private void WriteContentsTo10(XmlDictionaryWriter writer) { // Address writer.WriteStartElement(XD.AddressingDictionary.Address, XD.Addressing10Dictionary.Namespace); if (IsAnonymous) { writer.WriteString(XD.Addressing10Dictionary.Anonymous); } else if (_isNone) { writer.WriteString(XD.Addressing10Dictionary.NoneAddress); } else { writer.WriteString(Uri.AbsoluteUri); } writer.WriteEndElement(); // Headers if (_headers != null && _headers.Count > 0) { writer.WriteStartElement(XD.AddressingDictionary.ReferenceParameters, XD.Addressing10Dictionary.Namespace); _headers.WriteContentsTo(writer); writer.WriteEndElement(); } // Metadata if (_metadataSection >= 0) { XmlDictionaryReader reader = GetReaderAtSection(Buffer, _metadataSection); writer.WriteStartElement(XD.Addressing10Dictionary.Metadata, XD.Addressing10Dictionary.Namespace); Copy(writer, reader); writer.WriteEndElement(); } // EndpointIdentity if (Identity != null) { Identity.WriteTo(writer); } // Extensions if (_extensionSection >= 0) { XmlDictionaryReader reader = GetReaderAtSection(Buffer, _extensionSection); while (reader.IsStartElement()) { if (reader.NamespaceURI == AddressingVersion.WSAddressing10.Namespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.AddressingExtensionInBadNS, reader.LocalName, reader.NamespaceURI))); } writer.WriteNode(reader, true); } } } public void WriteContentsTo(AddressingVersion addressingVersion, XmlWriter writer) { XmlDictionaryWriter dictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer); WriteContentsTo(addressingVersion, dictionaryWriter); } public void WriteTo(AddressingVersion addressingVersion, XmlDictionaryWriter writer) { WriteTo(addressingVersion, writer, XD.AddressingDictionary.EndpointReference, addressingVersion.DictionaryNamespace); } public void WriteTo(AddressingVersion addressingVersion, XmlDictionaryWriter writer, XmlDictionaryString localName, XmlDictionaryString ns) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(writer)); } if (addressingVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(addressingVersion)); } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localName)); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(ns)); } writer.WriteStartElement(localName, ns); WriteContentsTo(addressingVersion, writer); writer.WriteEndElement(); } public void WriteTo(AddressingVersion addressingVersion, XmlWriter writer) { XmlDictionaryString dictionaryNamespace = addressingVersion.DictionaryNamespace; if (dictionaryNamespace == null) { dictionaryNamespace = XD.AddressingDictionary.Empty; } WriteTo(addressingVersion, XmlDictionaryWriter.CreateDictionaryWriter(writer), XD.AddressingDictionary.EndpointReference, dictionaryNamespace); } public void WriteTo(AddressingVersion addressingVersion, XmlWriter writer, string localName, string ns) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(writer)); } if (addressingVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(addressingVersion)); } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localName)); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(ns)); } writer.WriteStartElement(localName, ns); WriteContentsTo(addressingVersion, writer); writer.WriteEndElement(); } public static bool operator ==(EndpointAddress address1, EndpointAddress address2) { if (object.ReferenceEquals(address2, null)) { return (object.ReferenceEquals(address1, null)); } return address2.Equals(address1); } public static bool operator !=(EndpointAddress address1, EndpointAddress address2) { if (object.ReferenceEquals(address2, null)) { return !object.ReferenceEquals(address1, null); } return !address2.Equals(address1); } } public class EndpointAddressBuilder { private XmlBuffer _extensionBuffer; // this buffer is wrapped just like in EndpointAddress private XmlBuffer _metadataBuffer; // this buffer is wrapped just like in EndpointAddress private bool _hasExtension; private bool _hasMetadata; private EndpointAddress _epr; public EndpointAddressBuilder() { Headers = new Collection<AddressHeader>(); } public EndpointAddressBuilder(EndpointAddress address) { _epr = address ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(address)); Uri = address.Uri; Identity = address.Identity; Headers = new Collection<AddressHeader>(); for (int i = 0; i < address.Headers.Count; i++) { Headers.Add(address.Headers[i]); } } public Uri Uri { get; set; } public EndpointIdentity Identity { get; set; } public Collection<AddressHeader> Headers { get; } public XmlDictionaryReader GetReaderAtMetadata() { if (!_hasMetadata) { return _epr == null ? null : _epr.GetReaderAtMetadata(); } if (_metadataBuffer == null) { return null; } XmlDictionaryReader reader = _metadataBuffer.GetReader(0); reader.MoveToContent(); Fx.Assert(reader.Name == EndpointAddress.DummyName, "EndpointAddressBuilder: Expected dummy element not found"); reader.Read(); // consume the wrapper element return reader; } public void SetMetadataReader(XmlDictionaryReader reader) { _hasMetadata = true; _metadataBuffer = null; if (reader != null) { _metadataBuffer = new XmlBuffer(short.MaxValue); XmlDictionaryWriter writer = _metadataBuffer.OpenSection(reader.Quotas); writer.WriteStartElement(EndpointAddress.DummyName, EndpointAddress.DummyNamespace); EndpointAddress.Copy(writer, reader); _metadataBuffer.CloseSection(); _metadataBuffer.Close(); } } public XmlDictionaryReader GetReaderAtExtensions() { if (!_hasExtension) { return _epr == null ? null : _epr.GetReaderAtExtensions(); } if (_extensionBuffer == null) { return null; } XmlDictionaryReader reader = _extensionBuffer.GetReader(0); reader.MoveToContent(); Fx.Assert(reader.Name == EndpointAddress.DummyName, "EndpointAddressBuilder: Expected dummy element not found"); reader.Read(); // consume the wrapper element return reader; } public void SetExtensionReader(XmlDictionaryReader reader) { _hasExtension = true; EndpointIdentity identity; int tmp; _extensionBuffer = EndpointAddress.ReadExtensions(reader, null, null, out identity, out tmp); if (_extensionBuffer != null) { _extensionBuffer.Close(); } if (identity != null) { Identity = identity; } } public EndpointAddress ToEndpointAddress() { return new EndpointAddress( Uri, Identity, new AddressHeaderCollection(Headers), GetReaderAtMetadata(), GetReaderAtExtensions(), _epr == null ? null : _epr.GetReaderAtPsp()); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.Windows.Forms; namespace OpenLiveWriter.CoreServices.Diagnostics { /// <summary> /// DisplayMessage component. /// </summary> public class UnexpectedErrorMessage : Component { /// <summary> /// The title of the message. /// </summary> private string title; /// <summary> /// Gets or sets the title to display for the message. /// </summary> [ Category("Appearance"), Localizable(true), DefaultValue(null), Description("Specifies the the title to display for the message. Note that this property is optional.") ] public string Title { get { return title; } set { title = value; } } /// <summary> /// The text of the message. /// </summary> private string text; /// <summary> /// Gets or sets the text of the message. /// </summary> [ Category("Appearance"), Localizable(true), DefaultValue(null), Description("Specifies the the text to display for the message.") ] public string Text { get { return text; } set { text = value; } } /// <summary> /// Required designer variable. /// </summary> private Container components = null; /// <summary> /// Initializes a new instance of the message class. /// </summary> /// <param name="container"></param> public UnexpectedErrorMessage(IContainer container) { /// /// Required for Windows.Forms Class Composition Designer support /// container.Add(this); InitializeComponent(); } /// <summary> /// Initializes a new instance of the message class. /// </summary> public UnexpectedErrorMessage() { /// /// Required for Windows.Forms Class Composition Designer support /// InitializeComponent(); } /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion /// <summary> /// Show with just an exception /// </summary> /// <param name="rootCause">root cause</param> public static void Show(Exception rootCause) { Show(null, rootCause); } /// <summary> /// Show with owner and exception /// </summary> /// <param name="owner">owner</param> /// <param name="rootCause">root cause</param> public static void Show(IWin32Window owner, Exception rootCause) { Show(typeof(UnhandledExceptionErrorMessage), owner, rootCause); } /// <summary> /// Static version of Show that allows you to specify the Type of the /// UnexpectedErrorMessage and have the method automatically create /// and dispose the instance /// </summary> /// <param name="errorType">type of error (must be derived from UnexpectedErrorMessage)</param> /// <param name="owner">window owner for showing message</param> /// <param name="rootCause">root cause (can be null)</param> /// <param name="args">format arguments (optional)</param> public static void Show(Type errorType, IWin32Window owner, Exception rootCause, params object[] args) { // verify calling semantics if (errorType.IsSubclassOf(typeof(UnexpectedErrorMessage))) { // create instance of error type using (UnexpectedErrorMessage errorMessage = Activator.CreateInstance(errorType) as UnexpectedErrorMessage) { errorMessage.ShowMessage(owner, rootCause, args); } } else { Debug.Fail("Type passed to ShowErrorMessage (" + errorType.Name + ") is not a subclass of UnexpectedErrorMessage"); } } public static void Show(IWin32Window owner, Exception rootCause, string title) { // create instance of error type using (UnexpectedErrorMessage errorMessage = new UnexpectedErrorMessage()) { errorMessage.Title = title; errorMessage.ShowMessage(owner, rootCause, new string[0]); } } /// <summary> /// Shows the message -- includes root cause information that can optionally /// be made available for logging and/or for developers or motivated/curious /// end users. /// </summary> public virtual void ShowMessage(IWin32Window owner, Exception rootCause, params object[] args) { string dialogTitle = Title; string dialogMessage = FormatText(args); bool isUnexpected = true; //check for special error message type ExceptionMessage dynamicMessage; if (DynamicExceptionMessageRegistry.Instance.GetMessage(out dynamicMessage, rootCause)) { if (dynamicMessage == null) return; else { dialogTitle = dynamicMessage.GetTitle(Title); dialogMessage = dynamicMessage.GetMessage(args); isUnexpected = dynamicMessage.Unexpected; } } Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0}\r\nException Details:\r\n{1}\r\n{2}", title, dialogMessage, rootCause.ToString()), ErrText.FailText); try { using (Form errorDialog = new UnexpectedErrorDialog(dialogTitle, dialogMessage, rootCause)) { if (owner != null) errorDialog.ShowDialog(owner); else errorDialog.ShowDialog(); } } catch (Exception ex) { Trace.Fail("Failure while attempting to show unexpected error", ex.Message); } } /// <summary> /// Format the title message /// </summary> /// <returns>title message</returns> private string FormatTitle() { if (title == null || title.Length == 0) return "Error"; else return title; } /// <summary> /// Format the main error message text /// </summary> /// <param name="args">optional substitution parameters</param> /// <returns>formatted error text</returns> private string FormatText(params object[] args) { // format text (substitute arguments) string formattedText; if (args != null && args.Length != 0) formattedText = String.Format(CultureInfo.CurrentCulture, Text, args); else formattedText = Text; // return the formatted text return formattedText; } } public class ErrText { /// <summary> /// Fail text. /// </summary> public const string FailText = "Fail"; } }
// -- FILE ------------------------------------------------------------------ // name : CalendarDateAddTest.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.04.04 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using System.Globalization; using Itenso.TimePeriod; using Xunit; namespace Itenso.TimePeriodTests { // ------------------------------------------------------------------------ public sealed class CalendarDateAddTest : TestUnitBase { // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void NoPeriodsTest() { DateTime test = new DateTime( 2011, 4, 12 ); CalendarDateAdd calendarDateAdd = new CalendarDateAdd(); Assert.Equal( calendarDateAdd.Add( test, TimeSpan.Zero ), test ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 1, 0, 0, 0 ) ), test.Add( new TimeSpan( 1, 0, 0, 0 ) ) ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( -1, 0, 0, 0 ) ), test.Add( new TimeSpan( -1, 0, 0, 0 ) ) ); Assert.Equal( calendarDateAdd.Subtract( test, new TimeSpan( 1, 0, 0, 0 ) ), test.Subtract( new TimeSpan( 1, 0, 0, 0 ) ) ); Assert.Equal( calendarDateAdd.Subtract( test, new TimeSpan( -1, 0, 0, 0 ) ), test.Subtract( new TimeSpan( -1, 0, 0, 0 ) ) ); } // NoPeriodsTest // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void PeriodLimitsAddTest() { DateTime test = new DateTime( 2011, 4, 12 ); TimeRange timeRange1 = new TimeRange( new DateTime( 2011, 4, 20 ), new DateTime( 2011, 4, 25 ) ); TimeRange timeRange2 = new TimeRange( new DateTime( 2011, 4, 30 ), DateTime.MaxValue ); CalendarDateAdd calendarDateAdd = new CalendarDateAdd(); calendarDateAdd.ExcludePeriods.Add( timeRange1 ); calendarDateAdd.ExcludePeriods.Add( timeRange2 ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 8, 0, 0, 0 ) ), timeRange1.End ); Assert.Null( calendarDateAdd.Add( test, new TimeSpan( 20, 0, 0, 0 ) ) ); } // PeriodLimitsAddTest // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void PeriodLimitsSubtractTest() { DateTime test = new DateTime( 2011, 4, 30 ); TimeRange timeRange1 = new TimeRange( new DateTime( 2011, 4, 20 ), new DateTime( 2011, 4, 25 ) ); TimeRange timeRange2 = new TimeRange( DateTime.MinValue, new DateTime( 2011, 4, 10 ) ); CalendarDateAdd calendarDateAdd = new CalendarDateAdd(); calendarDateAdd.ExcludePeriods.Add( timeRange1 ); calendarDateAdd.ExcludePeriods.Add( timeRange2 ); Assert.Equal( calendarDateAdd.Subtract( test, new TimeSpan( 5, 0, 0, 0 ) ), timeRange1.Start ); Assert.Null( calendarDateAdd.Subtract( test, new TimeSpan( 20, 0, 0, 0 ) ) ); } // PeriodLimitsSubtractTest // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void ExcludeTest() { DateTime test = new DateTime( 2011, 4, 12 ); TimeRange timeRange = new TimeRange( new DateTime( 2011, 4, 15 ), new DateTime( 2011, 4, 20 ) ); CalendarDateAdd calendarDateAdd = new CalendarDateAdd(); calendarDateAdd.ExcludePeriods.Add( timeRange ); Assert.Equal( calendarDateAdd.Add( test, TimeSpan.Zero ), test ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 2, 0, 0, 0 ) ), test.Add( new TimeSpan( 2, 0, 0, 0 ) ) ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 3, 0, 0, 0 ) ), timeRange.End ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 3, 0, 0, 0, 1 ) ), timeRange.End.Add( new TimeSpan( 0, 0, 0, 0, 1 ) ) ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 5, 0, 0, 0 ) ), timeRange.End.Add( new TimeSpan( 2, 0, 0, 0 ) ) ); } // ExcludeTest // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void ExcludeSplitTest() { DateTime test = new DateTime( 2011, 4, 12 ); TimeRange timeRange1 = new TimeRange( new DateTime( 2011, 4, 15 ), new DateTime( 2011, 4, 20 ) ); TimeRange timeRange2 = new TimeRange( new DateTime( 2011, 4, 22 ), new DateTime( 2011, 4, 25 ) ); CalendarDateAdd calendarDateAdd = new CalendarDateAdd(); calendarDateAdd.ExcludePeriods.Add( timeRange1 ); calendarDateAdd.ExcludePeriods.Add( timeRange2 ); Assert.Equal( calendarDateAdd.Add( test, TimeSpan.Zero ), test ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 2, 0, 0, 0 ) ), test.Add( new TimeSpan( 2, 0, 0, 0 ) ) ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 3, 0, 0, 0 ) ), timeRange1.End ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 4, 0, 0, 0 ) ), timeRange1.End.Add( new TimeSpan( 1, 0, 0, 0 ) ) ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 5, 0, 0, 0 ) ), timeRange2.End ); Assert.Equal( calendarDateAdd.Add( test, new TimeSpan( 7, 0, 0, 0 ) ), timeRange2.End.Add( new TimeSpan( 2, 0, 0, 0 ) ) ); } // ExcludeSplitTest // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void CalendarDateAddSeekBoundaryModeTest() { TimeCalendar timeCalendar = new TimeCalendar( new TimeCalendarConfig { Culture = new CultureInfo( "en-AU" ), EndOffset = TimeSpan.Zero } ); CalendarDateAdd calendarDateAdd = new CalendarDateAdd( timeCalendar ); calendarDateAdd.AddWorkingWeekDays(); calendarDateAdd.ExcludePeriods.Add( new Day( 2011, 4, 4, calendarDateAdd.Calendar ) ); calendarDateAdd.WorkingHours.Add( new HourRange( 8, 18 ) ); DateTime start = new DateTime( 2011, 4, 1, 9, 0, 0 ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 29, 0, 0 ), SeekBoundaryMode.Fill ), new DateTime( 2011, 4, 6, 18, 0, 0 ) ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 29, 0, 0 ) ), new DateTime( 2011, 4, 7, 8, 0, 0 ) ); } // CalendarDateAddSeekBoundaryModeTest // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void CalendarDateAdd1Test() { TimeCalendar timeCalendar = new TimeCalendar( new TimeCalendarConfig { Culture = new CultureInfo( "en-AU" ), EndOffset = TimeSpan.Zero } ); CalendarDateAdd calendarDateAdd = new CalendarDateAdd( timeCalendar ); calendarDateAdd.AddWorkingWeekDays(); calendarDateAdd.ExcludePeriods.Add( new Day( 2011, 4, 4, calendarDateAdd.Calendar ) ); calendarDateAdd.WorkingHours.Add( new HourRange( 8, 18 ) ); DateTime start = new DateTime( 2011, 4, 1, 9, 0, 0 ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 22, 0, 0 ) ), new DateTime( 2011, 4, 6, 11, 0, 0 ) ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 29, 0, 0 ) ), new DateTime( 2011, 4, 7, 8, 0, 0 ) ); } // CalendarDateAdd1Test // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void CalendarDateAdd2Test() { CalendarDateAdd calendarDateAdd = new CalendarDateAdd(); calendarDateAdd.AddWorkingWeekDays(); calendarDateAdd.ExcludePeriods.Add( new Day( 2011, 4, 4, calendarDateAdd.Calendar ) ); calendarDateAdd.WorkingHours.Add( new HourRange( 8, 12 ) ); calendarDateAdd.WorkingHours.Add( new HourRange( 13, 18 ) ); DateTime start = new DateTime( 2011, 4, 1, 9, 0, 0 ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 03, 0, 0 ) ), new DateTime( 2011, 4, 1, 13, 0, 0 ) ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 04, 0, 0 ) ), new DateTime( 2011, 4, 1, 14, 0, 0 ) ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 08, 0, 0 ) ), new DateTime( 2011, 4, 5, 08, 0, 0 ) ); } // CalendarDateAdd2Test // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void CalendarDateAdd3Test() { CalendarDateAdd calendarDateAdd = new CalendarDateAdd(); calendarDateAdd.AddWorkingWeekDays(); calendarDateAdd.ExcludePeriods.Add( new Day( 2011, 4, 4, calendarDateAdd.Calendar ) ); calendarDateAdd.WorkingHours.Add( new HourRange( new Time( 8, 30 ), new Time( 12 ) ) ); calendarDateAdd.WorkingHours.Add( new HourRange( new Time( 13, 30 ), new Time( 18 ) ) ); DateTime start = new DateTime( 2011, 4, 1, 9, 0, 0 ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 03, 0, 0 ) ), new DateTime( 2011, 4, 1, 13, 30, 0 ) ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 04, 0, 0 ) ), new DateTime( 2011, 4, 1, 14, 30, 0 ) ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 08, 0, 0 ) ), new DateTime( 2011, 4, 5, 09, 00, 0 ) ); } // CalendarDateAdd3Test // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void EmptyStartWeekTest() { CalendarDateAdd calendarDateAdd = new CalendarDateAdd(); // weekdays calendarDateAdd.AddWorkingWeekDays(); //Start on a Saturday DateTime start = new DateTime( 2011, 4, 2, 13, 0, 0 ); TimeSpan offset = new TimeSpan( 20, 0, 0 ); // 20 hours Assert.Equal( calendarDateAdd.Add( start, offset ), new DateTime( 2011, 4, 4, 20, 00, 0 ) ); } // EmptyStartWeekTest // ---------------------------------------------------------------------- [Trait("Category", "CalendarDateAdd")] [Fact] public void WorkingDayHoursTest() { CalendarDateAdd calendarDateAdd = new CalendarDateAdd(); calendarDateAdd.AddWorkingWeekDays(); calendarDateAdd.WorkingDayHours.Add( new DayHourRange( DayOfWeek.Monday, 09, 16 ) ); calendarDateAdd.WorkingDayHours.Add( new DayHourRange( DayOfWeek.Tuesday, 09, 16 ) ); calendarDateAdd.WorkingDayHours.Add( new DayHourRange( DayOfWeek.Wednesday, 09, 16 ) ); calendarDateAdd.WorkingDayHours.Add( new DayHourRange( DayOfWeek.Thursday, 09, 16 ) ); calendarDateAdd.WorkingDayHours.Add( new DayHourRange( DayOfWeek.Friday, 09, 13 ) ); DateTime start = new DateTime( 2011, 08, 15 ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 00, 0, 0 ) ), new DateTime( 2011, 8, 15, 09, 0, 0 ) ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 07, 0, 0 ) ), new DateTime( 2011, 8, 16, 09, 0, 0 ) ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 28, 0, 0 ) ), new DateTime( 2011, 8, 19, 09, 0, 0 ) ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 31, 0, 0 ) ), new DateTime( 2011, 8, 19, 12, 0, 0 ) ); Assert.Equal( calendarDateAdd.Add( start, new TimeSpan( 32, 0, 0 ) ), new DateTime( 2011, 8, 22, 09, 0, 0 ) ); } // WorkingDayHoursTest } // class CalendarDateAddTest } // namespace Itenso.TimePeriodTests // -- EOF -------------------------------------------------------------------
// 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.Immutable; using System.IO; using System.Linq; using System.Reflection.Internal; using System.Reflection.Metadata; using System.Reflection.Metadata.Tests; using Xunit; namespace System.Reflection.PortableExecutable.Tests { public class DebugDirectoryTests { [Fact] public void NoDebugDirectory() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream)) { var entries = reader.ReadDebugDirectory(); Assert.Empty(entries); } } [Fact] public void CodeView() { var peStream = new MemoryStream(Misc.Debug); using (var reader = new PEReader(peStream)) { ValidateCodeView(reader); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void CodeView_Loaded() { LoaderUtilities.LoadPEAndValidate(Misc.Debug, ValidateCodeView); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void CodeView_Loaded_FromStream() { LoaderUtilities.LoadPEAndValidate(Misc.Debug, ValidateCodeView, useStream: true); } private void ValidateCodeView(PEReader reader) { // dumpbin: // // Debug Directories // // Time Type Size RVA Pointer // -------------- - ------------------------ // 5670C4E6 cv 11C 0000230C 50C Format: RSDS, { 0C426227-31E6-4EC2-BD5F-712C4D96C0AB}, 1, C:\Temp\Debug.pdb var cvEntry = reader.ReadDebugDirectory().Single(); Assert.Equal(DebugDirectoryEntryType.CodeView, cvEntry.Type); Assert.False(cvEntry.IsPortableCodeView); Assert.Equal(0x050c, cvEntry.DataPointer); Assert.Equal(0x230c, cvEntry.DataRelativeVirtualAddress); Assert.Equal(0x011c, cvEntry.DataSize); // includes NUL padding Assert.Equal(0, cvEntry.MajorVersion); Assert.Equal(0, cvEntry.MinorVersion); Assert.Equal(0x5670c4e6u, cvEntry.Stamp); var cv = reader.ReadCodeViewDebugDirectoryData(cvEntry); Assert.Equal(1, cv.Age); Assert.Equal(new Guid("0C426227-31E6-4EC2-BD5F-712C4D96C0AB"), cv.Guid); Assert.Equal(@"C:\Temp\Debug.pdb", cv.Path); } [Fact] public void Deterministic() { var peStream = new MemoryStream(Misc.Deterministic); using (var reader = new PEReader(peStream)) { ValidateDeterministic(reader); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void Deterministic_Loaded() { LoaderUtilities.LoadPEAndValidate(Misc.Deterministic, ValidateDeterministic); } private void ValidateDeterministic(PEReader reader) { // dumpbin: // // Debug Directories // // Time Type Size RVA Pointer // -------- ------- -------- -------- -------- // D2FC74D3 cv 32 00002338 538 Format: RSDS, {814C578F-7676-0263-4F8A-2D3E8528EAF1}, 1, C:\Temp\Deterministic.pdb // 00000000 repro 0 00000000 0 var entries = reader.ReadDebugDirectory(); var cvEntry = entries[0]; Assert.Equal(DebugDirectoryEntryType.CodeView, cvEntry.Type); Assert.False(cvEntry.IsPortableCodeView); Assert.Equal(0x0538, cvEntry.DataPointer); Assert.Equal(0x2338, cvEntry.DataRelativeVirtualAddress); Assert.Equal(0x0032, cvEntry.DataSize); // no NUL padding Assert.Equal(0, cvEntry.MajorVersion); Assert.Equal(0, cvEntry.MinorVersion); Assert.Equal(0xD2FC74D3u, cvEntry.Stamp); var cv = reader.ReadCodeViewDebugDirectoryData(cvEntry); Assert.Equal(1, cv.Age); Assert.Equal(new Guid("814C578F-7676-0263-4F8A-2D3E8528EAF1"), cv.Guid); Assert.Equal(@"C:\Temp\Deterministic.pdb", cv.Path); var detEntry = entries[1]; Assert.Equal(DebugDirectoryEntryType.Reproducible, detEntry.Type); Assert.False(detEntry.IsPortableCodeView); Assert.Equal(0, detEntry.DataPointer); Assert.Equal(0, detEntry.DataRelativeVirtualAddress); Assert.Equal(0, detEntry.DataSize); Assert.Equal(0, detEntry.MajorVersion); Assert.Equal(0, detEntry.MinorVersion); Assert.Equal(0u, detEntry.Stamp); Assert.Equal(2, entries.Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void EmbeddedPortablePdb_Loaded() { LoaderUtilities.LoadPEAndValidate(PortablePdbs.DocumentsEmbeddedDll, ValidateEmbeddedPortablePdb); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void EmbeddedPortablePdb_Loaded_FromStream() { LoaderUtilities.LoadPEAndValidate(PortablePdbs.DocumentsEmbeddedDll, ValidateEmbeddedPortablePdb, useStream: true); } private void ValidateEmbeddedPortablePdb(PEReader reader) { var entries = reader.ReadDebugDirectory(); Assert.Equal(DebugDirectoryEntryType.CodeView, entries[0].Type); Assert.Equal(DebugDirectoryEntryType.Reproducible, entries[1].Type); Assert.Equal(DebugDirectoryEntryType.EmbeddedPortablePdb, entries[2].Type); using (MetadataReaderProvider provider = reader.ReadEmbeddedPortablePdbDebugDirectoryData(entries[2])) { var pdbReader = provider.GetMetadataReader(); var document = pdbReader.GetDocument(pdbReader.Documents.First()); Assert.Equal(@"C:\Documents.cs", pdbReader.GetString(document.Name)); } } [Fact] public void DebugDirectoryData_Errors() { var reader = new PEReader(new MemoryStream(Misc.Members)); AssertExtensions.Throws<ArgumentException>("entry", () => reader.ReadCodeViewDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.Coff, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => reader.ReadCodeViewDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.CodeView, 0, 0, 0))); AssertExtensions.Throws<ArgumentException>("entry", () => reader.ReadEmbeddedPortablePdbDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.Coff, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => reader.ReadEmbeddedPortablePdbDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); } [Fact] public void ValidateEmbeddedPortablePdbVersion() { // major version (Portable PDB format): PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)); PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0101, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)); PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0xffff, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)); Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0000, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x00ff, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); // minor version (Embedded blob format): Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0101, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0000, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x00ff, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0200, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); } [Fact] public void CodeView_PathPadding() { var bytes = ImmutableArray.Create(new byte[] { (byte)'R', (byte)'S', (byte)'D', (byte)'S', // signature 0x6E, 0xE6, 0x88, 0x3C, 0xB9, 0xE0, 0x08, 0x45, 0x92, 0x90, 0x11, 0xE0, 0xDB, 0x51, 0xA1, 0xC5, // GUID 0x01, 0x00, 0x00, 0x00, // age (byte)'x', 0x00, 0x20, 0xff, // path }); using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length)) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 1)) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 2)) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 3)) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 4)) { Assert.Equal("", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } } [Fact] public void CodeView_Errors() { var bytes = ImmutableArray.Create(new byte[] { (byte)'R', (byte)'S', (byte)'D', (byte)'S', // signature 0x6E, 0xE6, 0x88, 0x3C, 0xB9, 0xE0, 0x08, 0x45, 0x92, 0x90, 0x11, 0xE0, 0xDB, 0x51, 0xA1, 0xC5, // GUID 0x01, 0x00, 0x00, 0x00, // age (byte)'x', 0x00, // path }); using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, 1)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeCodeViewDebugDirectoryData(block)); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, 4)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeCodeViewDebugDirectoryData(block)); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 3)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeCodeViewDebugDirectoryData(block)); } } [Fact] public void EmbeddedPortablePdb_Errors() { var bytes1 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0xFF, 0xFF, 0xFF, 0xFF, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes1).GetMemoryBlock(0, bytes1.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes2 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0x09, 0x00, 0x00, 0x00, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes2).GetMemoryBlock(0, bytes2.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes3 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0x00, 0x00, 0x00, 0x00, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes3).GetMemoryBlock(0, bytes3.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes4 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0xff, 0xff, 0xff, 0x7f, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes4).GetMemoryBlock(0, bytes4.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes5 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0x08, 0x00, 0x00, 0x00, // uncompressed size 0xEF, 0xFF, 0x4F, 0xFF, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes4).GetMemoryBlock(0, bytes4.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes6 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, 0x00, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes6).GetMemoryBlock(0, bytes6.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes7 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, }); using (var block = new ByteArrayMemoryProvider(bytes7).GetMemoryBlock(0, bytes7.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes8 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, }); using (var block = new ByteArrayMemoryProvider(bytes8).GetMemoryBlock(0, bytes8.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes9 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, 0x00 }); using (var block = new ByteArrayMemoryProvider(bytes9).GetMemoryBlock(0, 1)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } } [Fact] public void PdbChecksum() { var bytes = ImmutableArray.Create(new byte[] { (byte)'A', (byte)'L', (byte)'G', 0, // AlgorithmName 0x01, 0x02, 0x03, 0x04, 0x05 // checksum }); using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length)) { var data = PEReader.DecodePdbChecksumDebugDirectoryData(block); Assert.Equal("ALG", data.AlgorithmName); AssertEx.Equal(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 }, data.Checksum); } } [Theory] [InlineData(new byte[] { 0, // AlgorithmName 0x01, 0x02, 0x03, 0x04, 0x05 // checksum })] [InlineData(new byte[] { 0x01, 0x01, 0x02, 0x03, 0x04, 0x05 })] [InlineData(new byte[] { 0x01, 0x00 })] [InlineData(new byte[] { 0x00 })] [InlineData(new byte[] { 0x01 })] [InlineData(new byte[0])] public void PdbChecksum_Errors(byte[] blob) { var bytes = ImmutableArray.Create(blob); using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodePdbChecksumDebugDirectoryData(block)); } } } }
#region Usings using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using StreamingServer.CityIndexLightstreamerClient.Models; using StreamingServer.Common.JsonSerializer; using StreamingServer.Common.Logging; using StreamingServer.LightstreamerClient; using StreamingServer.LightstreamerClient.EventArguments; using StreamingServer.LightstreamerClient.Interfaces; #endregion namespace StreamingServer.CityIndexLightstreamerClient { public interface IStreamingClient : IDisposable { void Init(string streamingUri, bool usePolling); event EventHandler<ConnectionStatusEventArgs> StatusChanged; IStreamingListener<PriceDTO> BuildPricesListener(string userName, string password, string[] marketIds); IStreamingListener<NewsDTO> BuildNewsHeadlinesListener(string userName, string password, string category); IStreamingListener<QuoteDTO> BuildQuotesListener(string userName, string password); IStreamingListener<ClientAccountMarginDTO> BuildClientAccountMarginListener(string userName, string password); IStreamingListener<OrderDTO> BuildOrdersListener(string userName, string password); IStreamingListener<PriceDTO> BuildDefaultPricesListener(string userName, string password, int accountOperatorId); IStreamingListener<TradeMarginDTO> BuildTradeMarginListener(string userName, string password); IStreamingListener<TradingAccountMarginDTO> BuildTradingAccountMarginListener(string userName, string password); void TearDownListener(IStreamingListener listener); } public class StreamingClient : IStreamingClient { private const string DataAdapter = "STREAMINGALL"; private readonly IJsonSerializer _serializer; private readonly ILogger _logger; private readonly Dictionary<string, ILightstreamerAdapter> _adapters; private string _streamingUri; private bool _usePolling; private bool _disposed; public event EventHandler<ConnectionStatusEventArgs> StatusChanged; public StreamingClient(ILogger logger, IJsonSerializer serializer) { _adapters = new Dictionary<string, ILightstreamerAdapter>(); _logger = logger; _serializer = serializer; } public void Init(string streamingUri, bool usePolling) { _usePolling = usePolling; _streamingUri = streamingUri; } /// <exception cref="RegexMatchTimeoutException">A time-out occurred. For more information about time-outs, see the Remarks section.</exception> public IStreamingListener<NewsDTO> BuildNewsHeadlinesListener(string userName, string password, string category) { var topic = Regex.Replace("NEWS.HEADLINES.{category}", "{category}", category); return BuildListener<NewsDTO>(userName, password, DataAdapter, "MERGE", true, topic); } /// <exception cref="RegexMatchTimeoutException">A time-out occurred. For more information about time-outs, see the Remarks section.</exception> /// <exception cref="ArgumentNullException"><paramref name="source" /> is null.</exception> /// <exception cref="ArgumentException">A regular expression parsing error occurred.</exception> public IStreamingListener<PriceDTO> BuildPricesListener(string userName, string password, string[] marketIds) { var topic = string.Join(" ", (from t in marketIds select Regex.Replace("PRICES.PRICE.{marketIds}", "{marketIds}", t)).ToArray<string>()); return BuildListener<PriceDTO>(userName, password, DataAdapter, "MERGE", true, topic); } public IStreamingListener<QuoteDTO> BuildQuotesListener(string userName, string password) { const string topic = "QUOTES.QUOTES"; return BuildListener<QuoteDTO>(userName, password, DataAdapter, "MERGE", true, topic); } public IStreamingListener<ClientAccountMarginDTO> BuildClientAccountMarginListener(string userName, string password) { const string topic = "CLIENTACCOUNTMARGIN.CLIENTACCOUNTMARGIN"; return BuildListener<ClientAccountMarginDTO>(userName, password, DataAdapter, "MERGE", true, topic); } public IStreamingListener<OrderDTO> BuildOrdersListener(string userName, string password) { const string topic = "ORDERS.ORDERS"; return BuildListener<OrderDTO>(userName, password, DataAdapter, "MERGE", true, topic); } public IStreamingListener<PriceDTO> BuildDefaultPricesListener(string userName, string password, int accountOperatorId) { return BuildListener<PriceDTO>(userName, password, "CITYINDEXSTREAMINGDEFAULTPRICES", "MERGE", true, "PRICES.AC" + accountOperatorId); } public IStreamingListener<TradeMarginDTO> BuildTradeMarginListener(string userName, string password) { const string topic = "TRADEMARGIN.TRADEMARGIN"; return BuildListener<TradeMarginDTO>(userName, password, DataAdapter, "RAW", false, topic); } public IStreamingListener<TradingAccountMarginDTO> BuildTradingAccountMarginListener(string userName, string password) { const string topic = "TRADINGACCOUNTMARGIN.TRADINGACCOUNTMARGIN"; return BuildListener<TradingAccountMarginDTO>(userName, password, DataAdapter, "RAW", false, topic); } /// <exception cref="ObjectDisposedException">Condition. </exception> /// <exception cref="KeyNotFoundException"> /// The property is retrieved and <paramref name="key" /> does not exist in the collection. /// </exception> [MethodImpl(MethodImplOptions.Synchronized)] public void TearDownListener(IStreamingListener listener) { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } if (!_adapters.ContainsKey(listener.Adapter)) { return; } var clientAdapter = _adapters[listener.Adapter]; clientAdapter.TearDownListener(listener); if (clientAdapter.ListenerCount == 0) { _adapters.Remove(listener.Adapter); clientAdapter.Dispose(); } } public void Dispose() { _disposed = true; Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { foreach (var current in _adapters) { current.Value.Dispose(); } } } /// <exception cref="Exception">A delegate callback throws an exception. </exception> protected virtual void OnStatusChanged(object sender, ConnectionStatusEventArgs e) { var statusChanged = StatusChanged; if (statusChanged != null) { statusChanged(sender, e); } } [MethodImpl(MethodImplOptions.Synchronized)] private IStreamingListener<TDto> BuildListener<TDto>(string userName, string password, string dataAdapter, string mode, bool snapshot, string topic) where TDto : class, new() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } if (!_adapters.ContainsKey(dataAdapter)) { LightstreamerAdapter lightstreamerAdapter = null; try { lightstreamerAdapter = new LightstreamerAdapter(_logger, _serializer, _streamingUri, userName, password, dataAdapter, _usePolling); lightstreamerAdapter.StatusUpdate += OnStatusChanged; _adapters.Add(dataAdapter, lightstreamerAdapter); lightstreamerAdapter.Start(); } catch { if (lightstreamerAdapter != null) { lightstreamerAdapter.Dispose(); } throw; } } _logger.Debug("StreamingClient created for " + string.Format("{0} {1}", userName, topic)); return _adapters[dataAdapter].BuildListener<TDto>(topic, mode, snapshot); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsCompositeBoolIntClient { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// IntModel operations. /// </summary> public partial class IntModel : IServiceOperations<CompositeBoolInt>, IIntModel { /// <summary> /// Initializes a new instance of the IntModel class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public IntModel(CompositeBoolInt client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the CompositeBoolInt /// </summary> public CompositeBoolInt Client { get; private set; } /// <summary> /// Get null Int value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<int?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/null").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<int?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<int?>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get invalid Int value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<int?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/invalid").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<int?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<int?>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<int?>> GetOverflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetOverflowInt32", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/overflowint32").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<int?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<int?>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<int?>> GetUnderflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowInt32", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/underflowint32").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<int?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<int?>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<long?>> GetOverflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetOverflowInt64", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/overflowint64").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<long?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<long?>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<long?>> GetUnderflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowInt64", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/underflowint64").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<long?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<long?>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put max int32 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutMax32WithHttpMessagesAsync(int intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutMax32", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/max/32").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(intBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put max int64 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutMax64WithHttpMessagesAsync(long intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutMax64", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/max/64").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(intBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put min int32 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutMin32WithHttpMessagesAsync(int intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutMin32", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/min/32").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(intBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put min int64 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutMin64WithHttpMessagesAsync(long intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutMin64", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/min/64").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(intBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get datetime encoded as Unix time value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.DateTime?>> GetUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetUnixTime", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new UnixTimeJsonConverter()); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put datetime encoded as Unix time /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutUnixTimeDateWithHttpMessagesAsync(System.DateTime intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutUnixTimeDate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(intBody, new UnixTimeJsonConverter()); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get invalid Unix time value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.DateTime?>> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalidUnixTime", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/invalidunixtime").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new UnixTimeJsonConverter()); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get null Unix time value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.DateTime?>> GetNullUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNullUnixTime", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/nullunixtime").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new UnixTimeJsonConverter()); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* From http://xmlunit.sourceforge.net/ Moved here because the original library is for testing, and * it is tied to nunit, which we don't want to ship in production */ using System; using System.IO; using System.Xml; namespace SIL.Lift.Merging.xmldiff { ///<summary></summary> public class XmlDiff { private readonly XmlReader _controlReader; private readonly XmlReader _testReader; private readonly DiffConfiguration _diffConfiguration; private DiffResult _diffResult; ///<summary> /// Constructor. ///</summary> public XmlDiff(XmlInput control, XmlInput test, DiffConfiguration diffConfiguration) { _diffConfiguration = diffConfiguration; _controlReader = CreateXmlReader(control); if (control.Equals(test)) { _testReader = _controlReader; } else { _testReader = CreateXmlReader(test); } } ///<summary> /// Constructor. ///</summary> public XmlDiff(XmlInput control, XmlInput test) : this(control, test, new DiffConfiguration()) { } ///<summary> /// Constructor. ///</summary> public XmlDiff(TextReader control, TextReader test) : this(new XmlInput(control), new XmlInput(test)) { } ///<summary> /// Constructor. ///</summary> public XmlDiff(string control, string test) : this(new XmlInput(control), new XmlInput(test)) { } private XmlReader CreateXmlReader(XmlInput forInput) { XmlReader xmlReader = forInput.CreateXmlReader(); if (xmlReader is XmlTextReader) { ((XmlTextReader)xmlReader).WhitespaceHandling = _diffConfiguration.WhitespaceHandling; } if (_diffConfiguration.UseValidatingParser) { #pragma warning disable 612,618 XmlValidatingReader validatingReader = new XmlValidatingReader(xmlReader); #pragma warning restore 612,618 return validatingReader; } return xmlReader; } ///<summary></summary> public DiffResult Compare() { if (_diffResult == null) { _diffResult = new DiffResult(); if (!_controlReader.Equals(_testReader)) { Compare(_diffResult); } } return _diffResult; } private void Compare(DiffResult result) { bool controlRead, testRead; try { do { controlRead = _controlReader.Read(); testRead = _testReader.Read(); Compare(result, ref controlRead, ref testRead); } while (controlRead && testRead); } catch (FlowControlException e) { Console.Out.WriteLine(e.Message); } } private void Compare(DiffResult result, ref bool controlRead, ref bool testRead) { if (controlRead) { if (testRead) { CompareNodes(result); CheckEmptyOrAtEndElement(result, ref controlRead, ref testRead); } else { DifferenceFound(DifferenceType.CHILD_NODELIST_LENGTH_ID, result); } } //jh added this; under a condition I haven't got into an xdiff test yet, the // 'test' guy still had more children, and this fact was being missed by the above code if (controlRead != testRead) { DifferenceFound(DifferenceType.CHILD_NODELIST_LENGTH_ID, result); } } private void CompareNodes(DiffResult result) { XmlNodeType controlNodeType = _controlReader.NodeType; XmlNodeType testNodeType = _testReader.NodeType; if (!controlNodeType.Equals(testNodeType)) { CheckNodeTypes(controlNodeType, testNodeType, result); } else if (controlNodeType == XmlNodeType.Element) { CompareElements(result); } else if (controlNodeType == XmlNodeType.Text) { CompareText(result); } } private void CheckNodeTypes(XmlNodeType controlNodeType, XmlNodeType testNodeType, DiffResult result) { XmlReader readerToAdvance = null; if (controlNodeType.Equals(XmlNodeType.XmlDeclaration)) { readerToAdvance = _controlReader; } else if (testNodeType.Equals(XmlNodeType.XmlDeclaration)) { readerToAdvance = _testReader; } if (readerToAdvance != null) { DifferenceFound(DifferenceType.HAS_XML_DECLARATION_PREFIX_ID, controlNodeType, testNodeType, result); readerToAdvance.Read(); CompareNodes(result); } else { DifferenceFound(DifferenceType.NODE_TYPE_ID, controlNodeType, testNodeType, result); } } private void CompareElements(DiffResult result) { string controlTagName = _controlReader.Name; string testTagName = _testReader.Name; if (!String.Equals(controlTagName, testTagName)) { DifferenceFound(DifferenceType.ELEMENT_TAG_NAME_ID, result); } else { int controlAttributeCount = _controlReader.AttributeCount; int testAttributeCount = _testReader.AttributeCount; if (controlAttributeCount != testAttributeCount) { DifferenceFound(DifferenceType.ELEMENT_NUM_ATTRIBUTES_ID, result); } else { CompareAttributes(result, controlAttributeCount); } } } private void CompareAttributes(DiffResult result, int controlAttributeCount) { string controlAttrValue, controlAttrName; string testAttrValue, testAttrName; _controlReader.MoveToFirstAttribute(); _testReader.MoveToFirstAttribute(); for (int i = 0; i < controlAttributeCount; ++i) { controlAttrName = _controlReader.Name; testAttrName = _testReader.Name; controlAttrValue = _controlReader.Value; testAttrValue = _testReader.Value; if (!String.Equals(controlAttrName, testAttrName)) { DifferenceFound(DifferenceType.ATTR_SEQUENCE_ID, result); if (!_testReader.MoveToAttribute(controlAttrName)) { DifferenceFound(DifferenceType.ATTR_NAME_NOT_FOUND_ID, result); } testAttrValue = _testReader.Value; } if (!String.Equals(controlAttrValue, testAttrValue)) { DifferenceFound(DifferenceType.ATTR_VALUE_ID, result); } _controlReader.MoveToNextAttribute(); _testReader.MoveToNextAttribute(); } } private void CompareText(DiffResult result) { string controlText = _controlReader.Value; string testText = _testReader.Value; if (!String.Equals(controlText, testText)) { DifferenceFound(DifferenceType.TEXT_VALUE_ID, result); } } private void DifferenceFound(DifferenceType differenceType, DiffResult result) { DifferenceFound(new Difference(differenceType), result); } private void DifferenceFound(Difference difference, DiffResult result) { result.DifferenceFound(this, difference); if (!ContinueComparison(difference)) { throw new FlowControlException(difference); } } private void DifferenceFound(DifferenceType differenceType, XmlNodeType controlNodeType, XmlNodeType testNodeType, DiffResult result) { DifferenceFound(new Difference(differenceType, controlNodeType, testNodeType), result); } private bool ContinueComparison(Difference afterDifference) { return !afterDifference.HasMajorDifference; } private void CheckEmptyOrAtEndElement(DiffResult result, ref bool controlRead, ref bool testRead) { if (_controlReader.IsEmptyElement) { if (!_testReader.IsEmptyElement) { CheckEndElement(_testReader, ref testRead, result); } } else { if (_testReader.IsEmptyElement) { CheckEndElement(_controlReader, ref controlRead, result); } } } private void CheckEndElement(XmlReader reader, ref bool readResult, DiffResult result) { readResult = reader.Read(); if (!readResult || reader.NodeType != XmlNodeType.EndElement) { DifferenceFound(DifferenceType.CHILD_NODELIST_LENGTH_ID, result); } } private class FlowControlException : ApplicationException { public FlowControlException(Difference cause) : base(cause.ToString()) { } } ///<summary></summary> public string OptionalDescription { get { return _diffConfiguration.Description; } } } }
/* Copyright (c) 2010-2015 by Genstein and Jason Lautzenheiser. This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Trizbort { partial class ConnectionPropertiesDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConnectionPropertiesDialog)); this.m_cancelButton = new System.Windows.Forms.Button(); this.m_okButton = new System.Windows.Forms.Button(); this.m_oneWayCheckBox = new System.Windows.Forms.CheckBox(); this.m_dottedCheckBox = new System.Windows.Forms.CheckBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.m_endLabel = new System.Windows.Forms.Label(); this.m_endTextBox = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.m_middleTextBox = new System.Windows.Forms.TextBox(); this.m_startTextBox = new System.Windows.Forms.TextBox(); this.m_customRadioButton = new System.Windows.Forms.RadioButton(); this.m_oiRadioButton = new System.Windows.Forms.RadioButton(); this.m_ioRadioButton = new System.Windows.Forms.RadioButton(); this.m_duRadioButton = new System.Windows.Forms.RadioButton(); this.m_udRadioButton = new System.Windows.Forms.RadioButton(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.connectionColorBox = new DevComponents.DotNetBar.Controls.TextBoxX(); this.connectionColorChange = new System.Windows.Forms.Button(); this.label11 = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // m_cancelButton // this.m_cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.m_cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.m_cancelButton.Location = new System.Drawing.Point(348, 208); this.m_cancelButton.Name = "m_cancelButton"; this.m_cancelButton.Size = new System.Drawing.Size(75, 23); this.m_cancelButton.TabIndex = 3; this.m_cancelButton.Text = "Cancel"; this.m_cancelButton.UseVisualStyleBackColor = true; // // m_okButton // this.m_okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.m_okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.m_okButton.Location = new System.Drawing.Point(267, 208); this.m_okButton.Name = "m_okButton"; this.m_okButton.Size = new System.Drawing.Size(75, 23); this.m_okButton.TabIndex = 2; this.m_okButton.Text = "OK"; this.m_okButton.UseVisualStyleBackColor = true; // // m_oneWayCheckBox // this.m_oneWayCheckBox.AutoSize = true; this.m_oneWayCheckBox.Location = new System.Drawing.Point(9, 44); this.m_oneWayCheckBox.Name = "m_oneWayCheckBox"; this.m_oneWayCheckBox.Size = new System.Drawing.Size(103, 17); this.m_oneWayCheckBox.TabIndex = 1; this.m_oneWayCheckBox.Text = "One Way &Arrow"; this.m_oneWayCheckBox.UseVisualStyleBackColor = true; // // m_dottedCheckBox // this.m_dottedCheckBox.AutoSize = true; this.m_dottedCheckBox.Location = new System.Drawing.Point(10, 21); this.m_dottedCheckBox.Name = "m_dottedCheckBox"; this.m_dottedCheckBox.Size = new System.Drawing.Size(59, 17); this.m_dottedCheckBox.TabIndex = 0; this.m_dottedCheckBox.Text = "&Dotted"; this.m_dottedCheckBox.UseVisualStyleBackColor = true; // // groupBox1 // this.groupBox1.Controls.Add(this.m_endLabel); this.groupBox1.Controls.Add(this.m_endTextBox); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.m_middleTextBox); this.groupBox1.Controls.Add(this.m_startTextBox); this.groupBox1.Controls.Add(this.m_customRadioButton); this.groupBox1.Controls.Add(this.m_oiRadioButton); this.groupBox1.Controls.Add(this.m_ioRadioButton); this.groupBox1.Controls.Add(this.m_duRadioButton); this.groupBox1.Controls.Add(this.m_udRadioButton); this.groupBox1.Location = new System.Drawing.Point(12, 90); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(411, 106); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "&Text"; // // m_endLabel // this.m_endLabel.AutoSize = true; this.m_endLabel.Location = new System.Drawing.Point(216, 72); this.m_endLabel.Name = "m_endLabel"; this.m_endLabel.Size = new System.Drawing.Size(25, 13); this.m_endLabel.TabIndex = 9; this.m_endLabel.Text = "&End"; // // m_endTextBox // this.m_endTextBox.Location = new System.Drawing.Point(245, 69); this.m_endTextBox.Name = "m_endTextBox"; this.m_endTextBox.Size = new System.Drawing.Size(156, 21); this.m_endTextBox.TabIndex = 10; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(204, 46); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(37, 13); this.label2.TabIndex = 7; this.label2.Text = "&Middle"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(210, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(31, 13); this.label1.TabIndex = 5; this.label1.Text = "&Start"; // // m_middleTextBox // this.m_middleTextBox.Location = new System.Drawing.Point(245, 43); this.m_middleTextBox.Name = "m_middleTextBox"; this.m_middleTextBox.Size = new System.Drawing.Size(156, 21); this.m_middleTextBox.TabIndex = 8; // // m_startTextBox // this.m_startTextBox.Location = new System.Drawing.Point(245, 17); this.m_startTextBox.Name = "m_startTextBox"; this.m_startTextBox.Size = new System.Drawing.Size(156, 21); this.m_startTextBox.TabIndex = 6; // // m_customRadioButton // this.m_customRadioButton.AutoSize = true; this.m_customRadioButton.Checked = true; this.m_customRadioButton.Location = new System.Drawing.Point(9, 70); this.m_customRadioButton.Name = "m_customRadioButton"; this.m_customRadioButton.Size = new System.Drawing.Size(61, 17); this.m_customRadioButton.TabIndex = 4; this.m_customRadioButton.TabStop = true; this.m_customRadioButton.Text = "&Custom"; this.m_customRadioButton.UseVisualStyleBackColor = true; this.m_customRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonCheckedChanged); // // m_oiRadioButton // this.m_oiRadioButton.AutoSize = true; this.m_oiRadioButton.Location = new System.Drawing.Point(95, 44); this.m_oiRadioButton.Name = "m_oiRadioButton"; this.m_oiRadioButton.Size = new System.Drawing.Size(57, 17); this.m_oiRadioButton.TabIndex = 3; this.m_oiRadioButton.Text = "&Out/In"; this.m_oiRadioButton.UseVisualStyleBackColor = true; this.m_oiRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonCheckedChanged); // // m_ioRadioButton // this.m_ioRadioButton.AutoSize = true; this.m_ioRadioButton.Location = new System.Drawing.Point(95, 18); this.m_ioRadioButton.Name = "m_ioRadioButton"; this.m_ioRadioButton.Size = new System.Drawing.Size(57, 17); this.m_ioRadioButton.TabIndex = 2; this.m_ioRadioButton.Text = "&In/Out"; this.m_ioRadioButton.UseVisualStyleBackColor = true; this.m_ioRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonCheckedChanged); // // m_duRadioButton // this.m_duRadioButton.AutoSize = true; this.m_duRadioButton.Location = new System.Drawing.Point(9, 44); this.m_duRadioButton.Name = "m_duRadioButton"; this.m_duRadioButton.Size = new System.Drawing.Size(69, 17); this.m_duRadioButton.TabIndex = 1; this.m_duRadioButton.Text = "&Down/Up"; this.m_duRadioButton.UseVisualStyleBackColor = true; this.m_duRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonCheckedChanged); // // m_udRadioButton // this.m_udRadioButton.AutoSize = true; this.m_udRadioButton.Location = new System.Drawing.Point(9, 18); this.m_udRadioButton.Name = "m_udRadioButton"; this.m_udRadioButton.Size = new System.Drawing.Size(69, 17); this.m_udRadioButton.TabIndex = 0; this.m_udRadioButton.Text = "&Up/Down"; this.m_udRadioButton.UseVisualStyleBackColor = true; this.m_udRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonCheckedChanged); // // groupBox2 // this.groupBox2.Controls.Add(this.connectionColorBox); this.groupBox2.Controls.Add(this.connectionColorChange); this.groupBox2.Controls.Add(this.label11); this.groupBox2.Controls.Add(this.m_oneWayCheckBox); this.groupBox2.Controls.Add(this.m_dottedCheckBox); this.groupBox2.Location = new System.Drawing.Point(12, 10); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(411, 72); this.groupBox2.TabIndex = 0; this.groupBox2.TabStop = false; this.groupBox2.Text = "&Style"; // // connectionColorBox // // // // this.connectionColorBox.Border.Class = "TextBoxBorder"; this.connectionColorBox.Border.CornerType = DevComponents.DotNetBar.eCornerType.Square; this.connectionColorBox.ButtonCustom.Text = "Clear"; this.connectionColorBox.ButtonCustom.Visible = true; this.connectionColorBox.Cursor = System.Windows.Forms.Cursors.Arrow; this.connectionColorBox.Location = new System.Drawing.Point(233, 18); this.connectionColorBox.Name = "connectionColorBox"; this.connectionColorBox.ReadOnly = true; this.connectionColorBox.Size = new System.Drawing.Size(133, 21); this.connectionColorBox.TabIndex = 24; this.connectionColorBox.ButtonCustomClick += new System.EventHandler(this.connectionColorBox_ButtonCustomClick); this.connectionColorBox.DoubleClick += new System.EventHandler(this.connectionColorBox_DoubleClick); // // connectionColorChange // this.connectionColorChange.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.connectionColorChange.Location = new System.Drawing.Point(372, 17); this.connectionColorChange.Name = "connectionColorChange"; this.connectionColorChange.Size = new System.Drawing.Size(29, 23); this.connectionColorChange.TabIndex = 23; this.connectionColorChange.Text = "..."; this.connectionColorChange.UseVisualStyleBackColor = true; this.connectionColorChange.Click += new System.EventHandler(this.connectionColorChange_Click); // // label11 // this.label11.AutoSize = true; this.label11.BackColor = System.Drawing.Color.Transparent; this.label11.Location = new System.Drawing.Point(195, 22); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(32, 13); this.label11.TabIndex = 22; this.label11.Text = "Color"; // // ConnectionPropertiesDialog // this.AcceptButton = this.m_okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.m_cancelButton; this.ClientSize = new System.Drawing.Size(435, 243); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.m_cancelButton); this.Controls.Add(this.m_okButton); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ConnectionPropertiesDialog"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Connection Properties"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button m_cancelButton; private System.Windows.Forms.Button m_okButton; private System.Windows.Forms.CheckBox m_oneWayCheckBox; private System.Windows.Forms.CheckBox m_dottedCheckBox; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.RadioButton m_customRadioButton; private System.Windows.Forms.RadioButton m_oiRadioButton; private System.Windows.Forms.RadioButton m_ioRadioButton; private System.Windows.Forms.RadioButton m_duRadioButton; private System.Windows.Forms.RadioButton m_udRadioButton; private System.Windows.Forms.Label m_endLabel; private System.Windows.Forms.TextBox m_endTextBox; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox m_middleTextBox; private System.Windows.Forms.TextBox m_startTextBox; private System.Windows.Forms.GroupBox groupBox2; private DevComponents.DotNetBar.Controls.TextBoxX connectionColorBox; private System.Windows.Forms.Button connectionColorChange; private System.Windows.Forms.Label label11; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using SinchBackend.Areas.HelpPage.ModelDescriptions; using SinchBackend.Areas.HelpPage.Models; namespace SinchBackend.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//--------------------------------------------------------------------- // File: StreamHelper.cs // // Summary: // // Author: Kevin B. Smith (http://www.kevinsmith.co.uk) // //--------------------------------------------------------------------- // Copyright (c) 2004-2010, Kevin B. Smith. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. //--------------------------------------------------------------------- namespace BizUnit { using System; using System.Xml; using System.Text; using System.IO; /// <summary> /// Helper class for stream opperations /// </summary> public class StreamHelper { /// <summary> /// Performs a binary comparison between two streams /// </summary> /// <param name="s1">The 1st stream to compare aginst the 2nd</param> /// <param name="s2">The 2nd stream to compare aginst the 1st</param> static public void CompareStreams(Stream s1, Stream s2) { byte[] buff1 = new byte[4096]; byte[] buff2 = new byte[4096]; int read1; do { read1 = s1.Read(buff1, 0, 4096); int read2 = s2.Read(buff2, 0, 4096); if ( read1 != read2 ) { throw new ApplicationException( String.Format( "Streams do not contain identical data!" ) ); } if ( 0 == read1 ) { break; } for ( int c = 0; c < read1; c++ ) { if ( buff1[c] != buff2[c] ) { throw new ApplicationException( String.Format( "Streams do not contain identical data!" ) ); } } } while( read1 > 0 ); } /// <summary> /// Helper method to load a disc FILE into a MemoryStream /// </summary> /// <param name="filePath">The path to the FILE containing the data</param> /// <param name="timeout">The timeout afterwhich if the FILE is not found the method will fail</param> /// <returns>MemoryStream containing the data in the FILE</returns> public static MemoryStream LoadFileToStream(string filePath, double timeout) { MemoryStream ms = null; bool loaded = false; DateTime now = DateTime.Now; do { try { ms = LoadFileToStream(filePath); loaded = true; break; } catch(Exception) { if ( DateTime.Now < now.AddMilliseconds(timeout) ) { System.Threading.Thread.Sleep(500); } } } while ( DateTime.Now < now.AddMilliseconds(timeout) ); if ( !loaded ) { throw new ApplicationException( string.Format( "The file: {0} was not found within the timeout period!", filePath ) ); } return ms; } /// <summary> /// Helper method to load a disc FILE into a MemoryStream /// </summary> /// <param name="filePath">The path to the FILE containing the data</param> /// <returns>MemoryStream containing the data in the FILE</returns> public static MemoryStream LoadFileToStream(string filePath) { FileStream fs = null; MemoryStream s; try { // Get the match data... fs = File.OpenRead(filePath); s = new MemoryStream(); byte[] buff = new byte[1024]; int read = fs.Read(buff, 0, 1024); while ( 0 < read ) { s.Write(buff, 0, read); read = fs.Read(buff, 0, 1024); } s.Flush(); s.Seek(0, SeekOrigin.Begin); } finally { if ( null != fs ) { fs.Close(); } } return s; } /// <summary> /// Helper method to write the data in a stream to the console /// </summary> /// <param name="description">The description text that will be written before the stream data</param> /// <param name="ms">Stream containing the data to write</param> /// <param name="context">The BizUnit context object which holds state and is passed between test steps</param> public static void WriteStreamToConsole(string description, MemoryStream ms, Context context) { ms.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(ms); context.LogData( description, sr.ReadToEnd() ); ms.Seek(0, SeekOrigin.Begin); } /// <summary> /// Helper method to load a forward only stream into a seekable MemoryStream /// </summary> /// <param name="s">The forward only stream to read the data from</param> /// <returns>MemoryStream containg the data as read from s</returns> public static MemoryStream LoadMemoryStream(Stream s) { MemoryStream ms = new MemoryStream(); byte[] buff = new byte[1024]; int read = s.Read(buff, 0, 1024); while ( 0 < read ) { ms.Write(buff, 0, read); read = s.Read(buff, 0, 1024); } ms.Flush(); ms.Seek(0, SeekOrigin.Begin); return ms; } /// <summary> /// Helper method to load a string into a MemoryStream /// </summary> /// <param name="s">The string containing the data that will be loaded into the stream</param> /// <returns>MemoryStream containg the data read from the string</returns> public static MemoryStream LoadMemoryStream(string s) { Encoding utf8 = Encoding.UTF8; byte[] bytes = utf8.GetBytes(s); MemoryStream ms = new MemoryStream(bytes); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); return ms; } /// <summary> /// Helper method to compare two Xml documents from streams /// </summary> /// <param name="s1">Stream containing the 1st Xml document</param> /// <param name="s2">Stream containing the 2nd Xml document</param> /// <param name="context">The BizUnit context object which holds state and is passed between test steps</param> public static void CompareXmlDocs(Stream s1, Stream s2, Context context) { XmlDocument doc = new XmlDocument(); doc.Load(new XmlTextReader(s1)); XmlElement root = doc.DocumentElement; string data1 = root.OuterXml; doc = new XmlDocument(); doc.Load(new XmlTextReader(s2)); root = doc.DocumentElement; string data2 = root.OuterXml; context.LogInfo("About to compare the following Xml documents:\r\nDocument1: {0},\r\nDocument2: {1}", data1, data2); CompareStreams( LoadMemoryStream(data1), LoadMemoryStream(data2) ); } /// <summary> /// Helper method to encode a stream /// </summary> /// <param name="rawData">Stream containing data to be encoded</param> /// <param name="encoding">The encoding to be used for the data</param> /// <returns>Encoded MemoryStream</returns> public static Stream EncodeStream(Stream rawData, Encoding encoding) { rawData.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(rawData); string data = sr.ReadToEnd(); Encoding e = encoding; byte[] bytes = e.GetBytes(data); return new MemoryStream(bytes); } } }
//------------------------------------------------------------------------------ // <copyright file="LiteralTextParser.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Text; using System.Web; namespace System.Web.UI.MobileControls { /* * LiteralTextParser class. * * The LiteralTextParser class parses a string of literal text, * containing certain recognizable tags, and creates a set of controls * from them. Any unrecognized tags are ignored. * * This is an abstract base class. RuntimeLiteralTextParser and * CompileTimeLiteralTextParser inherit from this class. * * Copyright (c) 2000 Microsoft Corporation */ [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal abstract class LiteralTextParser { // The parsing methods (Parse, ParseTag, ParseTagAttributes, ParseText) // build up LiteralElement objects, which can either be text or tags. // ProcessElementInternal is then called. It combines some other data // and calls ProcessElement, a method which is overridable by inherited // classes. // Literal Element type - includes recognized tags. protected enum LiteralElementType { Unrecognized, Text, Bold, Italic, Break, Paragraph, Anchor, } // Available formatting options for literal elements. This enum can // be combined with the | operator. protected enum LiteralFormat { None = 0, Bold = 1, Italic = 2, } // Literal Element. protected class LiteralElement { public LiteralElementType Type; public IDictionary Attributes; public String Text; public LiteralFormat Format = LiteralFormat.None; public bool BreakAfter = false; public bool ForceBreakTag = false; public LiteralElement(String text) { Type = LiteralElementType.Text; Attributes = null; Text = text; } public LiteralElement(LiteralElementType type, IDictionary attributes) { Type = type; Attributes = attributes; Text = String.Empty; } public bool IsText { get { return Type == LiteralElementType.Text; } } public bool IsEmptyText { get { return IsText && !LiteralTextParser.IsValidText(Text); } } public String GetAttribute(String attributeName) { Object o = (Attributes != null) ? Attributes[attributeName] : null; return (o != null) ? (String)o : String.Empty; } } // Methods overriden by inherited classes. protected abstract void ProcessElement(LiteralElement element); protected abstract void ProcessTagInnerText(String text); private bool _isBreakingReset = true; private LiteralElement _lastQueuedElement = null; private LiteralElement _currentTag = null; private bool _beginNewParagraph = true; private FormatStack _formatStack = new FormatStack(); private bool _elementsProcessed = false; // Static constructor that builds a lookup table of recognized tags. private static IDictionary _recognizedTags = new Hashtable(); static LiteralTextParser() { // PERF: Add both lowercase and uppercase. _recognizedTags.Add("b", LiteralElementType.Bold); _recognizedTags.Add("B", LiteralElementType.Bold); _recognizedTags.Add("i", LiteralElementType.Italic); _recognizedTags.Add("I", LiteralElementType.Italic); _recognizedTags.Add("br", LiteralElementType.Break); _recognizedTags.Add("BR", LiteralElementType.Break); _recognizedTags.Add("p", LiteralElementType.Paragraph); _recognizedTags.Add("P", LiteralElementType.Paragraph); _recognizedTags.Add("a", LiteralElementType.Anchor); _recognizedTags.Add("A", LiteralElementType.Anchor); } // Convert a tag name to a type. private static LiteralElementType TagNameToType(String tagName) { Object o = _recognizedTags[tagName]; if (o == null) { o = _recognizedTags[tagName.ToLower(CultureInfo.InvariantCulture)]; } return (o != null) ? (LiteralElementType)o : LiteralElementType.Unrecognized; } // Returns true if any valid controls could be generated from the given text. internal /*public*/ static bool IsValidText(String validText) { // if (validText.Length == 0) { return false; } foreach (char c in validText) { if (!Char.IsWhiteSpace(c) && c != '\t' && c != '\r' && c != '\n') { return true; } } return false; } // Main parse routine. Called with a block of text to parse. internal /*public*/ void Parse(String literalText) { int length = literalText.Length; int currentPosition = 0; while (currentPosition < length) { // Find start of next tag. int nextTag = literalText.IndexOf('<', currentPosition); if (nextTag == -1) { ParseText(literalText.Substring(currentPosition)); break; } if (nextTag > currentPosition) { ParseText(literalText.Substring(currentPosition, nextTag - currentPosition)); } // Find end of tag. char quoteChar = '\0'; int endOfTag; for (endOfTag = nextTag + 1; endOfTag < length; endOfTag++) { char c = literalText[endOfTag]; if (quoteChar == '\0') { if (c == '\'' || c == '\"') { quoteChar = c; } else if (c == '>') { break; } } else { if (c == quoteChar) { quoteChar = '\0'; } } } if (endOfTag == length) { // break; } ParseTag(literalText, nextTag + 1, endOfTag); currentPosition = endOfTag + 1; } Flush(); } internal /*public*/ void ResetBreaking() { _isBreakingReset = true; ElementsProcessed = false; } internal /*public*/ void ResetNewParagraph() { _beginNewParagraph = false; } internal /*public*/ void UnResetBreaking() { _isBreakingReset = false; } protected bool ElementsProcessed { get { return _elementsProcessed; } set { _elementsProcessed = value; } } protected void OnAfterDataBoundLiteral() { ElementsProcessed = true; UnResetBreaking(); } // Parse a single tag. private void ParseTag(String literalText, int tagStart, int tagFinish) { bool isClosingTag = (literalText[tagStart] == '/'); if (isClosingTag) { tagStart++; } // Empty tag? if (tagStart == tagFinish) { return; } // Look for end of tag name. int tagNameFinish = tagStart; while (tagNameFinish < tagFinish && !Char.IsWhiteSpace(literalText[tagNameFinish]) && literalText[tagNameFinish] != '/') { tagNameFinish++; } // Extract tag name, and compare to recognized tags. String tagName = literalText.Substring(tagStart, tagNameFinish - tagStart); LiteralElementType tagType = TagNameToType(tagName); if (tagType == LiteralElementType.Unrecognized) { return; } // Are we already in a complex tag? if (_currentTag != null) { // Ignore any inner tags, except the closing tag. if (_currentTag.Type == tagType && isClosingTag) { ProcessElementInternal(_currentTag); _currentTag = null; } else { // } return; } switch (tagType) { case LiteralElementType.Paragraph: // Do not create two breaks for </p><p> pairs. if (!_isBreakingReset) { _isBreakingReset = true; goto case LiteralElementType.Break; } break; case LiteralElementType.Break: // If a break is already pending, insert an empty one. if (_beginNewParagraph) { ParseText(String.Empty); } if (_lastQueuedElement != null && _lastQueuedElement.Text.Length == 0) { _lastQueuedElement.ForceBreakTag = true; } _beginNewParagraph = true; break; case LiteralElementType.Bold: if (isClosingTag) { _formatStack.Pop(FormatStack.Bold); } else { _formatStack.Push(FormatStack.Bold); } break; case LiteralElementType.Italic: if (isClosingTag) { _formatStack.Pop(FormatStack.Italic); } else { _formatStack.Push(FormatStack.Italic); } break; default: { if (!isClosingTag) { IDictionary attribs = ParseTagAttributes(literalText, tagNameFinish, tagFinish, tagName); _currentTag = new LiteralElement(tagType, attribs); } break; } } if (_isBreakingReset && tagType != LiteralElementType.Paragraph) { _isBreakingReset = false; } } protected bool IsInTag { get { return _currentTag != null; } } protected LiteralFormat CurrentFormat { get { return _formatStack.CurrentFormat; } } // Parse attributes of a tag. private enum AttributeParseState { StartingAttributeName, ReadingAttributeName, ReadingEqualSign, StartingAttributeValue, ReadingAttributeValue, Error, } private IDictionary ParseTagAttributes(String literalText, int attrStart, int attrFinish, String tagName) { if (attrFinish > attrStart && literalText[attrFinish - 1] == '/') { attrFinish--; } IDictionary dictionary = null; int attrPos = attrStart; bool skipWhiteSpaces = true; int attrNameStart = 0; int attrNameFinish = 0; int attrValueStart = 0; char quoteChar = '\0'; AttributeParseState state = AttributeParseState.StartingAttributeName; while (attrPos <= attrFinish && state != AttributeParseState.Error) { char c = attrPos == attrFinish ? '\0' : literalText[attrPos]; if (skipWhiteSpaces) { if (Char.IsWhiteSpace(c)) { attrPos++; continue; } else { skipWhiteSpaces = false; } } switch (state) { case AttributeParseState.StartingAttributeName: if (c == '\0') { attrPos = attrFinish + 1; } else { attrNameStart = attrPos; state = AttributeParseState.ReadingAttributeName; } break; case AttributeParseState.ReadingAttributeName: if (c == '=' || Char.IsWhiteSpace(c)) { attrNameFinish = attrPos; skipWhiteSpaces = true; state = AttributeParseState.ReadingEqualSign; } else if (c == '\0') { state = AttributeParseState.Error; } else { attrPos++; } break; case AttributeParseState.ReadingEqualSign: if (c == '=') { skipWhiteSpaces = true; state = AttributeParseState.StartingAttributeValue; attrPos++; } else { state = AttributeParseState.Error; } break; case AttributeParseState.StartingAttributeValue: attrValueStart = attrPos; if (c == '\0') { state = AttributeParseState.Error; break; } else if (c == '\"' || c == '\'') { quoteChar = c; attrValueStart++; attrPos++; } else { quoteChar = '\0'; } state = AttributeParseState.ReadingAttributeValue; break; case AttributeParseState.ReadingAttributeValue: if (c == quoteChar || ((Char.IsWhiteSpace(c) || c == '\0') && quoteChar == '\0')) { if (attrNameFinish == attrNameStart) { state = AttributeParseState.Error; break; } if (dictionary == null) { dictionary = new HybridDictionary(true); } dictionary.Add( literalText.Substring(attrNameStart, attrNameFinish - attrNameStart), literalText.Substring(attrValueStart, attrPos - attrValueStart)); skipWhiteSpaces = true; state = AttributeParseState.StartingAttributeName; if (c == quoteChar) { attrPos++; } } else { attrPos++; } break; } } if (state == AttributeParseState.Error) { throw new Exception(SR.GetString(SR.LiteralTextParser_InvalidTagFormat)); } return dictionary; } // Parse a plain text literal. private void ParseText(String text) { if (_currentTag != null) { // Add to inner text of tag. _currentTag.Text += text; } else { if (_isBreakingReset && IsValidText(text)) { _isBreakingReset = false; } ProcessElementInternal(new LiteralElement(text)); } } private void ProcessElementInternal(LiteralElement element) { // This method needs to fill in an element with formatting and // breaking information, and calls ProcessElement. However, // each element needs to know whether there will be a break // AFTER the element, so elements are processed lazily, keeping // the last one in a single-element queue. LiteralFormat currentFormat = _formatStack.CurrentFormat; if (_lastQueuedElement != null) { // If both the last and current element are text elements, and // the formatting hasn't changed, then just combine the two into // a single element. if (_lastQueuedElement.IsText && element.IsText && (_lastQueuedElement.Format == currentFormat) && !_beginNewParagraph) { _lastQueuedElement.Text += element.Text; return; } else if (_lastQueuedElement.IsEmptyText && !_beginNewParagraph && IgnoreWhiteSpaceElement(_lastQueuedElement)) { // Empty text element with no breaks - so just ignore. } else { _lastQueuedElement.BreakAfter = _beginNewParagraph; ProcessElement(_lastQueuedElement); ElementsProcessed = true; } } _lastQueuedElement = element; _lastQueuedElement.Format = currentFormat; _beginNewParagraph = false; } private void Flush() { if (_currentTag != null) { // In the middle of a tag. There may be multiple inner text elements inside // a tag, e.g. // <a ...>some text <%# a databinding %> some more text</a> // and we're being flushed just at the start of the databinding. if (!_currentTag.IsEmptyText) { ProcessTagInnerText(_currentTag.Text); } _currentTag.Text = String.Empty; return; } if (_lastQueuedElement == null) { return; } // Ignore orphaned whitespace. if (!_lastQueuedElement.ForceBreakTag && _lastQueuedElement.IsEmptyText) { if (!ElementsProcessed) { return; } if (_lastQueuedElement.Text.Length == 0 || _lastQueuedElement.Text[0] != ' ') { return; } _lastQueuedElement.Text = " "; } _lastQueuedElement.BreakAfter = _beginNewParagraph; ProcessElement(_lastQueuedElement); _lastQueuedElement = null; } protected virtual bool IgnoreWhiteSpaceElement(LiteralElement element) { return true; } /* * FormatStack private class * * This class maintains a simple stack of formatting directives. As tags and * closing tags are processed, they are pushed on and popped off this stack. * The CurrentFormat property returns the current state. */ private class FormatStack { internal const char Bold = 'b'; internal const char Italic = 'i'; private StringBuilder _stringBuilder = new StringBuilder(16); public void Push(char option) { _stringBuilder.Append(option); } public void Pop(char option) { // Only pop a matching directive - non-matching directives are ignored! int length = _stringBuilder.Length; if (length > 0 && _stringBuilder[length - 1] == option) { _stringBuilder.Remove(length - 1, 1); } } public LiteralFormat CurrentFormat { get { LiteralFormat format = LiteralFormat.None; for (int i = _stringBuilder.Length - 1; i >= 0; i--) { switch (_stringBuilder[i]) { case Bold: format |= LiteralFormat.Bold; break; case Italic: format |= LiteralFormat.Italic; break; } } return format; } } } } }
using System; using System.Linq; using System.Collections.Generic; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Formatting; namespace RefactoringEssentials.CSharp.CodeRefactorings { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert 'if' to 'switch'")] public class ConvertIfStatementToSwitchStatementCodeRefactoringProvider : CodeRefactoringProvider { public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; var span = context.Span; if (!span.IsEmpty) return; var cancellationToken = context.CancellationToken; if (cancellationToken.IsCancellationRequested) return; var root = await document.GetSyntaxRootAsync(cancellationToken); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (model.IsFromGeneratedCode(cancellationToken)) return; var node = root.FindNode(span) as IfStatementSyntax; if (node == null) return; var switchExpr = GetSwitchExpression(model, node.Condition); if (switchExpr == null) return; var switchSections = new List<SwitchSectionSyntax>(); if (!CollectSwitchSections(switchSections, model, node, switchExpr)) return; context.RegisterRefactoring( CodeActionFactory.Create( span, DiagnosticSeverity.Info, GettextCatalog.GetString("To 'switch'"), ct => { var switchStatement = SyntaxFactory.SwitchStatement(switchExpr, new SyntaxList<SwitchSectionSyntax>().AddRange(switchSections)); return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode( (SyntaxNode)node, switchStatement .WithLeadingTrivia(node.GetLeadingTrivia()) .WithAdditionalAnnotations(Formatter.Annotation)))); }) ); } internal static ExpressionSyntax GetSwitchExpression(SemanticModel context, ExpressionSyntax expr) { var binaryOp = expr as BinaryExpressionSyntax; if (binaryOp == null) return null; if (binaryOp.OperatorToken.IsKind(SyntaxKind.LogicalOrExpression)) return GetSwitchExpression(context, binaryOp.Left); if (binaryOp.OperatorToken.IsKind(SyntaxKind.EqualsEqualsToken)) { ExpressionSyntax switchExpr = null; if (IsConstantExpression(context, binaryOp.Right)) switchExpr = binaryOp.Left; if (IsConstantExpression(context, binaryOp.Left)) switchExpr = binaryOp.Right; if (switchExpr != null && IsValidSwitchType(context.GetTypeInfo(switchExpr).Type)) return switchExpr; } return null; } static bool IsConstantExpression(SemanticModel context, ExpressionSyntax expr) { if (expr is LiteralExpressionSyntax) return true; if (expr is DefaultExpressionSyntax) return true; return context.GetConstantValue(expr).HasValue; } static readonly SpecialType[] validTypes = { SpecialType.System_String, SpecialType.System_Boolean, SpecialType.System_Char, SpecialType.System_Byte, SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_Int32, SpecialType.System_Int64, SpecialType.System_UInt16, SpecialType.System_UInt32, SpecialType.System_UInt64 }; static bool IsValidSwitchType(ITypeSymbol type) { if (type == null || type is IErrorTypeSymbol) return false; if (type.TypeKind == TypeKind.Enum) return true; if (type.IsNullableType()) { type = type.GetNullableUnderlyingType(); if (type == null || type is IErrorTypeSymbol) return false; } return Array.IndexOf(validTypes, type.SpecialType) != -1; } internal static bool CollectSwitchSections(List<SwitchSectionSyntax> result, SemanticModel context, IfStatementSyntax ifStatement, ExpressionSyntax switchExpr) { // if var labels = new List<SwitchLabelSyntax>(); if (!CollectCaseLabels(labels, context, ifStatement.Condition, switchExpr)) return false; var statements = new List<StatementSyntax>(); CollectSwitchSectionStatements(statements, context, ifStatement.Statement); result.Add(SyntaxFactory.SwitchSection(new SyntaxList<SwitchLabelSyntax>().AddRange(labels), new SyntaxList<StatementSyntax>().AddRange(statements))); if (ifStatement.Statement.DescendantNodes().Any(n => n is BreakStatementSyntax)) return false; if (ifStatement.Else == null) return true; // else if var falseStatement = ifStatement.Else.Statement as IfStatementSyntax; if (falseStatement != null) return CollectSwitchSections(result, context, falseStatement, switchExpr); if (ifStatement.Else.Statement.DescendantNodes().Any(n => n is BreakStatementSyntax)) return false; // else (default label) labels = new List<SwitchLabelSyntax>(); labels.Add(SyntaxFactory.DefaultSwitchLabel()); statements = new List<StatementSyntax>(); CollectSwitchSectionStatements(statements, context, ifStatement.Else.Statement); result.Add(SyntaxFactory.SwitchSection(new SyntaxList<SwitchLabelSyntax>().AddRange(labels), new SyntaxList<StatementSyntax>().AddRange(statements))); return true; } static bool CollectCaseLabels(List<SwitchLabelSyntax> result, SemanticModel context, ExpressionSyntax condition, ExpressionSyntax switchExpr) { if (condition is ParenthesizedExpressionSyntax) return CollectCaseLabels(result, context, ((ParenthesizedExpressionSyntax)condition).Expression, switchExpr); var binaryOp = condition as BinaryExpressionSyntax; if (binaryOp == null) return false; if (binaryOp.IsKind(SyntaxKind.LogicalOrExpression)) return CollectCaseLabels(result, context, binaryOp.Left, switchExpr) && CollectCaseLabels(result, context, binaryOp.Right, switchExpr); if (binaryOp.IsKind(SyntaxKind.EqualsExpression)) { if (switchExpr.IsEquivalentTo(binaryOp.Left, true)) { if (IsConstantExpression(context, binaryOp.Right)) { result.Add(SyntaxFactory.CaseSwitchLabel(binaryOp.Right)); return true; } } else if (switchExpr.IsEquivalentTo(binaryOp.Right, true)) { if (IsConstantExpression(context, binaryOp.Left)) { result.Add(SyntaxFactory.CaseSwitchLabel(binaryOp.Left)); return true; } } } return false; } static void CollectSwitchSectionStatements(List<StatementSyntax> result, SemanticModel context, StatementSyntax statement) { var blockStatement = statement as BlockSyntax; if (blockStatement != null) result.AddRange(blockStatement.Statements); else result.Add(statement); // add 'break;' at end if necessary var reachabilityAnalysis = context.AnalyzeControlFlow(statement); if (reachabilityAnalysis.EndPointIsReachable) result.Add(SyntaxFactory.BreakStatement()); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.StreamAnalytics { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// TransformationsOperations operations. /// </summary> internal partial class TransformationsOperations : IServiceOperations<StreamAnalyticsManagementClient>, ITransformationsOperations { /// <summary> /// Initializes a new instance of the TransformationsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal TransformationsOperations(StreamAnalyticsManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the StreamAnalyticsManagementClient /// </summary> public StreamAnalyticsManagementClient Client { get; private set; } /// <summary> /// Creates a transformation or replaces an already existing transformation /// under an existing streaming job. /// </summary> /// <param name='transformation'> /// The definition of the transformation that will be used to create a new /// transformation or replace the existing one under the streaming job. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='jobName'> /// The name of the streaming job. /// </param> /// <param name='transformationName'> /// The name of the transformation. /// </param> /// <param name='ifMatch'> /// The ETag of the transformation. Omit this value to always overwrite the /// current transformation. Specify the last-seen ETag value to prevent /// accidentally overwritting concurrent changes. /// </param> /// <param name='ifNoneMatch'> /// Set to '*' to allow a new transformation to be created, but to prevent /// updating an existing transformation. Other values will result in a 412 /// Pre-condition Failed response. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Transformation,TransformationsCreateOrReplaceHeaders>> CreateOrReplaceWithHttpMessagesAsync(Transformation transformation, string resourceGroupName, string jobName, string transformationName, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (transformation == null) { throw new ValidationException(ValidationRules.CannotBeNull, "transformation"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (jobName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "jobName"); } if (transformationName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "transformationName"); } string apiVersion = "2016-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("transformation", transformation); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("ifNoneMatch", ifNoneMatch); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("transformationName", transformationName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrReplace", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/transformations/{transformationName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName)); _url = _url.Replace("{transformationName}", System.Uri.EscapeDataString(transformationName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (ifNoneMatch != null) { if (_httpRequest.Headers.Contains("If-None-Match")) { _httpRequest.Headers.Remove("If-None-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(transformation != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(transformation, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Transformation,TransformationsCreateOrReplaceHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Transformation>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Transformation>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<TransformationsCreateOrReplaceHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates an existing transformation under an existing streaming job. This /// can be used to partially update (ie. update one or two properties) a /// transformation without affecting the rest the job or transformation /// definition. /// </summary> /// <param name='transformation'> /// A Transformation object. The properties specified here will overwrite the /// corresponding properties in the existing transformation (ie. Those /// properties will be updated). Any properties that are set to null here will /// mean that the corresponding property in the existing transformation will /// remain the same and not change as a result of this PATCH operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='jobName'> /// The name of the streaming job. /// </param> /// <param name='transformationName'> /// The name of the transformation. /// </param> /// <param name='ifMatch'> /// The ETag of the transformation. Omit this value to always overwrite the /// current transformation. Specify the last-seen ETag value to prevent /// accidentally overwritting concurrent changes. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Transformation,TransformationsUpdateHeaders>> UpdateWithHttpMessagesAsync(Transformation transformation, string resourceGroupName, string jobName, string transformationName, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (transformation == null) { throw new ValidationException(ValidationRules.CannotBeNull, "transformation"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (jobName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "jobName"); } if (transformationName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "transformationName"); } string apiVersion = "2016-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("transformation", transformation); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("transformationName", transformationName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/transformations/{transformationName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName)); _url = _url.Replace("{transformationName}", System.Uri.EscapeDataString(transformationName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(transformation != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(transformation, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Transformation,TransformationsUpdateHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Transformation>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<TransformationsUpdateHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets details about the specified transformation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='jobName'> /// The name of the streaming job. /// </param> /// <param name='transformationName'> /// The name of the transformation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Transformation,TransformationsGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string jobName, string transformationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (jobName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "jobName"); } if (transformationName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "transformationName"); } string apiVersion = "2016-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("transformationName", transformationName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/transformations/{transformationName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName)); _url = _url.Replace("{transformationName}", System.Uri.EscapeDataString(transformationName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Transformation,TransformationsGetHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Transformation>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<TransformationsGetHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using WhatsAppApi.Parser; using WhatsAppApi.Settings; namespace WhatsAppApi.Register { public static class WhatsRegisterV2 { public static string GenerateIdentity(string phoneNumber, string salt = "") { return (phoneNumber + salt).Reverse().ToSHAString(); } public static string GetToken(string number) { return WaToken.GenerateToken(number); } public static bool RequestCode(string phoneNumber, out string password, string method = "sms", string id = null) { string response = string.Empty; return RequestCode(phoneNumber, out password, out response, method, id); } public static bool RequestCode(string phoneNumber, out string password, out string response, string method = "sms", string id = null) { string request = string.Empty; return RequestCode(phoneNumber, out password, out request, out response, method, id); } public static bool RequestCode(string phoneNumber, out string password, out string request, out string response, string method = "sms", string id = null) { response = null; password = null; request = null; try { if (string.IsNullOrEmpty(id)) { //auto-generate id = GenerateIdentity(phoneNumber); } PhoneNumber pn = new PhoneNumber(phoneNumber); string token = System.Uri.EscapeDataString(WhatsRegisterV2.GetToken(pn.Number)); request = String.Format("https://v.whatsapp.net/v2/code?method={0}&in={1}&cc={2}&id={3}&lg={4}&lc={5}&token={6}&sim_mcc=000&sim_mnc=000", method, pn.Number, pn.CC, id, pn.ISO639, pn.ISO3166, token, pn.MCC, pn.MNC); response = GetResponse(request); password = response.GetJsonValue("pw"); if (!string.IsNullOrEmpty(password)) { return true; } return (response.GetJsonValue("status") == "sent"); } catch(Exception e) { response = e.Message; return false; } } public static string RegisterCode(string phoneNumber, string code, string id = null) { string response = string.Empty; return WhatsRegisterV2.RegisterCode(phoneNumber, code, out response, id); } public static string RegisterCode(string phoneNumber, string code, out string response, string id = null) { response = string.Empty; try { if (string.IsNullOrEmpty(id)) { //auto generate id = GenerateIdentity(phoneNumber); } PhoneNumber pn = new PhoneNumber(phoneNumber); string uri = string.Format("https://v.whatsapp.net/v2/register?cc={0}&in={1}&id={2}&code={3}", pn.CC, pn.Number, id, code); response = GetResponse(uri); if (response.GetJsonValue("status") == "ok") { return response.GetJsonValue("pw"); } return null; } catch { return null; } } public static string RequestExist(string phoneNumber, string id = null) { string response = string.Empty; return RequestExist(phoneNumber, out response, id); } public static string RequestExist(string phoneNumber, out string response, string id = null) { response = string.Empty; try { if (String.IsNullOrEmpty(id)) { id = GenerateIdentity(phoneNumber); } PhoneNumber pn = new PhoneNumber(phoneNumber); string uri = string.Format("https://v.whatsapp.net/v2/exist?cc={0}&in={1}&id={2}&&lg={3}&lc={4}", pn.CC, pn.Number, id, pn.ISO639, pn.ISO3166); response = GetResponse(uri); if (response.GetJsonValue("status") == "ok") { return response.GetJsonValue("pw"); } return null; } catch { return null; } } private static string GetResponse(string uri) { HttpWebRequest request = HttpWebRequest.Create(new Uri(uri)) as HttpWebRequest; request.KeepAlive = false; request.UserAgent = WhatsConstants.UserAgent; request.Accept = "text/json"; using (var reader = new System.IO.StreamReader(request.GetResponse().GetResponseStream())) { return reader.ReadLine(); } } private static string ToSHAString(this IEnumerable<char> s) { return new string(s.ToArray()).ToSHAString(); } public static string UrlEncode(string data) { StringBuilder sb = new StringBuilder(); foreach (char c in data.ToCharArray()) { int i = (int)c; if ( ( i >= 0 && i <= 31 ) || ( i >= 32 && i <= 47 ) || ( i >= 58 && i <= 64 ) || ( i >= 91 && i <= 96 ) || ( i >= 123 && i <= 126 ) || i > 127 ) { //encode sb.Append('%'); sb.AppendFormat("{0:x2}", (byte)c); } else { //do not encode sb.Append(c); } } return sb.ToString(); } private static string ToSHAString(this string s) { byte[] data = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(s)); string str = Encoding.GetEncoding("iso-8859-1").GetString(data); str = WhatsRegisterV2.UrlEncode(str).ToLower(); return str; } private static string ToMD5String(this IEnumerable<char> s) { return new string(s.ToArray()).ToMD5String(); } private static string ToMD5String(this string s) { return string.Join(string.Empty, MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(item => item.ToString("x2")).ToArray()); } private static void GetLanguageAndLocale(this CultureInfo self, out string language, out string locale) { string name = self.Name; int n1 = name.IndexOf('-'); if (n1 > 0) { int n2 = name.LastIndexOf('-'); language = name.Substring(0, n1); locale = name.Substring(n2 + 1); } else { language = name; switch (language) { case "cs": locale = "CZ"; return; case "da": locale = "DK"; return; case "el": locale = "GR"; return; case "ja": locale = "JP"; return; case "ko": locale = "KR"; return; case "sv": locale = "SE"; return; case "sr": locale = "RS"; return; } locale = language.ToUpper(); } } private static string GetJsonValue(this string s, string parameter) { Match match; if ((match = Regex.Match(s, string.Format("\"?{0}\"?:\"(?<Value>.+?)\"", parameter), RegexOptions.Singleline | RegexOptions.IgnoreCase)).Success) { return match.Groups["Value"].Value; } return null; } } }
//------------------------------------------------------------------------------ // <copyright file="MBThreadService.cs"> // Copyright (c) 2014-present Andrea Di Giorgi // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // </copyright> // <author>Andrea Di Giorgi</author> // <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Liferay.SDK.Service.V62.MBThread { public class MBThreadService : ServiceBase { public MBThreadService(ISession session) : base(session) { } public async Task DeleteThreadAsync(long threadId) { var _parameters = new JsonObject(); _parameters.Add("threadId", threadId); var _command = new JsonObject() { { "/mbthread/delete-thread", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task<IEnumerable<dynamic>> GetGroupThreadsAsync(long groupId, long userId, int status, int start, int end) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("status", status); _parameters.Add("start", start); _parameters.Add("end", end); var _command = new JsonObject() { { "/mbthread/get-group-threads", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetGroupThreadsAsync(long groupId, long userId, long modifiedDate, int status, int start, int end) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("modifiedDate", modifiedDate); _parameters.Add("status", status); _parameters.Add("start", start); _parameters.Add("end", end); var _command = new JsonObject() { { "/mbthread/get-group-threads", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetGroupThreadsAsync(long groupId, long userId, int status, bool subscribed, int start, int end) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("status", status); _parameters.Add("subscribed", subscribed); _parameters.Add("start", start); _parameters.Add("end", end); var _command = new JsonObject() { { "/mbthread/get-group-threads", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetGroupThreadsAsync(long groupId, long userId, int status, bool subscribed, bool includeAnonymous, int start, int end) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("status", status); _parameters.Add("subscribed", subscribed); _parameters.Add("includeAnonymous", includeAnonymous); _parameters.Add("start", start); _parameters.Add("end", end); var _command = new JsonObject() { { "/mbthread/get-group-threads", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<long> GetGroupThreadsCountAsync(long groupId, long userId, int status) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("status", status); var _command = new JsonObject() { { "/mbthread/get-group-threads-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<long> GetGroupThreadsCountAsync(long groupId, long userId, long modifiedDate, int status) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("modifiedDate", modifiedDate); _parameters.Add("status", status); var _command = new JsonObject() { { "/mbthread/get-group-threads-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<long> GetGroupThreadsCountAsync(long groupId, long userId, int status, bool subscribed) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("status", status); _parameters.Add("subscribed", subscribed); var _command = new JsonObject() { { "/mbthread/get-group-threads-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<long> GetGroupThreadsCountAsync(long groupId, long userId, int status, bool subscribed, bool includeAnonymous) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("status", status); _parameters.Add("subscribed", subscribed); _parameters.Add("includeAnonymous", includeAnonymous); var _command = new JsonObject() { { "/mbthread/get-group-threads-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<IEnumerable<dynamic>> GetThreadsAsync(long groupId, long categoryId, int status, int start, int end) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("categoryId", categoryId); _parameters.Add("status", status); _parameters.Add("start", start); _parameters.Add("end", end); var _command = new JsonObject() { { "/mbthread/get-threads", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<long> GetThreadsCountAsync(long groupId, long categoryId, int status) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("categoryId", categoryId); _parameters.Add("status", status); var _command = new JsonObject() { { "/mbthread/get-threads-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<dynamic> LockThreadAsync(long threadId) { var _parameters = new JsonObject(); _parameters.Add("threadId", threadId); var _command = new JsonObject() { { "/mbthread/lock-thread", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> MoveThreadAsync(long categoryId, long threadId) { var _parameters = new JsonObject(); _parameters.Add("categoryId", categoryId); _parameters.Add("threadId", threadId); var _command = new JsonObject() { { "/mbthread/move-thread", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> MoveThreadFromTrashAsync(long categoryId, long threadId) { var _parameters = new JsonObject(); _parameters.Add("categoryId", categoryId); _parameters.Add("threadId", threadId); var _command = new JsonObject() { { "/mbthread/move-thread-from-trash", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> MoveThreadToTrashAsync(long threadId) { var _parameters = new JsonObject(); _parameters.Add("threadId", threadId); var _command = new JsonObject() { { "/mbthread/move-thread-to-trash", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task RestoreThreadFromTrashAsync(long threadId) { var _parameters = new JsonObject(); _parameters.Add("threadId", threadId); var _command = new JsonObject() { { "/mbthread/restore-thread-from-trash", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task<dynamic> SearchAsync(long groupId, long creatorUserId, int status, int start, int end) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("creatorUserId", creatorUserId); _parameters.Add("status", status); _parameters.Add("start", start); _parameters.Add("end", end); var _command = new JsonObject() { { "/mbthread/search", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> SearchAsync(long groupId, long creatorUserId, long startDate, long endDate, int status, int start, int end) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("creatorUserId", creatorUserId); _parameters.Add("startDate", startDate); _parameters.Add("endDate", endDate); _parameters.Add("status", status); _parameters.Add("start", start); _parameters.Add("end", end); var _command = new JsonObject() { { "/mbthread/search", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> SplitThreadAsync(long messageId, string subject, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("messageId", messageId); _parameters.Add("subject", subject); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/mbthread/split-thread", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task UnlockThreadAsync(long threadId) { var _parameters = new JsonObject(); _parameters.Add("threadId", threadId); var _command = new JsonObject() { { "/mbthread/unlock-thread", _parameters } }; await this.Session.InvokeAsync(_command); } } }
#region File Description //----------------------------------------------------------------------------- // EquipmentScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using RolePlayingGameData; #endregion namespace RolePlaying { /// <summary> /// Lists the player's equipped gear, and allows the user to unequip them. /// </summary> class EquipmentScreen : ListScreen<Equipment> { #region Columns protected string nameColumnText = "Name"; private const int nameColumnInterval = 80; protected string powerColumnText = "Power (min, max)"; private const int powerColumnInterval = 270; protected string slotColumnText = "Slot"; private const int slotColumnInterval = 400; #endregion #region Data Access /// <summary> /// The FightingCharacter object whose equipment is displayed. /// </summary> private FightingCharacter fightingCharacter; /// <summary> /// Get the list that this screen displays. /// </summary> public override ReadOnlyCollection<Equipment> GetDataList() { return fightingCharacter.EquippedEquipment.AsReadOnly(); } #endregion #region Initialization /// <summary> /// Creates a new EquipmentScreen object for the given player. /// </summary> public EquipmentScreen(FightingCharacter fightingCharacter) : base() { // check the parameter if (fightingCharacter == null) { throw new ArgumentNullException("fightingCharacter"); } this.fightingCharacter = fightingCharacter; // sort the player's equipment this.fightingCharacter.EquippedEquipment.Sort( delegate(Equipment equipment1, Equipment equipment2) { // handle null values if (equipment1 == null) { return (equipment2 == null ? 0 : 1); } else if (equipment2 == null) { return -1; } // handle weapons - they're always first in the list if (equipment1 is Weapon) { return (equipment2 is Weapon ? equipment1.Name.CompareTo(equipment2.Name) : -1); } else if (equipment2 is Weapon) { return 1; } // compare armor slots Armor armor1 = equipment1 as Armor; Armor armor2 = equipment2 as Armor; if ((armor1 != null) && (armor2 != null)) { return armor1.Slot.CompareTo(armor2.Slot); } return 0; }); // configure the menu text titleText = "Equipped Gear"; selectButtonText = String.Empty; backButtonText = "Back"; xButtonText = "Unequip"; yButtonText = String.Empty; leftTriggerText = String.Empty; rightTriggerText = String.Empty; } #endregion #region Input Handling /// <summary> /// Respond to the triggering of the X button (and related key). /// </summary> protected override void ButtonXPressed(Equipment entry) { // remove the equipment from the player's equipped list fightingCharacter.Unequip(entry); // add the equipment back to the party's inventory Session.Party.AddToInventory(entry, 1); } #endregion #region Drawing /// <summary> /// Draw the equipment at the given position in the list. /// </summary> /// <param name="contentEntry">The equipment to draw.</param> /// <param name="position">The position to draw the entry at.</param> /// <param name="isSelected">If true, this item is selected.</param> protected override void DrawEntry(Equipment entry, Vector2 position, bool isSelected) { // check the parameter if (entry == null) { throw new ArgumentNullException("entry"); } SpriteBatch spriteBatch = ScreenManager.SpriteBatch; Vector2 drawPosition = position; // draw the icon spriteBatch.Draw(entry.IconTexture, drawPosition + iconOffset, Color.White); // draw the name Color color = isSelected ? Fonts.HighlightColor : Fonts.DisplayColor; drawPosition.Y += listLineSpacing / 4; drawPosition.X += nameColumnInterval; spriteBatch.DrawString(Fonts.GearInfoFont, entry.Name, drawPosition, color); // draw the power drawPosition.X += powerColumnInterval; string powerText = entry.GetPowerText(); Vector2 powerTextSize = Fonts.GearInfoFont.MeasureString(powerText); Vector2 powerPosition = drawPosition; powerPosition.Y -= (float)Math.Ceiling((powerTextSize.Y - 30f) / 2); spriteBatch.DrawString(Fonts.GearInfoFont, powerText, powerPosition, color); // draw the slot drawPosition.X += slotColumnInterval; if (entry is Weapon) { spriteBatch.DrawString(Fonts.GearInfoFont, "Weapon", drawPosition, color); } else if (entry is Armor) { Armor armor = entry as Armor; spriteBatch.DrawString(Fonts.GearInfoFont, armor.Slot.ToString(), drawPosition, color); } // turn on or off the unequip button if (isSelected) { xButtonText = "Unequip"; } } /// <summary> /// Draw the description of the selected item. /// </summary> protected override void DrawSelectedDescription(Equipment entry) { // check the parameter if (entry == null) { throw new ArgumentNullException("entry"); } SpriteBatch spriteBatch = ScreenManager.SpriteBatch; Vector2 position = descriptionTextPosition; // draw the description // -- it's up to the content owner to fit the description string text = entry.Description; if (!String.IsNullOrEmpty(text)) { spriteBatch.DrawString(Fonts.DescriptionFont, text, position, Fonts.DescriptionColor); position.Y += Fonts.DescriptionFont.LineSpacing; } // draw the modifiers text = entry.OwnerBuffStatistics.GetModifierString(); if (!String.IsNullOrEmpty(text)) { spriteBatch.DrawString(Fonts.DescriptionFont, text, position, Fonts.DescriptionColor); position.Y += Fonts.DescriptionFont.LineSpacing; } // draw the restrictions text = entry.GetRestrictionsText(); if (!String.IsNullOrEmpty(text)) { spriteBatch.DrawString(Fonts.DescriptionFont, text, position, Fonts.DescriptionColor); position.Y += Fonts.DescriptionFont.LineSpacing; } } /// <summary> /// Draw the column headers above the list. /// </summary> protected override void DrawColumnHeaders() { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; Vector2 position = listEntryStartPosition; position.X += nameColumnInterval; if (!String.IsNullOrEmpty(nameColumnText)) { spriteBatch.DrawString(Fonts.CaptionFont, nameColumnText, position, Fonts.CaptionColor); } position.X += powerColumnInterval; if (!String.IsNullOrEmpty(powerColumnText)) { spriteBatch.DrawString(Fonts.CaptionFont, powerColumnText, position, Fonts.CaptionColor); } position.X += slotColumnInterval; if (!String.IsNullOrEmpty(slotColumnText)) { spriteBatch.DrawString(Fonts.CaptionFont, slotColumnText, position, Fonts.CaptionColor); } } #endregion } }
using System; using System.Collections.Generic; using System.Net; using System.Runtime.Serialization; using System.Threading; using Funq; using ServiceStack.Common.Extensions; using ServiceStack.Common.Web; using ServiceStack.Configuration; using ServiceStack.DataAnnotations; using ServiceStack.Logging; using ServiceStack.Logging.Support.Logging; using ServiceStack.OrmLite; using ServiceStack.OrmLite.Sqlite; using ServiceStack.Plugins.ProtoBuf; using ServiceStack.ServiceHost; using ServiceStack.ServiceInterface; using ServiceStack.ServiceInterface.ServiceModel; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints.Tests.IntegrationTests; using ServiceStack.WebHost.Endpoints.Tests.Support.Operations; namespace ServiceStack.WebHost.Endpoints.Tests.Support.Host { [Route("/factorial/{ForNumber}")] [DataContract] public class GetFactorial { [DataMember] public long ForNumber { get; set; } } [DataContract] public class GetFactorialResponse { [DataMember] public long Result { get; set; } } public class GetFactorialService : IService<GetFactorial> { public object Execute(GetFactorial request) { return new GetFactorialResponse { Result = GetFactorial(request.ForNumber) }; } public static long GetFactorial(long n) { return n > 1 ? n * GetFactorial(n - 1) : 1; } } [DataContract] public class AlwaysThrows { } [DataContract] public class AlwaysThrowsResponse : IHasResponseStatus { [DataMember] public ResponseStatus ResponseStatus { get; set; } } public class AlwaysThrowsService : ServiceBase<AlwaysThrows> { protected override object Run(AlwaysThrows request) { throw new ArgumentException("This service always throws an error"); } } [Route("/movies", "POST,PUT")] [Route("/movies/{Id}")] [DataContract] public class Movie { public Movie() { this.Genres = new List<string>(); } [DataMember(Order = 1)] [AutoIncrement] public int Id { get; set; } [DataMember(Order = 2)] public string ImdbId { get; set; } [DataMember(Order = 3)] public string Title { get; set; } [DataMember(Order = 4)] public decimal Rating { get; set; } [DataMember(Order = 5)] public string Director { get; set; } [DataMember(Order = 6)] public DateTime ReleaseDate { get; set; } [DataMember(Order = 7)] public string TagLine { get; set; } [DataMember(Order = 8)] public List<string> Genres { get; set; } #region AutoGen ReSharper code, only required by tests public bool Equals(Movie other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.ImdbId, ImdbId) && Equals(other.Title, Title) && other.Rating == Rating && Equals(other.Director, Director) && other.ReleaseDate.Equals(ReleaseDate) && Equals(other.TagLine, TagLine) && Genres.EquivalentTo(other.Genres); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(Movie)) return false; return Equals((Movie)obj); } public override int GetHashCode() { return ImdbId != null ? ImdbId.GetHashCode() : 0; } #endregion } [DataContract] public class MovieResponse { [DataMember] public Movie Movie { get; set; } } public class MovieService : RestServiceBase<Movie> { public IDbConnectionFactory DbFactory { get; set; } /// <summary> /// GET /movies/{Id} /// </summary> public override object OnGet(Movie movie) { return new MovieResponse { Movie = DbFactory.Run(db => db.GetById<Movie>(movie.Id)) }; } /// <summary> /// POST /movies /// </summary> public override object OnPost(Movie movie) { var newMovieId = DbFactory.Run(db => { db.Insert(movie); return db.GetLastInsertId(); }); var newMovie = new MovieResponse { Movie = DbFactory.Run(db => db.GetById<Movie>(newMovieId)) }; return new HttpResult(newMovie) { StatusCode = HttpStatusCode.Created, Headers = { { HttpHeaders.Location, this.RequestContext.AbsoluteUri.WithTrailingSlash() + newMovieId } } }; } /// <summary> /// PUT /movies /// </summary> public override object OnPut(Movie movie) { DbFactory.Run(db => db.Save(movie)); return new MovieResponse(); } /// <summary> /// DELETE /movies/{Id} /// </summary> public override object OnDelete(Movie request) { DbFactory.Run(db => db.DeleteById<Movie>(request.Id)); return new MovieResponse(); } } [DataContract] [Route("/movies", "GET")] [Route("/movies/genres/{Genre}")] public class Movies { [DataMember] public string Genre { get; set; } [DataMember] public Movie Movie { get; set; } } [DataContract] public class MoviesResponse { public MoviesResponse() { Movies = new List<Movie>(); } [DataMember(Order = 1)] public List<Movie> Movies { get; set; } } public class MoviesService : RestServiceBase<Movies> { public IDbConnectionFactory DbFactory { get; set; } /// <summary> /// GET /movies /// GET /movies/genres/{Genre} /// </summary> public override object OnGet(Movies request) { var response = new MoviesResponse { Movies = request.Genre.IsNullOrEmpty() ? DbFactory.Run(db => db.Select<Movie>()) : DbFactory.Run(db => db.Select<Movie>("Genres LIKE {0}", "%" + request.Genre + "%")) }; return response; } } public class MoviesZip { public string Genre { get; set; } public Movie Movie { get; set; } } public class MoviesZipResponse { public MoviesZipResponse() { Movies = new List<Movie>(); } public List<Movie> Movies { get; set; } } public class MoviesZipService : RestServiceBase<MoviesZip> { public IDbConnectionFactory DbFactory { get; set; } public override object OnGet(MoviesZip request) { return OnPost(request); } public override object OnPost(MoviesZip request) { var response = new MoviesZipResponse { Movies = request.Genre.IsNullOrEmpty() ? DbFactory.Run(db => db.Select<Movie>()) : DbFactory.Run(db => db.Select<Movie>("Genres LIKE {0}", "%" + request.Genre + "%")) }; return RequestContext.ToOptimizedResult(response); } } [DataContract] [Route("/reset-movies")] public class ResetMovies { } [DataContract] public class ResetMoviesResponse : IHasResponseStatus { public ResetMoviesResponse() { this.ResponseStatus = new ResponseStatus(); } [DataMember] public ResponseStatus ResponseStatus { get; set; } } public class ResetMoviesService : RestServiceBase<ResetMovies> { public static List<Movie> Top5Movies = new List<Movie> { new Movie { ImdbId = "tt0111161", Title = "The Shawshank Redemption", Rating = 9.2m, Director = "Frank Darabont", ReleaseDate = new DateTime(1995,2,17), TagLine = "Fear can hold you prisoner. Hope can set you free.", Genres = new List<string>{"Crime","Drama"}, }, new Movie { ImdbId = "tt0068646", Title = "The Godfather", Rating = 9.2m, Director = "Francis Ford Coppola", ReleaseDate = new DateTime(1972,3,24), TagLine = "An offer you can't refuse.", Genres = new List<string> {"Crime","Drama", "Thriller"}, }, new Movie { ImdbId = "tt1375666", Title = "Inception", Rating = 9.2m, Director = "Christopher Nolan", ReleaseDate = new DateTime(2010,7,16), TagLine = "Your mind is the scene of the crime", Genres = new List<string>{"Action", "Mystery", "Sci-Fi", "Thriller"}, }, new Movie { ImdbId = "tt0071562", Title = "The Godfather: Part II", Rating = 9.0m, Director = "Francis Ford Coppola", ReleaseDate = new DateTime(1974,12,20), Genres = new List<string> {"Crime","Drama", "Thriller"}, }, new Movie { ImdbId = "tt0060196", Title = "The Good, the Bad and the Ugly", Rating = 9.0m, Director = "Sergio Leone", ReleaseDate = new DateTime(1967,12,29), TagLine = "They formed an alliance of hate to steal a fortune in dead man's gold", Genres = new List<string>{"Adventure","Western"}, }, }; public IDbConnectionFactory DbFactory { get; set; } public override object OnPost(ResetMovies request) { DbFactory.Run(db => { const bool overwriteTable = true; db.CreateTable<Movie>(overwriteTable); db.SaveAll(Top5Movies); }); return new ResetMoviesResponse(); } } [DataContract] public class GetHttpResult { } [DataContract] public class GetHttpResultResponse { [DataMember] public string Result { get; set; } } public class HttpResultService : IService<GetHttpResult> { public object Execute(GetHttpResult request) { var getHttpResultResponse = new GetHttpResultResponse { Result = "result" }; return new HttpResult(getHttpResultResponse); } } [Route("inbox/{Id}/responses", "GET, PUT, OPTIONS")] public class InboxPostResponseRequest { public int Id { get; set; } public List<PageElementResponseDTO> Responses { get; set; } } public class InboxPostResponseRequestResponse { public int Id { get; set; } public List<PageElementResponseDTO> Responses { get; set; } } public class PageElementResponseDTO { public int PageElementId { get; set; } public string PageElementType { get; set; } public string PageElementResponse { get; set; } } public class InboxPostResponseRequestService : ServiceBase<InboxPostResponseRequest> { protected override object Run(InboxPostResponseRequest request) { if (request.Responses == null || request.Responses.Count == 0) { throw new ArgumentNullException("Responses"); } return new InboxPostResponseRequestResponse { Id = request.Id, Responses = request.Responses }; } } [Route("inbox/{Id}/responses", "GET, PUT, OPTIONS")] public class InboxPost { public bool Throw { get; set; } public int Id { get; set; } } public class InboxPostService : ServiceBase<InboxPost> { protected override object Run(InboxPost request) { if (request.Throw) throw new ArgumentNullException("Throw"); return null; } } [DataContract] [Route("/long_running")] public class LongRunning { } public class LongRunningService : ServiceBase<LongRunning> { protected override object Run(LongRunning request) { Thread.Sleep(5000); return "LongRunning done."; } } public class ExampleAppHostHttpListener : AppHostHttpListenerBase { //private static ILog log; public ExampleAppHostHttpListener() : base("ServiceStack Examples", typeof(GetFactorialService).Assembly) { LogManager.LogFactory = new DebugLogFactory(); //log = LogManager.GetLogger(typeof(ExampleAppHostHttpListener)); } public Action<Container> ConfigureFilter { get; set; } public override void Configure(Container container) { EndpointHostConfig.Instance.GlobalResponseHeaders.Clear(); //Signal advanced web browsers what HTTP Methods you accept base.SetConfig(new EndpointHostConfig { GlobalResponseHeaders = { { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }, }, WsdlServiceNamespace = "http://www.servicestack.net/types", LogFactory = new ConsoleLogFactory(), DebugMode = true, }); this.RegisterRequestBinder<CustomRequestBinder>( httpReq => new CustomRequestBinder { IsFromBinder = true }); Routes .Add<Movies>("/custom-movies", "GET") .Add<Movies>("/custom-movies/genres/{Genre}") .Add<Movie>("/custom-movies", "POST,PUT") .Add<Movie>("/custom-movies/{Id}") .Add<GetFactorial>("/fact/{ForNumber}") .Add<MoviesZip>("/movies.zip") .Add<GetHttpResult>("/gethttpresult") ; container.Register<IResourceManager>(new ConfigurationResourceManager()); //var appSettings = container.Resolve<IResourceManager>(); container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>())); //var appConfig = container.Resolve<ExampleConfig>(); container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory( ":memory:", false, SqliteOrmLiteDialectProvider.Instance)); var resetMovies = container.Resolve<ResetMoviesService>(); resetMovies.Post(null); //var movies = container.Resolve<IDbConnectionFactory>().Exec(x => x.Select<Movie>()); //Console.WriteLine(movies.Dump()); if (ConfigureFilter != null) { ConfigureFilter(container); } Plugins.Add(new ProtoBufFormat()); } } public class ExampleAppHostHttpListenerLongRunning : AppHostHttpListenerLongRunningBase { //private static ILog log; public ExampleAppHostHttpListenerLongRunning() : base("ServiceStack Examples", 500, typeof(GetFactorialService).Assembly) { LogManager.LogFactory = new DebugLogFactory(); //log = LogManager.GetLogger(typeof(ExampleAppHostHttpListener)); } public Action<Container> ConfigureFilter { get; set; } public override void Configure(Container container) { EndpointHostConfig.Instance.GlobalResponseHeaders.Clear(); //Signal advanced web browsers what HTTP Methods you accept base.SetConfig(new EndpointHostConfig { GlobalResponseHeaders = { { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }, }, WsdlServiceNamespace = "http://www.servicestack.net/types", LogFactory = new ConsoleLogFactory(), DebugMode = true, }); this.RegisterRequestBinder<CustomRequestBinder>( httpReq => new CustomRequestBinder { IsFromBinder = true }); Routes .Add<Movies>("/custom-movies", "GET") .Add<Movies>("/custom-movies/genres/{Genre}") .Add<Movie>("/custom-movies", "POST,PUT") .Add<Movie>("/custom-movies/{Id}") .Add<GetFactorial>("/fact/{ForNumber}") .Add<MoviesZip>("/movies.zip") .Add<GetHttpResult>("/gethttpresult") ; container.Register<IResourceManager>(new ConfigurationResourceManager()); //var appSettings = container.Resolve<IResourceManager>(); container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>())); //var appConfig = container.Resolve<ExampleConfig>(); container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory( ":memory:", false, SqliteOrmLiteDialectProvider.Instance)); var resetMovies = container.Resolve<ResetMoviesService>(); resetMovies.Post(null); //var movies = container.Resolve<IDbConnectionFactory>().Exec(x => x.Select<Movie>()); //Console.WriteLine(movies.Dump()); if (ConfigureFilter != null) { ConfigureFilter(container); } } } }
//----------------------------------------------------------------------- // <copyright file="NFCProperty.cs"> // Copyright (C) 2015-2015 lvsheng.huang <https://github.com/ketoo/NFrame> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; namespace NFrame { public class NFCProperty : NFIProperty { public NFCProperty( NFGUID self, string strPropertyName, NFIDataList varData) { mSelf = self; msPropertyName = strPropertyName; mxData = new NFIDataList.TData(varData.GetType(0)); switch (varData.GetType(0)) { case NFIDataList.VARIANT_TYPE.VTYPE_INT: mxData.Set(varData.IntVal(0)); break; case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT: mxData.Set(varData.FloatVal(0)); break; case NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE: mxData.Set(varData.DoubleVal(0)); break; case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT: mxData.Set(varData.ObjectVal(0)); break; case NFIDataList.VARIANT_TYPE.VTYPE_STRING: mxData.Set(varData.StringVal(0)); break; default: break; } } public NFCProperty(NFGUID self, string strPropertyName, NFIDataList.TData varData) { mSelf = self; msPropertyName = strPropertyName; mxData = new NFIDataList.TData(varData); } public override string GetKey() { return msPropertyName; } public override NFIDataList.VARIANT_TYPE GetType() { return mxData.GetType(); } public override NFIDataList.TData GetData() { return mxData; } public override Int64 QueryInt() { if (NFIDataList.VARIANT_TYPE.VTYPE_INT == mxData.GetType()) { return mxData.IntVal(); } return NFIDataList.NULL_INT; } public override float QueryFloat() { if (NFIDataList.VARIANT_TYPE.VTYPE_FLOAT == mxData.GetType()) { return (float)mxData.DoubleVal(); } return (float)NFIDataList.EPS_DOUBLE; } public override double QueryDouble() { if (NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE == mxData.GetType()) { return mxData.DoubleVal(); } return NFIDataList.EPS_DOUBLE; } public override string QueryString() { if (NFIDataList.VARIANT_TYPE.VTYPE_STRING == mxData.GetType()) { return mxData.StringVal(); } return NFIDataList.NULL_STRING; } public override NFGUID QueryObject() { if (NFIDataList.VARIANT_TYPE.VTYPE_INT == mxData.GetType()) { return (NFGUID)mxData.ObjectVal(); } return NFIDataList.NULL_OBJECT; } public override bool SetInt(Int64 value) { if (mxData.IntVal() != value) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_INT); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetFloat(float value) { if (mxData.DoubleVal() - value > NFIDataList.EPS_DOUBLE || mxData.DoubleVal() - value < -NFIDataList.EPS_DOUBLE) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_FLOAT); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetDouble(double value) { if (mxData.DoubleVal() - value > NFIDataList.EPS_DOUBLE || mxData.DoubleVal() - value < -NFIDataList.EPS_DOUBLE) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetString(string value) { if (mxData.StringVal() != value) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_STRING); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetObject(NFGUID value) { if (mxData.ObjectVal() != value) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_OBJECT); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetData(NFIDataList.TData x) { if (NFIDataList.VARIANT_TYPE.VTYPE_UNKNOWN == mxData.GetType() || x.GetType() == mxData.GetType()) { switch (mxData.GetType()) { case NFIDataList.VARIANT_TYPE.VTYPE_INT: SetInt(x.IntVal()); break; case NFIDataList.VARIANT_TYPE.VTYPE_STRING: SetString(x.StringVal()); break; case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT: SetFloat((float)x.DoubleVal()); break; case NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE: SetDouble(x.DoubleVal()); break; case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT: SetObject(x.ObjectVal()); break; default: break; } return true; } return false; } public override void RegisterCallback(PropertyEventHandler handler) { doHandleDel += handler; } PropertyEventHandler doHandleDel; NFGUID mSelf; string msPropertyName; NFIDataList.TData mxData; } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Graph.RBAC.Version1_6 { using Microsoft.Azure; using Microsoft.Azure.Graph; using Microsoft.Azure.Graph.RBAC; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ApplicationsOperations operations. /// </summary> public partial interface IApplicationsOperations { /// <summary> /// Create a new application. /// </summary> /// <param name='parameters'> /// The parameters for creating an application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Application>> CreateWithHttpMessagesAsync(ApplicationCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists applications by filter parameters. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Application>>> ListWithHttpMessagesAsync(ODataQuery<Application> odataQuery = default(ODataQuery<Application>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an application by object ID. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Application>> GetWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update an existing application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update an existing application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PatchWithHttpMessagesAsync(string applicationObjectId, ApplicationUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the keyCredentials associated with an application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<KeyCredential>>> ListKeyCredentialsWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update the keyCredentials associated with an application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update the keyCredentials of an existing application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> UpdateKeyCredentialsWithHttpMessagesAsync(string applicationObjectId, KeyCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the passwordCredentials associated with an application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<PasswordCredential>>> ListPasswordCredentialsWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update passwordCredentials associated with an application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update passwordCredentials of an existing /// application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> UpdatePasswordCredentialsWithHttpMessagesAsync(string applicationObjectId, PasswordCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of applications from the current tenant. /// </summary> /// <param name='nextLink'> /// Next link for the list operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Application>>> ListNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// // 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.Threading; using System.Threading.Tasks; using Microsoft.Azure.Subscriptions; using Microsoft.Azure.Subscriptions.Models; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Subscriptions { /// <summary> /// Operations for managing subscriptions. /// </summary> internal partial class SubscriptionOperations : IServiceOperations<SubscriptionClient>, ISubscriptionOperations { /// <summary> /// Initializes a new instance of the SubscriptionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SubscriptionOperations(SubscriptionClient client) { this._client = client; } private SubscriptionClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Subscriptions.SubscriptionClient. /// </summary> public SubscriptionClient Client { get { return this._client; } } /// <summary> /// Gets details about particular subscription. /// </summary> /// <param name='subscriptionId'> /// Required. Id of the subscription. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Subscription detailed information. /// </returns> public async Task<GetSubscriptionResult> GetAsync(string subscriptionId, CancellationToken cancellationToken) { // Validate if (subscriptionId == null) { throw new ArgumentNullException("subscriptionId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + subscriptionId.Trim() + "?"; url = url + "api-version=2014-04-01-preview"; 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) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result GetSubscriptionResult result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GetSubscriptionResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Subscription subscriptionInstance = new Subscription(); result.Subscription = subscriptionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionInstance.Id = idInstance; } JToken subscriptionIdValue = responseDoc["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionInstance.SubscriptionId = subscriptionIdInstance; } JToken displayNameValue = responseDoc["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionInstance.DisplayName = displayNameInstance; } JToken stateValue = responseDoc["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); subscriptionInstance.State = stateInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a list of the subscriptionIds. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Subscription list operation response. /// </returns> public async Task<SubscriptionListResult> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/subscriptions?"; url = url + "api-version=2014-04-01-preview"; 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) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result SubscriptionListResult result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionListResult(); 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)) { Subscription subscriptionInstance = new Subscription(); result.Subscriptions.Add(subscriptionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionInstance.Id = idInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionInstance.SubscriptionId = subscriptionIdInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionInstance.DisplayName = displayNameInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); subscriptionInstance.State = stateInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// // ExtensionMethods.cs // // Author: // Zachary Gramana <[email protected]> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET 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. // // // Copyright (c) 2014 Couchbase, 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; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Http.Headers; using Sharpen; using System.Threading.Tasks; namespace Couchbase.Lite { internal delegate bool TryParseDelegate<T>(string s, out T value); internal static class ExtensionMethods { public static IEnumerable<byte> Decompress(this IEnumerable<byte> compressedData) { using (var ms = new MemoryStream(compressedData.ToArray())) using (var gs = new GZipStream(ms, CompressionMode.Decompress, false)) { return gs.ReadAllBytes(); } } public static IEnumerable<byte> Compress(this IEnumerable<byte> data) { var array = data.ToArray(); using (var ms = new MemoryStream()) using (var gs = new GZipStream(ms, CompressionMode.Compress, false)) { gs.Write(array, 0, array.Length); return ms.ToArray(); } } public static bool TryGetValue<T>(this IDictionary<string, object> dic, string key, out T value) { value = default(T); object obj; if (!dic.TryGetValue(key, out obj)) { return false; } //If the types already match then things are easy if ((obj is T)) { value = (T)obj; return true; } try { //Take the slow route for things like boxed value types value = (T)Convert.ChangeType(value, typeof(T)); return true; } catch(Exception) { return false; } } public static bool TryCast<T>(object obj, out T castVal) { //If the types already match then things are easy if (obj is T) { castVal = (T)obj; return true; } try { //Take the slow route for things like boxed value types castVal = (T)Convert.ChangeType(obj, typeof(T)); } catch(Exception) { castVal = default(T); return false; } return true; } public static T CastOrDefault<T>(object obj, T defaultVal) { T retVal; if (obj != null && TryCast<T>(obj, out retVal)) { return retVal; } return defaultVal; } public static T CastOrDefault<T>(object obj) { return CastOrDefault<T>(obj, default(T)); } public static T GetCast<T>(this IDictionary<string, object> collection, string key) { return collection.GetCast(key, default(T)); } public static T GetCast<T>(this IDictionary<string, object> collection, string key, T defaultVal) { object value = collection.Get(key); return CastOrDefault<T>(value, defaultVal); } public static T? GetNullable<T>(this IDictionary<string, object> collection, string key) where T : struct { object value = collection.Get(key); return CastOrDefault<T>(value); } public static IEnumerable<T> AsSafeEnumerable<T>(this IEnumerable<T> source) { var e = ((IEnumerable)source).GetEnumerator(); using (e as IDisposable) { while (e.MoveNext()) { yield return (T)e.Current; } } } internal static IDictionary<TKey,TValue> AsDictionary<TKey, TValue>(this object attachmentProps) { return Manager.GetObjectMapper().ConvertToDictionary<TKey, TValue>(attachmentProps); } internal static IList<TValue> AsList<TValue>(this object value) { return Manager.GetObjectMapper().ConvertToList<TValue>(value); } public static IEnumerable ToEnumerable(this IEnumerator enumerator) { while(enumerator.MoveNext()) { yield return enumerator.Current; } } public static String Fmt(this String str, params Object[] vals) { return String.Format(str, vals); } public static Byte[] ReadAllBytes(this Stream stream) { var chunkBuffer = new byte[Attachment.DefaultStreamChunkSize]; // We know we'll be reading at least 1 chunk, so pre-allocate now to avoid an immediate resize. var blob = new List<Byte> (Attachment.DefaultStreamChunkSize); int bytesRead; do { chunkBuffer.Initialize (); // Resets all values back to zero. bytesRead = stream.Read(chunkBuffer, 0, Attachment.DefaultStreamChunkSize); blob.AddRange (chunkBuffer.Take (bytesRead)); } while (bytesRead > 0); return blob.ToArray(); } public static StatusCode GetStatusCode(this HttpStatusCode code) { var validVals = Enum.GetValues(typeof(StatusCode)); foreach (StatusCode validVal in validVals) { if ((Int32)code == (Int32)validVal) { return validVal; } } return StatusCode.Unknown; } public static AuthenticationHeaderValue GetAuthenticationHeader(this Uri uri, string scheme) { Debug.Assert(uri != null); var unescapedUserInfo = uri.UserEscaped ? Uri.UnescapeDataString(uri.UserInfo) : uri.UserInfo; var param = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(unescapedUserInfo)); return new AuthenticationHeaderValue(scheme, param); } public static AuthenticationHeaderValue AsAuthenticationHeader(this string userinfo, string scheme) { Debug.Assert(userinfo != null); return new AuthenticationHeaderValue(scheme, userinfo); } public static string ToQueryString(this IDictionary<string, object> parameters) { var maps = parameters.Select(kvp => { var key = Uri.EscapeUriString(kvp.Key); string value; if (kvp.Value is string) { value = Uri.EscapeUriString(kvp.Value as String); } else if (kvp.Value is ICollection) { value = Uri.EscapeUriString(Manager.GetObjectMapper().WriteValueAsString(kvp.Value)); } else { value = Uri.EscapeUriString(kvp.Value.ToString()); } return String.Format("{0}={1}", key, value); }); return String.Join("&", maps.ToArray()); } #if NET_3_5 public static IEnumerable<FileInfo> EnumerateFiles(this DirectoryInfo info, string searchPattern, SearchOption option) { foreach (var file in info.GetFiles(searchPattern, option)) { yield return file; } } public static IEnumerable<FileInfo> EnumerateFiles(this DirectoryInfo info) { foreach (var file in info.GetFiles()) { yield return file; } } public static Task<HttpListenerContext> GetContextAsync(this HttpListener listener) { return Task.Factory.FromAsync<HttpListenerContext>(listener.BeginGetContext, listener.EndGetContext, null); } #endif private static bool IsNumeric<T>() { Type type = typeof(T); return IsNumeric(type); } private static bool IsNumeric(Type type) { switch (Type.GetTypeCode(type)) { case TypeCode.Byte: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; case TypeCode.Object: if ( type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return IsNumeric(Nullable.GetUnderlyingType(type)); } return false; } return false; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// The Microsoft Azure Network management API provides a RESTful set of /// web services that interact with Microsoft Azure Networks service to /// manage your network resrources. The API has entities that capture the /// relationship between an end user and the Microsoft Azure Networks /// service. /// </summary> public partial class NetworkManagementClient : ServiceClient<NetworkManagementClient>, INetworkManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IApplicationGatewaysOperations. /// </summary> public virtual IApplicationGatewaysOperations ApplicationGateways { get; private set; } /// <summary> /// Gets the IExpressRouteCircuitAuthorizationsOperations. /// </summary> public virtual IExpressRouteCircuitAuthorizationsOperations ExpressRouteCircuitAuthorizations { get; private set; } /// <summary> /// Gets the IExpressRouteCircuitPeeringsOperations. /// </summary> public virtual IExpressRouteCircuitPeeringsOperations ExpressRouteCircuitPeerings { get; private set; } /// <summary> /// Gets the IExpressRouteCircuitsOperations. /// </summary> public virtual IExpressRouteCircuitsOperations ExpressRouteCircuits { get; private set; } /// <summary> /// Gets the IExpressRouteServiceProvidersOperations. /// </summary> public virtual IExpressRouteServiceProvidersOperations ExpressRouteServiceProviders { get; private set; } /// <summary> /// Gets the ILoadBalancersOperations. /// </summary> public virtual ILoadBalancersOperations LoadBalancers { get; private set; } /// <summary> /// Gets the ILocalNetworkGatewaysOperations. /// </summary> public virtual ILocalNetworkGatewaysOperations LocalNetworkGateways { get; private set; } /// <summary> /// Gets the INetworkInterfacesOperations. /// </summary> public virtual INetworkInterfacesOperations NetworkInterfaces { get; private set; } /// <summary> /// Gets the INetworkSecurityGroupsOperations. /// </summary> public virtual INetworkSecurityGroupsOperations NetworkSecurityGroups { get; private set; } /// <summary> /// Gets the IPublicIPAddressesOperations. /// </summary> public virtual IPublicIPAddressesOperations PublicIPAddresses { get; private set; } /// <summary> /// Gets the IRouteTablesOperations. /// </summary> public virtual IRouteTablesOperations RouteTables { get; private set; } /// <summary> /// Gets the IRoutesOperations. /// </summary> public virtual IRoutesOperations Routes { get; private set; } /// <summary> /// Gets the ISecurityRulesOperations. /// </summary> public virtual ISecurityRulesOperations SecurityRules { get; private set; } /// <summary> /// Gets the ISubnetsOperations. /// </summary> public virtual ISubnetsOperations Subnets { get; private set; } /// <summary> /// Gets the IVirtualNetworkPeeringsOperations. /// </summary> public virtual IVirtualNetworkPeeringsOperations VirtualNetworkPeerings { get; private set; } /// <summary> /// Gets the IUsagesOperations. /// </summary> public virtual IUsagesOperations Usages { get; private set; } /// <summary> /// Gets the IVirtualNetworkGatewayConnectionsOperations. /// </summary> public virtual IVirtualNetworkGatewayConnectionsOperations VirtualNetworkGatewayConnections { get; private set; } /// <summary> /// Gets the IVirtualNetworkGatewaysOperations. /// </summary> public virtual IVirtualNetworkGatewaysOperations VirtualNetworkGateways { get; private set; } /// <summary> /// Gets the IVirtualNetworksOperations. /// </summary> public virtual IVirtualNetworksOperations VirtualNetworks { get; private set; } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected NetworkManagementClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected NetworkManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected NetworkManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected NetworkManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public NetworkManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public NetworkManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public NetworkManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public NetworkManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.ApplicationGateways = new ApplicationGatewaysOperations(this); this.ExpressRouteCircuitAuthorizations = new ExpressRouteCircuitAuthorizationsOperations(this); this.ExpressRouteCircuitPeerings = new ExpressRouteCircuitPeeringsOperations(this); this.ExpressRouteCircuits = new ExpressRouteCircuitsOperations(this); this.ExpressRouteServiceProviders = new ExpressRouteServiceProvidersOperations(this); this.LoadBalancers = new LoadBalancersOperations(this); this.LocalNetworkGateways = new LocalNetworkGatewaysOperations(this); this.NetworkInterfaces = new NetworkInterfacesOperations(this); this.NetworkSecurityGroups = new NetworkSecurityGroupsOperations(this); this.PublicIPAddresses = new PublicIPAddressesOperations(this); this.RouteTables = new RouteTablesOperations(this); this.Routes = new RoutesOperations(this); this.SecurityRules = new SecurityRulesOperations(this); this.Subnets = new SubnetsOperations(this); this.VirtualNetworkPeerings = new VirtualNetworkPeeringsOperations(this); this.Usages = new UsagesOperations(this); this.VirtualNetworkGatewayConnections = new VirtualNetworkGatewayConnectionsOperations(this); this.VirtualNetworkGateways = new VirtualNetworkGatewaysOperations(this); this.VirtualNetworks = new VirtualNetworksOperations(this); this.BaseUri = new Uri("https://management.azure.com"); this.ApiVersion = "2016-06-01"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Checks whether a domain name in the cloudapp.net zone is available for use. /// </summary> /// <param name='location'> /// The location of the domain name /// </param> /// <param name='domainNameLabel'> /// The domain name to be verified. It must conform to the following regular /// expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DnsNameAvailabilityResult>> CheckDnsNameAvailabilityWithHttpMessagesAsync(string location, string domainNameLabel = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (this.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion"); } if (this.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("domainNameLabel", domainNameLabel); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckDnsNameAvailability", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability").ToString(); _url = _url.Replace("{location}", Uri.EscapeDataString(location)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (domainNameLabel != null) { _queryParameters.Add(string.Format("domainNameLabel={0}", Uri.EscapeDataString(domainNameLabel))); } if (this.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DnsNameAvailabilityResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DnsNameAvailabilityResult>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A preschool. /// </summary> public class Preschool_Core : TypeCore, IEducationalOrganization { public Preschool_Core() { this._TypeId = 214; this._Id = "Preschool"; this._Schema_Org_Url = "http://schema.org/Preschool"; string label = ""; GetLabel(out label, "Preschool", typeof(Preschool_Core)); this._Label = label; this._Ancestors = new int[]{266,193,88}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{88}; this._Properties = new int[]{67,108,143,229,5,10,47,75,77,85,91,94,95,115,130,137,199,196,13}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// Alumni of educational organization. /// </summary> private Alumni_Core alumni; public Alumni_Core Alumni { get { return alumni; } set { alumni = value; SetPropertyInstance(alumni); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using gagr = Google.Api.Gax.ResourceNames; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Dataproc.V1 { /// <summary>Settings for <see cref="BatchControllerClient"/> instances.</summary> public sealed partial class BatchControllerSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="BatchControllerSettings"/>.</summary> /// <returns>A new instance of the default <see cref="BatchControllerSettings"/>.</returns> public static BatchControllerSettings GetDefault() => new BatchControllerSettings(); /// <summary>Constructs a new <see cref="BatchControllerSettings"/> object with default settings.</summary> public BatchControllerSettings() { } private BatchControllerSettings(BatchControllerSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); CreateBatchSettings = existing.CreateBatchSettings; CreateBatchOperationsSettings = existing.CreateBatchOperationsSettings.Clone(); GetBatchSettings = existing.GetBatchSettings; ListBatchesSettings = existing.ListBatchesSettings; DeleteBatchSettings = existing.DeleteBatchSettings; OnCopy(existing); } partial void OnCopy(BatchControllerSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BatchControllerClient.CreateBatch</c> and <c>BatchControllerClient.CreateBatchAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateBatchSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// Long Running Operation settings for calls to <c>BatchControllerClient.CreateBatch</c> and /// <c>BatchControllerClient.CreateBatchAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings CreateBatchOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BatchControllerClient.GetBatch</c> and <c>BatchControllerClient.GetBatchAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetBatchSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BatchControllerClient.ListBatches</c> and <c>BatchControllerClient.ListBatchesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListBatchesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BatchControllerClient.DeleteBatch</c> and <c>BatchControllerClient.DeleteBatchAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteBatchSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="BatchControllerSettings"/> object.</returns> public BatchControllerSettings Clone() => new BatchControllerSettings(this); } /// <summary> /// Builder class for <see cref="BatchControllerClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> public sealed partial class BatchControllerClientBuilder : gaxgrpc::ClientBuilderBase<BatchControllerClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public BatchControllerSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public BatchControllerClientBuilder() { UseJwtAccessWithScopes = BatchControllerClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref BatchControllerClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<BatchControllerClient> task); /// <summary>Builds the resulting client.</summary> public override BatchControllerClient Build() { BatchControllerClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<BatchControllerClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<BatchControllerClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private BatchControllerClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return BatchControllerClient.Create(callInvoker, Settings); } private async stt::Task<BatchControllerClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return BatchControllerClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => BatchControllerClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => BatchControllerClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => BatchControllerClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>BatchController client wrapper, for convenient use.</summary> /// <remarks> /// The BatchController provides methods to manage batch workloads. /// </remarks> public abstract partial class BatchControllerClient { /// <summary> /// The default endpoint for the BatchController service, which is a host of "dataproc.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "dataproc.googleapis.com:443"; /// <summary>The default BatchController scopes.</summary> /// <remarks> /// The default BatchController scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="BatchControllerClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="BatchControllerClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="BatchControllerClient"/>.</returns> public static stt::Task<BatchControllerClient> CreateAsync(st::CancellationToken cancellationToken = default) => new BatchControllerClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="BatchControllerClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="BatchControllerClientBuilder"/>. /// </summary> /// <returns>The created <see cref="BatchControllerClient"/>.</returns> public static BatchControllerClient Create() => new BatchControllerClientBuilder().Build(); /// <summary> /// Creates a <see cref="BatchControllerClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="BatchControllerSettings"/>.</param> /// <returns>The created <see cref="BatchControllerClient"/>.</returns> internal static BatchControllerClient Create(grpccore::CallInvoker callInvoker, BatchControllerSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } BatchController.BatchControllerClient grpcClient = new BatchController.BatchControllerClient(callInvoker); return new BatchControllerClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC BatchController client</summary> public virtual BatchController.BatchControllerClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Batch, BatchOperationMetadata> CreateBatch(CreateBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(CreateBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(CreateBatchRequest request, st::CancellationToken cancellationToken) => CreateBatchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>CreateBatch</c>.</summary> public virtual lro::OperationsClient CreateBatchOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>CreateBatch</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<Batch, BatchOperationMetadata> PollOnceCreateBatch(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Batch, BatchOperationMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateBatchOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>CreateBatch</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> PollOnceCreateBatchAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Batch, BatchOperationMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateBatchOperationsClient, callSettings); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Batch, BatchOperationMetadata> CreateBatch(string parent, Batch batch, string batchId, gaxgrpc::CallSettings callSettings = null) => CreateBatch(new CreateBatchRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), Batch = gax::GaxPreconditions.CheckNotNull(batch, nameof(batch)), BatchId = batchId ?? "", }, callSettings); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(string parent, Batch batch, string batchId, gaxgrpc::CallSettings callSettings = null) => CreateBatchAsync(new CreateBatchRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), Batch = gax::GaxPreconditions.CheckNotNull(batch, nameof(batch)), BatchId = batchId ?? "", }, callSettings); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(string parent, Batch batch, string batchId, st::CancellationToken cancellationToken) => CreateBatchAsync(parent, batch, batchId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Batch, BatchOperationMetadata> CreateBatch(gagr::LocationName parent, Batch batch, string batchId, gaxgrpc::CallSettings callSettings = null) => CreateBatch(new CreateBatchRequest { ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), Batch = gax::GaxPreconditions.CheckNotNull(batch, nameof(batch)), BatchId = batchId ?? "", }, callSettings); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(gagr::LocationName parent, Batch batch, string batchId, gaxgrpc::CallSettings callSettings = null) => CreateBatchAsync(new CreateBatchRequest { ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), Batch = gax::GaxPreconditions.CheckNotNull(batch, nameof(batch)), BatchId = batchId ?? "", }, callSettings); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(gagr::LocationName parent, Batch batch, string batchId, st::CancellationToken cancellationToken) => CreateBatchAsync(parent, batch, batchId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Batch GetBatch(GetBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(GetBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(GetBatchRequest request, st::CancellationToken cancellationToken) => GetBatchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Batch GetBatch(string name, gaxgrpc::CallSettings callSettings = null) => GetBatch(new GetBatchRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(string name, gaxgrpc::CallSettings callSettings = null) => GetBatchAsync(new GetBatchRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(string name, st::CancellationToken cancellationToken) => GetBatchAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Batch GetBatch(BatchName name, gaxgrpc::CallSettings callSettings = null) => GetBatch(new GetBatchRequest { BatchName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(BatchName name, gaxgrpc::CallSettings callSettings = null) => GetBatchAsync(new GetBatchRequest { BatchName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(BatchName name, st::CancellationToken cancellationToken) => GetBatchAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedEnumerable<ListBatchesResponse, Batch> ListBatches(ListBatchesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListBatchesResponse, Batch> ListBatchesAsync(ListBatchesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="parent"> /// Required. The parent, which owns this collection of batches. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedEnumerable<ListBatchesResponse, Batch> ListBatches(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListBatches(new ListBatchesRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="parent"> /// Required. The parent, which owns this collection of batches. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListBatchesResponse, Batch> ListBatchesAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListBatchesAsync(new ListBatchesRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="parent"> /// Required. The parent, which owns this collection of batches. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedEnumerable<ListBatchesResponse, Batch> ListBatches(gagr::LocationName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListBatches(new ListBatchesRequest { ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="parent"> /// Required. The parent, which owns this collection of batches. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListBatchesResponse, Batch> ListBatchesAsync(gagr::LocationName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListBatchesAsync(new ListBatchesRequest { ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteBatch(DeleteBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(DeleteBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(DeleteBatchRequest request, st::CancellationToken cancellationToken) => DeleteBatchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteBatch(string name, gaxgrpc::CallSettings callSettings = null) => DeleteBatch(new DeleteBatchRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(string name, gaxgrpc::CallSettings callSettings = null) => DeleteBatchAsync(new DeleteBatchRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(string name, st::CancellationToken cancellationToken) => DeleteBatchAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteBatch(BatchName name, gaxgrpc::CallSettings callSettings = null) => DeleteBatch(new DeleteBatchRequest { BatchName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(BatchName name, gaxgrpc::CallSettings callSettings = null) => DeleteBatchAsync(new DeleteBatchRequest { BatchName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(BatchName name, st::CancellationToken cancellationToken) => DeleteBatchAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>BatchController client wrapper implementation, for convenient use.</summary> /// <remarks> /// The BatchController provides methods to manage batch workloads. /// </remarks> public sealed partial class BatchControllerClientImpl : BatchControllerClient { private readonly gaxgrpc::ApiCall<CreateBatchRequest, lro::Operation> _callCreateBatch; private readonly gaxgrpc::ApiCall<GetBatchRequest, Batch> _callGetBatch; private readonly gaxgrpc::ApiCall<ListBatchesRequest, ListBatchesResponse> _callListBatches; private readonly gaxgrpc::ApiCall<DeleteBatchRequest, wkt::Empty> _callDeleteBatch; /// <summary> /// Constructs a client wrapper for the BatchController service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="BatchControllerSettings"/> used within this client.</param> public BatchControllerClientImpl(BatchController.BatchControllerClient grpcClient, BatchControllerSettings settings) { GrpcClient = grpcClient; BatchControllerSettings effectiveSettings = settings ?? BatchControllerSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); CreateBatchOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.CreateBatchOperationsSettings); _callCreateBatch = clientHelper.BuildApiCall<CreateBatchRequest, lro::Operation>(grpcClient.CreateBatchAsync, grpcClient.CreateBatch, effectiveSettings.CreateBatchSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callCreateBatch); Modify_CreateBatchApiCall(ref _callCreateBatch); _callGetBatch = clientHelper.BuildApiCall<GetBatchRequest, Batch>(grpcClient.GetBatchAsync, grpcClient.GetBatch, effectiveSettings.GetBatchSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callGetBatch); Modify_GetBatchApiCall(ref _callGetBatch); _callListBatches = clientHelper.BuildApiCall<ListBatchesRequest, ListBatchesResponse>(grpcClient.ListBatchesAsync, grpcClient.ListBatches, effectiveSettings.ListBatchesSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callListBatches); Modify_ListBatchesApiCall(ref _callListBatches); _callDeleteBatch = clientHelper.BuildApiCall<DeleteBatchRequest, wkt::Empty>(grpcClient.DeleteBatchAsync, grpcClient.DeleteBatch, effectiveSettings.DeleteBatchSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callDeleteBatch); Modify_DeleteBatchApiCall(ref _callDeleteBatch); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_CreateBatchApiCall(ref gaxgrpc::ApiCall<CreateBatchRequest, lro::Operation> call); partial void Modify_GetBatchApiCall(ref gaxgrpc::ApiCall<GetBatchRequest, Batch> call); partial void Modify_ListBatchesApiCall(ref gaxgrpc::ApiCall<ListBatchesRequest, ListBatchesResponse> call); partial void Modify_DeleteBatchApiCall(ref gaxgrpc::ApiCall<DeleteBatchRequest, wkt::Empty> call); partial void OnConstruction(BatchController.BatchControllerClient grpcClient, BatchControllerSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC BatchController client</summary> public override BatchController.BatchControllerClient GrpcClient { get; } partial void Modify_CreateBatchRequest(ref CreateBatchRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetBatchRequest(ref GetBatchRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListBatchesRequest(ref ListBatchesRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteBatchRequest(ref DeleteBatchRequest request, ref gaxgrpc::CallSettings settings); /// <summary>The long-running operations client for <c>CreateBatch</c>.</summary> public override lro::OperationsClient CreateBatchOperationsClient { get; } /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<Batch, BatchOperationMetadata> CreateBatch(CreateBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateBatchRequest(ref request, ref callSettings); return new lro::Operation<Batch, BatchOperationMetadata>(_callCreateBatch.Sync(request, callSettings), CreateBatchOperationsClient); } /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(CreateBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateBatchRequest(ref request, ref callSettings); return new lro::Operation<Batch, BatchOperationMetadata>(await _callCreateBatch.Async(request, callSettings).ConfigureAwait(false), CreateBatchOperationsClient); } /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override Batch GetBatch(GetBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetBatchRequest(ref request, ref callSettings); return _callGetBatch.Sync(request, callSettings); } /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<Batch> GetBatchAsync(GetBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetBatchRequest(ref request, ref callSettings); return _callGetBatch.Async(request, callSettings); } /// <summary> /// Lists batch workloads. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Batch"/> resources.</returns> public override gax::PagedEnumerable<ListBatchesResponse, Batch> ListBatches(ListBatchesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListBatchesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListBatchesRequest, ListBatchesResponse, Batch>(_callListBatches, request, callSettings); } /// <summary> /// Lists batch workloads. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Batch"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListBatchesResponse, Batch> ListBatchesAsync(ListBatchesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListBatchesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListBatchesRequest, ListBatchesResponse, Batch>(_callListBatches, request, callSettings); } /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override void DeleteBatch(DeleteBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteBatchRequest(ref request, ref callSettings); _callDeleteBatch.Sync(request, callSettings); } /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task DeleteBatchAsync(DeleteBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteBatchRequest(ref request, ref callSettings); return _callDeleteBatch.Async(request, callSettings); } } public partial class ListBatchesRequest : gaxgrpc::IPageRequest { } public partial class ListBatchesResponse : gaxgrpc::IPageResponse<Batch> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Batch> GetEnumerator() => Batches.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public static partial class BatchController { public partial class BatchControllerClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker); } } }