context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using BTCPayServer.Abstractions.Extensions; using BTCPayServer.Controllers; using BTCPayServer.Data; using BTCPayServer.Events; using BTCPayServer.HostedServices; using BTCPayServer.Logging; using BTCPayServer.Services.PaymentRequests; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Logging; using PaymentRequestData = BTCPayServer.Client.Models.PaymentRequestData; namespace BTCPayServer.PaymentRequest { public class PaymentRequestHub : Hub { private readonly UIPaymentRequestController _PaymentRequestController; public const string InvoiceCreated = "InvoiceCreated"; public const string PaymentReceived = "PaymentReceived"; public const string InfoUpdated = "InfoUpdated"; public const string InvoiceError = "InvoiceError"; public const string CancelInvoiceError = "CancelInvoiceError"; public const string InvoiceCancelled = "InvoiceCancelled"; public PaymentRequestHub(UIPaymentRequestController paymentRequestController) { _PaymentRequestController = paymentRequestController; } public async Task ListenToPaymentRequest(string paymentRequestId) { if (Context.Items.ContainsKey("pr-id")) { await Groups.RemoveFromGroupAsync(Context.ConnectionId, Context.Items["pr-id"].ToString()); Context.Items.Remove("pr-id"); } Context.Items.Add("pr-id", paymentRequestId); await Groups.AddToGroupAsync(Context.ConnectionId, paymentRequestId); } public async Task Pay(decimal? amount = null) { _PaymentRequestController.ControllerContext.HttpContext = Context.GetHttpContext(); var result = await _PaymentRequestController.PayPaymentRequest(Context.Items["pr-id"].ToString(), false, amount); switch (result) { case OkObjectResult okObjectResult: await Clients.Caller.SendCoreAsync(InvoiceCreated, new[] { okObjectResult.Value.ToString() }); break; case ObjectResult objectResult: await Clients.Caller.SendCoreAsync(InvoiceError, new[] { objectResult.Value }); break; default: await Clients.Caller.SendCoreAsync(InvoiceError, System.Array.Empty<object>()); break; } } public async Task CancelUnpaidPendingInvoice() { _PaymentRequestController.ControllerContext.HttpContext = Context.GetHttpContext(); var result = await _PaymentRequestController.CancelUnpaidPendingInvoice(Context.Items["pr-id"].ToString(), false); switch (result) { case OkObjectResult okObjectResult: await Clients.Group(Context.Items["pr-id"].ToString()).SendCoreAsync(InvoiceCancelled, System.Array.Empty<object>()); break; default: await Clients.Caller.SendCoreAsync(CancelInvoiceError, System.Array.Empty<object>()); break; } } public static string GetHubPath(HttpRequest request) { return request.GetRelativePathOrAbsolute("/payment-requests/hub"); } public static void Register(IEndpointRouteBuilder route) { route.MapHub<PaymentRequestHub>("/payment-requests/hub"); } } public class PaymentRequestStreamer : EventHostedServiceBase { private readonly IHubContext<PaymentRequestHub> _HubContext; private readonly PaymentRequestRepository _PaymentRequestRepository; private readonly PaymentRequestService _PaymentRequestService; public PaymentRequestStreamer(EventAggregator eventAggregator, IHubContext<PaymentRequestHub> hubContext, PaymentRequestRepository paymentRequestRepository, PaymentRequestService paymentRequestService, Logs logs) : base(eventAggregator, logs) { _HubContext = hubContext; _PaymentRequestRepository = paymentRequestRepository; _PaymentRequestService = paymentRequestService; } public override async Task StartAsync(CancellationToken cancellationToken) { await base.StartAsync(cancellationToken); _CheckingPendingPayments = CheckingPendingPayments(cancellationToken) .ContinueWith(_ => _CheckingPendingPayments = null, TaskScheduler.Default); } private async Task CheckingPendingPayments(CancellationToken cancellationToken) { Logs.PayServer.LogInformation("Starting payment request expiration watcher"); var (total, items) = await _PaymentRequestRepository.FindPaymentRequests(new PaymentRequestQuery() { Status = new[] { Client.Models.PaymentRequestData.PaymentRequestStatus.Pending } }, cancellationToken); Logs.PayServer.LogInformation($"{total} pending payment requests being checked since last run"); await Task.WhenAll(items.Select(i => _PaymentRequestService.UpdatePaymentRequestStateIfNeeded(i)) .ToArray()); } Task _CheckingPendingPayments; public override async Task StopAsync(CancellationToken cancellationToken) { await base.StopAsync(cancellationToken); await (_CheckingPendingPayments ?? Task.CompletedTask); } protected override void SubscribeToEvents() { Subscribe<InvoiceEvent>(); Subscribe<PaymentRequestUpdated>(); } protected override async Task ProcessEvent(object evt, CancellationToken cancellationToken) { if (evt is InvoiceEvent invoiceEvent) { foreach (var paymentId in PaymentRequestRepository.GetPaymentIdsFromInternalTags(invoiceEvent.Invoice)) { if (invoiceEvent.Name == InvoiceEvent.ReceivedPayment || invoiceEvent.Name == InvoiceEvent.MarkedCompleted || invoiceEvent.Name == InvoiceEvent.MarkedInvalid) { await _PaymentRequestService.UpdatePaymentRequestStateIfNeeded(paymentId); var data = invoiceEvent.Payment?.GetCryptoPaymentData(); if (data != null) { await _HubContext.Clients.Group(paymentId).SendCoreAsync(PaymentRequestHub.PaymentReceived, new object[] { data.GetValue(), invoiceEvent.Payment.GetCryptoCode(), invoiceEvent.Payment.GetPaymentMethodId()?.PaymentType?.ToString() }, cancellationToken); } } await InfoUpdated(paymentId); } } else if (evt is PaymentRequestUpdated updated) { await _PaymentRequestService.UpdatePaymentRequestStateIfNeeded(updated.PaymentRequestId); await InfoUpdated(updated.PaymentRequestId); var expiry = updated.Data.GetBlob().ExpiryDate; if (updated.Data.Status == PaymentRequestData.PaymentRequestStatus.Pending && expiry.HasValue) { QueueExpiryTask( updated.PaymentRequestId, expiry.Value.UtcDateTime, cancellationToken); } } } private void QueueExpiryTask(string paymentRequestId, DateTime expiry, CancellationToken cancellationToken) { Task.Run(async () => { var delay = expiry - DateTime.UtcNow; if (delay > TimeSpan.Zero) await Task.Delay(delay, cancellationToken); await _PaymentRequestService.UpdatePaymentRequestStateIfNeeded(paymentRequestId); }, cancellationToken); } private async Task InfoUpdated(string paymentRequestId) { var req = await _PaymentRequestService.GetPaymentRequest(paymentRequestId); if (req != null) { await _HubContext.Clients.Group(paymentRequestId) .SendCoreAsync(PaymentRequestHub.InfoUpdated, new object[] { req }); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using System.Security; using System.Text; using Xunit; public static class SecureStringTest { // With the current Unix implementation of SecureString, allocating more than a certain // number of pages worth of memory will likely result in OOMs unless in a privileged process. private static readonly bool s_isWindowsOrPrivilegedUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || Interop.libc.geteuid() == 0; private static void VerifyString(SecureString ss, string exString) { IntPtr uniStr = IntPtr.Zero; try { uniStr = SecureStringMarshal.SecureStringToCoTaskMemUnicode(ss); string acString = Marshal.PtrToStringUni(uniStr); Assert.Equal(exString.Length, acString.Length); Assert.Equal(exString, acString); } finally { if (uniStr != IntPtr.Zero) SecureStringMarshal.ZeroFreeCoTaskMemUnicode(uniStr); } } private static SecureString CreateSecureString(string exValue) { SecureString ss = null; if (string.IsNullOrEmpty(exValue)) ss = new SecureString(); else { unsafe { fixed (char* mychars = exValue.ToCharArray()) ss = new SecureString(mychars, exValue.Length); } } Assert.NotNull(ss); return ss; } private static void CreateAndVerifySecureString(string exValue) { using (SecureString ss = CreateSecureString(exValue)) { VerifyString(ss, exValue); } } [Fact] public static void SecureString_Ctor() { CreateAndVerifySecureString(string.Empty); } [Fact] public static unsafe void SecureString_Ctor_CharInt() { // 1. Positive cases CreateAndVerifySecureString("test"); if (s_isWindowsOrPrivilegedUnix) { CreateAndVerifySecureString(new string('a', UInt16.MaxValue + 1)/*Max allowed length is 65536*/); } // 2. Negative cases Assert.Throws<ArgumentNullException>(() => new SecureString(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => { fixed (char* chars = "test") new SecureString(chars, -1); }); Assert.Throws<ArgumentOutOfRangeException>(() => CreateSecureString(new string('a', UInt16.MaxValue + 2 /*65537: Max allowed length is 65536*/))); } [Fact] public static void SecureString_AppendChar() { using (SecureString testString = CreateSecureString(string.Empty)) { StringBuilder sb = new StringBuilder(); testString.AppendChar('u'); sb.Append('u'); VerifyString(testString, sb.ToString()); //Append another character. testString.AppendChar(char.MaxValue); sb.Append(char.MaxValue); VerifyString(testString, sb.ToString()); } if (s_isWindowsOrPrivilegedUnix) { Assert.Throws<ArgumentOutOfRangeException>(() => { using (SecureString ss = CreateSecureString(new string('a', UInt16.MaxValue + 1))) ss.AppendChar('a'); }); } Assert.Throws<InvalidOperationException>(() => { using (SecureString ss = CreateSecureString(string.Empty)) { ss.MakeReadOnly(); ss.AppendChar('k'); } }); } [Fact] public static void SecureString_Clear() { String exString = String.Empty; using (SecureString testString = CreateSecureString(exString)) { testString.Clear(); VerifyString(testString, exString); } using (SecureString testString = CreateSecureString("test")) { testString.Clear(); VerifyString(testString, String.Empty); } // Check if readOnly Assert.Throws<InvalidOperationException>(() => { using (SecureString ss = new SecureString()) { ss.MakeReadOnly(); ss.Clear(); } }); // Check if secureString has been disposed. Assert.Throws<ObjectDisposedException>(() => { using (SecureString ss = CreateSecureString(new string('a', 100))) { ss.Dispose(); ss.Clear(); } }); } [Fact] public static void SecureString_Copy() { string exString = new string('a', 4000); using (SecureString testString = CreateSecureString(exString)) { using (SecureString copy_string = testString.Copy()) VerifyString(copy_string, exString); } //ObjectDisposedException. { SecureString testString = CreateSecureString("SomeValue"); testString.Dispose(); Assert.Throws<ObjectDisposedException>(() => testString.Copy()); } //Check for ReadOnly. exString = "test"; using (SecureString testString = CreateSecureString(exString)) { testString.MakeReadOnly(); using (SecureString copy_string = testString.Copy()) { VerifyString(copy_string, exString); Assert.True(testString.IsReadOnly()); Assert.False(copy_string.IsReadOnly()); } } } [Fact] public static void SecureString_InsertAt() { using (SecureString testString = CreateSecureString("bd")) { testString.InsertAt(0, 'a'); VerifyString(testString, "abd"); testString.InsertAt(3, 'e'); VerifyString(testString, "abde"); testString.InsertAt(2, 'c'); VerifyString(testString, "abcde"); Assert.Throws<ArgumentOutOfRangeException>(() => testString.InsertAt(-1, 'S')); Assert.Throws<ArgumentOutOfRangeException>(() => testString.InsertAt(6, 'S')); } if (s_isWindowsOrPrivilegedUnix) { using (SecureString testString = CreateSecureString(new string('a', UInt16.MaxValue + 1))) { Assert.Throws<ArgumentOutOfRangeException>(() => testString.InsertAt(22, 'S')); } } using (SecureString testString = CreateSecureString("test")) { testString.MakeReadOnly(); Assert.Throws<InvalidOperationException>(() => testString.InsertAt(2, 'S')); } { SecureString testString = CreateSecureString("test"); testString.Dispose(); Assert.Throws<ObjectDisposedException>(() => testString.InsertAt(2, 'S')); } } [Fact] public static void SecureString_IsReadOnly() { using (SecureString testString = CreateSecureString("test")) { Assert.False(testString.IsReadOnly()); testString.MakeReadOnly(); Assert.True(testString.IsReadOnly()); } { SecureString testString = CreateSecureString("test"); testString.Dispose(); Assert.Throws<ObjectDisposedException>(() => testString.IsReadOnly()); } } [Fact] public static void SecureString_MakeReadOnly() { using (SecureString testString = CreateSecureString("test")) { Assert.False(testString.IsReadOnly()); testString.MakeReadOnly(); Assert.True(testString.IsReadOnly()); testString.MakeReadOnly(); Assert.True(testString.IsReadOnly()); } { SecureString testString = CreateSecureString("test"); testString.Dispose(); Assert.Throws<ObjectDisposedException>(() => testString.MakeReadOnly()); } } [Fact] public static void SecureString_RemoveAt() { using (SecureString testString = CreateSecureString("abcde")) { testString.RemoveAt(3); VerifyString(testString, "abce"); testString.RemoveAt(3); VerifyString(testString, "abc"); testString.RemoveAt(0); VerifyString(testString, "bc"); testString.RemoveAt(1); VerifyString(testString, "b"); testString.RemoveAt(0); VerifyString(testString, ""); testString.AppendChar('f'); VerifyString(testString, "f"); testString.AppendChar('g'); VerifyString(testString, "fg"); testString.RemoveAt(0); VerifyString(testString, "g"); } if (s_isWindowsOrPrivilegedUnix) { using (SecureString testString = CreateSecureString(new string('a', UInt16.MaxValue + 1))) { testString.RemoveAt(22); testString.AppendChar('a'); VerifyString(testString, new string('a', UInt16.MaxValue + 1)); } } using (SecureString testString = CreateSecureString("test")) { Assert.Throws<ArgumentOutOfRangeException>(() => testString.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => testString.RemoveAt(testString.Length)); Assert.Throws<ArgumentOutOfRangeException>(() => testString.RemoveAt(testString.Length + 1)); testString.MakeReadOnly(); Assert.Throws<InvalidOperationException>(() => testString.RemoveAt(0)); } { SecureString testString = CreateSecureString("test"); testString.Dispose(); Assert.Throws<ObjectDisposedException>(() => testString.RemoveAt(0)); } } [Fact] public static void SecureString_SetAt() { using (SecureString testString = CreateSecureString("abc")) { testString.SetAt(2, 'f'); VerifyString(testString, "abf"); testString.SetAt(0, 'd'); VerifyString(testString, "dbf"); testString.SetAt(1, 'e'); VerifyString(testString, "def"); } if (s_isWindowsOrPrivilegedUnix) { string exString = new string('a', UInt16.MaxValue + 1); using (SecureString testString = CreateSecureString(exString)) { testString.SetAt(22, 'b'); char[] chars = exString.ToCharArray(); chars[22] = 'b'; VerifyString(testString, new string(chars)); } } using (SecureString testString = CreateSecureString("test")) { Assert.Throws<ArgumentOutOfRangeException>(() => testString.SetAt(-1, 'a')); Assert.Throws<ArgumentOutOfRangeException>(() => testString.SetAt(testString.Length, 'b')); Assert.Throws<ArgumentOutOfRangeException>(() => testString.SetAt(testString.Length + 1, 'c')); testString.MakeReadOnly(); Assert.Throws<InvalidOperationException>(() => testString.SetAt(0, 'd')); } { SecureString testString = CreateSecureString("test"); testString.Dispose(); Assert.Throws<ObjectDisposedException>(() => testString.SetAt(0, 'e')); } } [Fact] public static void SecureStringMarshal_ArgValidation() { Assert.Throws<ArgumentNullException>(() => SecureStringMarshal.SecureStringToCoTaskMemUnicode(null)); } [Fact] public static void SecureString_RepeatedCtorDispose() { string str = new string('a', 4000); for (int i = 0; i < 1000; i++) { CreateSecureString(str).Dispose(); } } [Fact] [OuterLoop] public static void SecureString_Growth() { string starting = new string('a', 6000); StringBuilder sb = new StringBuilder(starting); using (SecureString testString = CreateSecureString(starting)) { for (int i = 0; i < 4000; i++) { char c = (char)('a' + (i % 26)); testString.AppendChar(c); sb.Append(c); } VerifyString(testString, sb.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; using System.Runtime.InteropServices; #pragma warning disable 1717 #pragma warning disable 0219 #pragma warning disable 1718 public enum TestEnum { red = 1, green = 2, blue = 4, } public class AA { public double[][] m_adblField1; public static ulong[] Static1() { for (App.m_xFwd1=App.m_xFwd1; App.m_bFwd2; App.m_shFwd3-=((short)(121.0))) { if (App.m_bFwd2) do { try { uint[,][] local1 = (new uint[88u, 43u][]); do { } while(App.m_bFwd2); } catch (Exception) { AA local2 = new AA(); } try { bool local3 = false; } finally { char local4 = '\x5d'; } } while(App.m_bFwd2); throw new DivideByZeroException(); } try { } catch (IndexOutOfRangeException) { byte local5 = ((byte)(26.0)); } return (new ulong[3u]); } public static ushort[] Static2() { for (App.m_ushFwd4*=App.m_ushFwd4; App.m_bFwd2; App.m_dblFwd5-=66.0) { float local6 = 112.0f; do { goto label1; } while(App.m_bFwd2); local6 = local6; label1: try { Array local7 = ((Array)(null)); } catch (Exception) { } } try { } catch (IndexOutOfRangeException) { } while (App.m_bFwd2) { } return App.m_aushFwd6; } public static long[] Static3() { for (App.m_sbyFwd7*=((sbyte)(70)); (null == new AA()); App.m_dblFwd5+=97.0) { double local8 = 20.0; for (App.m_iFwd8*=119; App.m_bFwd2; App.m_lFwd9--) { short local9 = App.m_shFwd3; return (new long[111u]); } local8 = local8; if (App.m_bFwd2) continue; } return App.m_alFwd10; } public static short[] Static4() { byte local10 = ((byte)(55u)); for (App.m_dblFwd5=App.m_dblFwd5; App.m_bFwd2; App.m_ulFwd11--) { sbyte[][,,][,] local11 = (new sbyte[91u][,,][,]); break; } while (App.m_bFwd2) { char local12 = '\x48'; while ((null != new AA())) { double local13 = 55.0; try { while ((local10 != local10)) { sbyte[,,] local14 = (new sbyte[97u, 62u, 10u]); } } catch (Exception) { } if (App.m_bFwd2) for (App.m_sbyFwd7/=((sbyte)(local10)); App.m_bFwd2; App.m_lFwd9/=App. m_lFwd9) { } } } return (new short[16u]); } public static long[][] Static5() { byte[,,] local15 = (new byte[7u, 92u, 57u]); return new long[][]{(new long[33u]), (new long[60u]), /*2 REFS*/(new long[61u] ), /*2 REFS*/(new long[61u]), (new long[22u]) }; } public static TestEnum Static6() { int local16 = 105; do { ulong local17 = ((ulong)(54)); for (local16+=(local16 *= local16); App.m_bFwd2; App.m_dblFwd5++) { int local18 = 90; try { int local19 = 45; if ((new AA() == null)) try { } catch (Exception) { } else { } } catch (InvalidOperationException) { } local17 += local17; goto label2; } } while(App.m_bFwd2); local16 -= ((int)(18u)); label2: return 0; } public static double Static7() { for (App.m_sbyFwd7=App.m_sbyFwd7; App.m_bFwd2; App.m_chFwd12++) { object local20 = null; for (App.m_iFwd8++; ((bool)(local20)); local20=local20) { AA.Static1( ); } } return 82.0; } public static byte Static8() { while (App.m_bFwd2) { short local21 = App.m_shFwd3; while (Convert.ToBoolean(local21)) { local21 *= (local21 -= local21); goto label3; } if (App.m_bFwd2) local21 /= local21; local21 = (local21 += local21); } if (App.m_bFwd2) for (App.m_lFwd9--; App.m_bFwd2; App.m_dblFwd5-=AA.Static7()) { TestEnum[][,,,][,] local22 = (new TestEnum[102u][,,,][,]); } label3: return App.m_byFwd13; } } [StructLayout(LayoutKind.Sequential)] public class App { public static int Main() { try { AA.Static1( ); } catch (Exception ) { } try { AA.Static2( ); } catch (Exception ) { } try { AA.Static3( ); } catch (Exception ) { } try { AA.Static4( ); } catch (Exception ) { } try { AA.Static5( ); } catch (Exception ) { } try { AA.Static6( ); } catch (Exception ) { } try { AA.Static7( ); } catch (Exception ) { } try { AA.Static8( ); } catch (Exception ) { } return 100; } public static Array m_xFwd1; public static bool m_bFwd2; public static short m_shFwd3; public static ushort m_ushFwd4; public static double m_dblFwd5; public static ushort[] m_aushFwd6; public static sbyte m_sbyFwd7; public static int m_iFwd8; public static long m_lFwd9; public static long[] m_alFwd10; public static ulong m_ulFwd11; public static char m_chFwd12; public static byte m_byFwd13; }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using Xunit; namespace System.Text.EncodingTests { // GetChars(System.Byte[],System.Int32,System.Int32,System.Char[],System.Int32) public class DecoderGetChars3 { #region Private Fields private const int c_SIZE_OF_ARRAY = 127; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); #endregion #region Positive Test Cases // PosTest1: Call GetChars with ASCII decoder to convert a ASCII byte array [Fact] public void PosTest1() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; char[] expectedChars = new char[bytes.Length]; Decoder decoder = Encoding.UTF8.GetDecoder(); for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)i; } for (int i = 0; i < expectedChars.Length; ++i) { expectedChars[i] = (char)('\0' + i); } VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, bytes.Length, expectedChars, "001.1"); } // PosTest2: Call GetChars with Unicode decoder to convert a ASCII byte array [Fact] public void PosTest2() { byte[] bytes = new byte[c_SIZE_OF_ARRAY * 2]; char[] chars = new char[c_SIZE_OF_ARRAY]; char[] expectedChars = new char[c_SIZE_OF_ARRAY]; Decoder decoder = Encoding.Unicode.GetDecoder(); byte c = 0; for (int i = 0; i < bytes.Length; i += 2) { bytes[i] = c++; bytes[i + 1] = 0; } for (int i = 0; i < expectedChars.Length; ++i) { expectedChars[i] = (char)('\0' + i); } VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, expectedChars.Length, expectedChars, "002.1"); } // PosTest3: Call GetChars with Unicode decoder to convert a Unicode byte array [Fact] public void PosTest3() { byte[] bytes = new byte[] { 217, 143, 42, 78, 0, 78, 42, 78, 75, 109, 213, 139 }; char[] expected = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); char[] chars = new char[expected.Length]; Decoder decoder = Encoding.Unicode.GetDecoder(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, expected.Length, expected, "003.1"); } // PosTest4: Call GetChars with ASCII decoder to convert partial of ASCII byte array [Fact] public void PosTest4() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.UTF8.GetDecoder(); for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)i; } VerificationHelper(decoder, bytes, 0, bytes.Length / 2, chars, 0, bytes.Length / 2, "004.1"); VerificationHelper(decoder, bytes, bytes.Length / 2, bytes.Length / 2, chars, chars.Length / 2, bytes.Length / 2, "004.2"); } // PosTest5: Call GetChars with Unicode decoder to convert partial of an Unicode byte array [Fact] public void PosTest5() { byte[] bytes = new byte[] { 217, 143, 42, 78, 0, 78, 42, 78, 75, 109, 213, 139 }; char[] expected = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); char[] chars = new char[expected.Length]; Decoder decoder = Encoding.Unicode.GetDecoder(); VerificationHelper(decoder, bytes, 0, bytes.Length / 2, chars, 0, chars.Length / 2, "005.1"); VerificationHelper(decoder, bytes, bytes.Length / 2, bytes.Length / 2, chars, 1, chars.Length / 2, "005.2"); } // PosTest6: Call GetChars with ASCII decoder to convert arbitrary byte array [Fact] public void PosTest6() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.UTF8.GetDecoder(); _generator.GetBytes(-55, bytes); decoder.GetChars(bytes, 0, bytes.Length, chars, 0); } // PosTest7: Call GetChars with Unicode decoder to convert arbitrary byte array [Fact] public void PosTest7() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.Unicode.GetDecoder(); _generator.GetBytes(-55, bytes); decoder.GetChars(bytes, 0, bytes.Length, chars, 0); } // PosTest8: Call GetChars but convert nothing [Fact] public void PosTest8() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.UTF8.GetDecoder(); _generator.GetBytes(-55, bytes); VerificationHelper(decoder, bytes, 0, 0, chars, 0, 0, "008.1"); decoder = Encoding.Unicode.GetDecoder(); VerificationHelper(decoder, bytes, 0, 0, chars, 0, 0, "008.2"); } #endregion #region Negative Test Cases // NegTest1: ArgumentNullException should be throw when bytes is a null reference or chars is a null reference [Fact] public void NegTest1() { Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentNullException>(decoder, null, 0, 0, chars, 0, typeof(ArgumentNullException), "101.1"); VerificationHelper<ArgumentNullException>(decoder, bytes, 0, 0, null, 0, typeof(ArgumentNullException), "101.2"); } // NegTest2: ArgumentOutOfRangeException should be throw when byteIndex or byteCount or charIndex is less than zero. [Fact] public void NegTest2() { Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 0, -1, chars, 0, typeof(ArgumentOutOfRangeException), "102.1"); VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 0, 0, chars, -1, typeof(ArgumentOutOfRangeException), "102.2"); VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, -1, 0, chars, 0, typeof(ArgumentOutOfRangeException), "102.3"); } // NegTest3: ArgumentException should be throw when charCount is less than the resulting number of characters [Fact] public void NegTest3() { Decoder decoder = Encoding.UTF8.GetDecoder(); byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[1]; _generator.GetBytes(-55, bytes); VerificationHelper<ArgumentException>(decoder, bytes, 0, bytes.Length, chars, 0, typeof(ArgumentException), "103.1"); } // NegTest4: ArgumentOutOfRangeException should be throw when byteindex and byteCount do not denote a valid range in bytes. [Fact] public void NegTest4() { Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 1, bytes.Length, chars, 0, typeof(ArgumentOutOfRangeException), "104.1"); VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, bytes.Length, 1, chars, 0, typeof(ArgumentOutOfRangeException), "104.2"); } // NegTest5: ArgumentOutOfRangeException should be throw when charIndex is not a valid index in chars. [Fact] public void NegTest5() { Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 1, 0, chars, chars.Length + 1, typeof(ArgumentOutOfRangeException), "105.1"); } #endregion private void VerificationHelper<T>(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, Type expected, string errorno) where T : Exception { Assert.Throws<T>(() => { decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex); }); } private void VerificationHelper(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int expected, string errorno) { int actual = decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex); Assert.Equal(expected, actual); } private void VerificationHelper(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int expected, char[] expectedChars, string errorno) { VerificationHelper(decoder, bytes, byteIndex, byteCount, chars, charIndex, expected, errorno + ".1"); Assert.Equal(expectedChars.Length, chars.Length); Assert.Equal(expectedChars, chars); } } }
using System; using System.Diagnostics; using Lucene.Net.Documents; namespace Lucene.Net.Search { using Lucene.Net.Index; using NUnit.Framework; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using DoubleField = DoubleField; using Field = Field; using FieldType = FieldType; using IndexReader = Lucene.Net.Index.IndexReader; using LongField = LongField; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MultiFields = Lucene.Net.Index.MultiFields; using NumericUtils = Lucene.Net.Util.NumericUtils; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using TestNumericUtils = Lucene.Net.Util.TestNumericUtils; // NaN arrays using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestNumericRangeQuery64 : LuceneTestCase { // distance of entries private static long Distance; // shift the starting of the values to the left, to also have negative values: private static readonly long StartOffset = -1L << 31; // number of docs to generate for testing private static int NoDocs; private static Directory Directory = null; private static IndexReader Reader = null; private static IndexSearcher Searcher = null; [TestFixtureSetUp] public static void BeforeClass() { NoDocs = AtLeast(4096); Distance = (1L << 60) / NoDocs; Directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 100, 1000)).SetMergePolicy(NewLogMergePolicy())); FieldType storedLong = new FieldType(LongField.TYPE_NOT_STORED); storedLong.Stored = true; storedLong.Freeze(); FieldType storedLong8 = new FieldType(storedLong); storedLong8.NumericPrecisionStep = 8; FieldType storedLong4 = new FieldType(storedLong); storedLong4.NumericPrecisionStep = 4; FieldType storedLong6 = new FieldType(storedLong); storedLong6.NumericPrecisionStep = 6; FieldType storedLong2 = new FieldType(storedLong); storedLong2.NumericPrecisionStep = 2; FieldType storedLongNone = new FieldType(storedLong); storedLongNone.NumericPrecisionStep = int.MaxValue; FieldType unstoredLong = LongField.TYPE_NOT_STORED; FieldType unstoredLong8 = new FieldType(unstoredLong); unstoredLong8.NumericPrecisionStep = 8; FieldType unstoredLong6 = new FieldType(unstoredLong); unstoredLong6.NumericPrecisionStep = 6; FieldType unstoredLong4 = new FieldType(unstoredLong); unstoredLong4.NumericPrecisionStep = 4; FieldType unstoredLong2 = new FieldType(unstoredLong); unstoredLong2.NumericPrecisionStep = 2; LongField field8 = new LongField("field8", 0L, storedLong8), field6 = new LongField("field6", 0L, storedLong6), field4 = new LongField("field4", 0L, storedLong4), field2 = new LongField("field2", 0L, storedLong2), fieldNoTrie = new LongField("field" + int.MaxValue, 0L, storedLongNone), ascfield8 = new LongField("ascfield8", 0L, unstoredLong8), ascfield6 = new LongField("ascfield6", 0L, unstoredLong6), ascfield4 = new LongField("ascfield4", 0L, unstoredLong4), ascfield2 = new LongField("ascfield2", 0L, unstoredLong2); Document doc = new Document(); // add fields, that have a distance to test general functionality doc.Add(field8); doc.Add(field6); doc.Add(field4); doc.Add(field2); doc.Add(fieldNoTrie); // add ascending fields with a distance of 1, beginning at -noDocs/2 to test the correct splitting of range and inclusive/exclusive doc.Add(ascfield8); doc.Add(ascfield6); doc.Add(ascfield4); doc.Add(ascfield2); // Add a series of noDocs docs with increasing long values, by updating the fields for (int l = 0; l < NoDocs; l++) { long val = Distance * l + StartOffset; field8.LongValue = val; field6.LongValue = val; field4.LongValue = val; field2.LongValue = val; fieldNoTrie.LongValue = val; val = l - (NoDocs / 2); ascfield8.LongValue = val; ascfield6.LongValue = val; ascfield4.LongValue = val; ascfield2.LongValue = val; writer.AddDocument(doc); } Reader = writer.Reader; Searcher = NewSearcher(Reader); writer.Dispose(); } [TestFixtureTearDown] public static void AfterClass() { Searcher = null; Reader.Dispose(); Reader = null; Directory.Dispose(); Directory = null; } [SetUp] public override void SetUp() { base.SetUp(); // set the theoretical maximum term count for 8bit (see docs for the number) // super.tearDown will restore the default BooleanQuery.MaxClauseCount = 7 * 255 * 2 + 255; } /// <summary> /// test for constant score + boolean query + filter, the other tests only use the constant score mode </summary> private void TestRange(int precisionStep) { string field = "field" + precisionStep; int count = 3000; long lower = (Distance * 3 / 2) + StartOffset, upper = lower + count * Distance + (Distance / 3); NumericRangeQuery<long> q = NumericRangeQuery.NewLongRange(field, precisionStep, lower, upper, true, true); NumericRangeFilter<long> f = NumericRangeFilter.NewLongRange(field, precisionStep, lower, upper, true, true); for (sbyte i = 0; i < 3; i++) { TopDocs topDocs; string type; switch (i) { case 0: type = " (constant score filter rewrite)"; q.SetRewriteMethod(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE); topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); break; case 1: type = " (constant score boolean rewrite)"; q.SetRewriteMethod(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE); topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); break; case 2: type = " (filter)"; topDocs = Searcher.Search(new MatchAllDocsQuery(), f, NoDocs, Sort.INDEXORDER); break; default: return; } ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(count, sd.Length, "Score doc count" + type); Document doc = Searcher.Doc(sd[0].Doc); Assert.AreEqual(2 * Distance + StartOffset, (long)doc.GetField(field).NumericValue, "First doc" + type); doc = Searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((1 + count) * Distance + StartOffset, (long)doc.GetField(field).NumericValue, "Last doc" + type); } } [Test] public virtual void TestRange_8bit() { TestRange(8); } [Test] public virtual void TestRange_6bit() { TestRange(6); } [Test] public virtual void TestRange_4bit() { TestRange(4); } [Test] public virtual void TestRange_2bit() { TestRange(2); } [Test] public virtual void TestInverseRange() { AtomicReaderContext context = (AtomicReaderContext)SlowCompositeReaderWrapper.Wrap(Searcher.IndexReader).Context; NumericRangeFilter<long> f = NumericRangeFilter.NewLongRange("field8", 8, 1000L, -1000L, true, true); Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A inverse range should return the null instance"); f = NumericRangeFilter.NewLongRange("field8", 8, long.MaxValue, null, false, false); Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A exclusive range starting with Long.MAX_VALUE should return the null instance"); f = NumericRangeFilter.NewLongRange("field8", 8, null, long.MinValue, false, false); Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A exclusive range ending with Long.MIN_VALUE should return the null instance"); } [Test] public virtual void TestOneMatchQuery() { NumericRangeQuery<long> q = NumericRangeQuery.NewLongRange("ascfield8", 8, 1000L, 1000L, true, true); TopDocs topDocs = Searcher.Search(q, NoDocs); ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(1, sd.Length, "Score doc count"); } private void TestLeftOpenRange(int precisionStep) { string field = "field" + precisionStep; int count = 3000; long upper = (count - 1) * Distance + (Distance / 3) + StartOffset; NumericRangeQuery<long> q = NumericRangeQuery.NewLongRange(field, precisionStep, null, upper, true, true); TopDocs topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(count, sd.Length, "Score doc count"); Document doc = Searcher.Doc(sd[0].Doc); Assert.AreEqual(StartOffset, (long)doc.GetField(field).NumericValue, "First doc"); doc = Searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((count - 1) * Distance + StartOffset, (long)doc.GetField(field).NumericValue, "Last doc"); q = NumericRangeQuery.NewLongRange(field, precisionStep, null, upper, false, true); topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(count, sd.Length, "Score doc count"); doc = Searcher.Doc(sd[0].Doc); Assert.AreEqual(StartOffset, (long)doc.GetField(field).NumericValue, "First doc"); doc = Searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((count - 1) * Distance + StartOffset, (long)doc.GetField(field).NumericValue, "Last doc"); } [Test] public virtual void TestLeftOpenRange_8bit() { TestLeftOpenRange(8); } [Test] public virtual void TestLeftOpenRange_6bit() { TestLeftOpenRange(6); } [Test] public virtual void TestLeftOpenRange_4bit() { TestLeftOpenRange(4); } [Test] public virtual void TestLeftOpenRange_2bit() { TestLeftOpenRange(2); } private void TestRightOpenRange(int precisionStep) { string field = "field" + precisionStep; int count = 3000; long lower = (count - 1) * Distance + (Distance / 3) + StartOffset; NumericRangeQuery<long> q = NumericRangeQuery.NewLongRange(field, precisionStep, lower, null, true, true); TopDocs topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(NoDocs - count, sd.Length, "Score doc count"); Document doc = Searcher.Doc(sd[0].Doc); Assert.AreEqual(count * Distance + StartOffset, (long)doc.GetField(field).NumericValue, "First doc"); doc = Searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((NoDocs - 1) * Distance + StartOffset, (long)doc.GetField(field).NumericValue, "Last doc"); q = NumericRangeQuery.NewLongRange(field, precisionStep, lower, null, true, false); topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(NoDocs - count, sd.Length, "Score doc count"); doc = Searcher.Doc(sd[0].Doc); Assert.AreEqual(count * Distance + StartOffset, (long)doc.GetField(field).NumericValue, "First doc"); doc = Searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((NoDocs - 1) * Distance + StartOffset, (long)doc.GetField(field).NumericValue, "Last doc"); } [Test] public virtual void TestRightOpenRange_8bit() { TestRightOpenRange(8); } [Test] public virtual void TestRightOpenRange_6bit() { TestRightOpenRange(6); } [Test] public virtual void TestRightOpenRange_4bit() { TestRightOpenRange(4); } [Test] public virtual void TestRightOpenRange_2bit() { TestRightOpenRange(2); } [Test] public virtual void TestInfiniteValues() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); Document doc = new Document(); doc.Add(new DoubleField("double", double.NegativeInfinity, Field.Store.NO)); doc.Add(new LongField("long", long.MinValue, Field.Store.NO)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleField("double", double.PositiveInfinity, Field.Store.NO)); doc.Add(new LongField("long", long.MaxValue, Field.Store.NO)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleField("double", 0.0, Field.Store.NO)); doc.Add(new LongField("long", 0L, Field.Store.NO)); writer.AddDocument(doc); foreach (double d in TestNumericUtils.DOUBLE_NANs) { doc = new Document(); doc.Add(new DoubleField("double", d, Field.Store.NO)); writer.AddDocument(doc); } writer.Dispose(); IndexReader r = DirectoryReader.Open(dir); IndexSearcher s = NewSearcher(r); Query q = NumericRangeQuery.NewLongRange("long", null, null, true, true); TopDocs topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewLongRange("long", null, null, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewLongRange("long", long.MinValue, long.MaxValue, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewLongRange("long", long.MinValue, long.MaxValue, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(1, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewDoubleRange("double", null, null, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewDoubleRange("double", null, null, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewDoubleRange("double", double.NegativeInfinity, double.PositiveInfinity, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewDoubleRange("double", double.NegativeInfinity, double.PositiveInfinity, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(1, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewDoubleRange("double", double.NaN, double.NaN, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(TestNumericUtils.DOUBLE_NANs.Length, topDocs.ScoreDocs.Length, "Score doc count"); r.Dispose(); dir.Dispose(); } private void TestRandomTrieAndClassicRangeQuery(int precisionStep) { string field = "field" + precisionStep; int totalTermCountT = 0, totalTermCountC = 0, termCountT, termCountC; int num = TestUtil.NextInt(Random(), 10, 20); for (int i = 0; i < num; i++) { long lower = (long)(Random().NextDouble() * NoDocs * Distance) + StartOffset; long upper = (long)(Random().NextDouble() * NoDocs * Distance) + StartOffset; if (lower > upper) { long a = lower; lower = upper; upper = a; } BytesRef lowerBytes = new BytesRef(NumericUtils.BUF_SIZE_LONG), upperBytes = new BytesRef(NumericUtils.BUF_SIZE_LONG); NumericUtils.LongToPrefixCodedBytes(lower, 0, lowerBytes); NumericUtils.LongToPrefixCodedBytes(upper, 0, upperBytes); // test inclusive range NumericRangeQuery<long> tq = NumericRangeQuery.NewLongRange(field, precisionStep, lower, upper, true, true); TermRangeQuery cq = new TermRangeQuery(field, lowerBytes, upperBytes, true, true); TopDocs tTopDocs = Searcher.Search(tq, 1); TopDocs cTopDocs = Searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); // test exclusive range tq = NumericRangeQuery.NewLongRange(field, precisionStep, lower, upper, false, false); cq = new TermRangeQuery(field, lowerBytes, upperBytes, false, false); tTopDocs = Searcher.Search(tq, 1); cTopDocs = Searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); // test left exclusive range tq = NumericRangeQuery.NewLongRange(field, precisionStep, lower, upper, false, true); cq = new TermRangeQuery(field, lowerBytes, upperBytes, false, true); tTopDocs = Searcher.Search(tq, 1); cTopDocs = Searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); // test right exclusive range tq = NumericRangeQuery.NewLongRange(field, precisionStep, lower, upper, true, false); cq = new TermRangeQuery(field, lowerBytes, upperBytes, true, false); tTopDocs = Searcher.Search(tq, 1); cTopDocs = Searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); } CheckTermCounts(precisionStep, totalTermCountT, totalTermCountC); if (VERBOSE && precisionStep != int.MaxValue) { Console.WriteLine("Average number of terms during random search on '" + field + "':"); Console.WriteLine(" Numeric query: " + (((double)totalTermCountT) / (num * 4))); Console.WriteLine(" Classical query: " + (((double)totalTermCountC) / (num * 4))); } } [Test] public virtual void TestEmptyEnums() { int count = 3000; long lower = (Distance * 3 / 2) + StartOffset, upper = lower + count * Distance + (Distance / 3); // test empty enum Debug.Assert(lower < upper); Assert.IsTrue(0 < CountTerms(NumericRangeQuery.NewLongRange("field4", 4, lower, upper, true, true))); Assert.AreEqual(0, CountTerms(NumericRangeQuery.NewLongRange("field4", 4, upper, lower, true, true))); // test empty enum outside of bounds lower = Distance * NoDocs + StartOffset; upper = 2L * lower; Debug.Assert(lower < upper); Assert.AreEqual(0, CountTerms(NumericRangeQuery.NewLongRange("field4", 4, lower, upper, true, true))); } private int CountTerms(MultiTermQuery q) { Terms terms = MultiFields.GetTerms(Reader, q.Field); if (terms == null) { return 0; } TermsEnum termEnum = q.GetTermsEnum(terms); Assert.IsNotNull(termEnum); int count = 0; BytesRef cur, last = null; while ((cur = termEnum.Next()) != null) { count++; if (last != null) { Assert.IsTrue(last.CompareTo(cur) < 0); } last = BytesRef.DeepCopyOf(cur); } // LUCENE-3314: the results after next() already returned null are undefined, // Assert.IsNull(termEnum.Next()); return count; } private void CheckTermCounts(int precisionStep, int termCountT, int termCountC) { if (precisionStep == int.MaxValue) { Assert.AreEqual(termCountC, termCountT, "Number of terms should be equal for unlimited precStep"); } else { Assert.IsTrue(termCountT <= termCountC, "Number of terms for NRQ should be <= compared to classical TRQ"); } } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_8bit() { TestRandomTrieAndClassicRangeQuery(8); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_6bit() { TestRandomTrieAndClassicRangeQuery(6); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_4bit() { TestRandomTrieAndClassicRangeQuery(4); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_2bit() { TestRandomTrieAndClassicRangeQuery(2); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_NoTrie() { TestRandomTrieAndClassicRangeQuery(int.MaxValue); } private void TestRangeSplit(int precisionStep) { string field = "ascfield" + precisionStep; // 10 random tests int num = TestUtil.NextInt(Random(), 10, 20); for (int i = 0; i < num; i++) { long lower = (long)(Random().NextDouble() * NoDocs - NoDocs / 2); long upper = (long)(Random().NextDouble() * NoDocs - NoDocs / 2); if (lower > upper) { long a = lower; lower = upper; upper = a; } // test inclusive range Query tq = NumericRangeQuery.NewLongRange(field, precisionStep, lower, upper, true, true); TopDocs tTopDocs = Searcher.Search(tq, 1); Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length"); // test exclusive range tq = NumericRangeQuery.NewLongRange(field, precisionStep, lower, upper, false, false); tTopDocs = Searcher.Search(tq, 1); Assert.AreEqual(Math.Max(upper - lower - 1, 0), tTopDocs.TotalHits, "Returned count of range query must be equal to exclusive range length"); // test left exclusive range tq = NumericRangeQuery.NewLongRange(field, precisionStep, lower, upper, false, true); tTopDocs = Searcher.Search(tq, 1); Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length"); // test right exclusive range tq = NumericRangeQuery.NewLongRange(field, precisionStep, lower, upper, true, false); tTopDocs = Searcher.Search(tq, 1); Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length"); } } [Test] public virtual void TestRangeSplit_8bit() { TestRangeSplit(8); } [Test] public virtual void TestRangeSplit_6bit() { TestRangeSplit(6); } [Test] public virtual void TestRangeSplit_4bit() { TestRangeSplit(4); } [Test] public virtual void TestRangeSplit_2bit() { TestRangeSplit(2); } /// <summary> /// we fake a double test using long2double conversion of NumericUtils </summary> private void TestDoubleRange(int precisionStep) { string field = "ascfield" + precisionStep; const long lower = -1000L, upper = +2000L; Query tq = NumericRangeQuery.NewDoubleRange(field, precisionStep, NumericUtils.SortableLongToDouble(lower), NumericUtils.SortableLongToDouble(upper), true, true); TopDocs tTopDocs = Searcher.Search(tq, 1); Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length"); Filter tf = NumericRangeFilter.NewDoubleRange(field, precisionStep, NumericUtils.SortableLongToDouble(lower), NumericUtils.SortableLongToDouble(upper), true, true); tTopDocs = Searcher.Search(new MatchAllDocsQuery(), tf, 1); Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range filter must be equal to inclusive range length"); } [Test] public virtual void TestDoubleRange_8bit() { TestDoubleRange(8); } [Test] public virtual void TestDoubleRange_6bit() { TestDoubleRange(6); } [Test] public virtual void TestDoubleRange_4bit() { TestDoubleRange(4); } [Test] public virtual void TestDoubleRange_2bit() { TestDoubleRange(2); } private void TestSorting(int precisionStep) { string field = "field" + precisionStep; // 10 random tests, the index order is ascending, // so using a reverse sort field should retun descending documents int num = TestUtil.NextInt(Random(), 10, 20); for (int i = 0; i < num; i++) { long lower = (long)(Random().NextDouble() * NoDocs * Distance) + StartOffset; long upper = (long)(Random().NextDouble() * NoDocs * Distance) + StartOffset; if (lower > upper) { long a = lower; lower = upper; upper = a; } Query tq = NumericRangeQuery.NewLongRange(field, precisionStep, lower, upper, true, true); TopDocs topDocs = Searcher.Search(tq, null, NoDocs, new Sort(new SortField(field, SortField.Type_e.LONG, true))); if (topDocs.TotalHits == 0) { continue; } ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); long last = (long)Searcher.Doc(sd[0].Doc).GetField(field).NumericValue; for (int j = 1; j < sd.Length; j++) { long act = (long)Searcher.Doc(sd[j].Doc).GetField(field).NumericValue; Assert.IsTrue(last > act, "Docs should be sorted backwards"); last = act; } } } [Test] public virtual void TestSorting_8bit() { TestSorting(8); } [Test] public virtual void TestSorting_6bit() { TestSorting(6); } [Test] public virtual void TestSorting_4bit() { TestSorting(4); } [Test] public virtual void TestSorting_2bit() { TestSorting(2); } [Test] public virtual void TestEqualsAndHash() { QueryUtils.CheckHashEquals(NumericRangeQuery.NewLongRange("test1", 4, 10L, 20L, true, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewLongRange("test2", 4, 10L, 20L, false, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewLongRange("test3", 4, 10L, 20L, true, false)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewLongRange("test4", 4, 10L, 20L, false, false)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewLongRange("test5", 4, 10L, null, true, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewLongRange("test6", 4, null, 20L, true, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewLongRange("test7", 4, null, null, true, true)); QueryUtils.CheckEqual(NumericRangeQuery.NewLongRange("test8", 4, 10L, 20L, true, true), NumericRangeQuery.NewLongRange("test8", 4, 10L, 20L, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewLongRange("test9", 4, 10L, 20L, true, true), NumericRangeQuery.NewLongRange("test9", 8, 10L, 20L, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewLongRange("test10a", 4, 10L, 20L, true, true), NumericRangeQuery.NewLongRange("test10b", 4, 10L, 20L, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewLongRange("test11", 4, 10L, 20L, true, true), NumericRangeQuery.NewLongRange("test11", 4, 20L, 10L, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewLongRange("test12", 4, 10L, 20L, true, true), NumericRangeQuery.NewLongRange("test12", 4, 10L, 20L, false, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewLongRange("test13", 4, 10L, 20L, true, true), NumericRangeQuery.NewFloatRange("test13", 4, 10f, 20f, true, true)); // difference to int range is tested in TestNumericRangeQuery32 } } }
using System; using System.Linq; using System.Collections.Generic; using UnityEditor.Experimental.Rendering.HDPipeline.Drawing; using UnityEditor.Graphing; using UnityEditor.ShaderGraph; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.ShaderGraph.Drawing.Controls; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.Experimental.Rendering.HDPipeline; namespace UnityEditor.Experimental.Rendering.HDPipeline { [Serializable] [Title("Master", "HDRP/Decal")] class DecalMasterNode : MasterNode<IDecalSubShader>, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent { public const string PositionSlotName = "Position"; public const int PositionSlotId = 0; public const string AlbedoSlotName = "Albedo"; public const string AlbedoDisplaySlotName = "BaseColor"; public const int AlbedoSlotId = 1; public const string BaseColorOpacitySlotName = "AlphaAlbedo"; public const string BaseColorOpacityDisplaySlotName = "BaseColor Opacity"; public const int BaseColorOpacitySlotId = 2; public const string NormalSlotName = "Normal"; public const int NormalSlotId = 3; public const string NormaOpacitySlotName = "AlphaNormal"; public const string NormaOpacityDisplaySlotName = "Normal Opacity"; public const int NormaOpacitySlotId = 4; public const string MetallicSlotName = "Metallic"; public const int MetallicSlotId = 5; public const string AmbientOcclusionSlotName = "Occlusion"; public const string AmbientOcclusionDisplaySlotName = "Ambient Occlusion"; public const int AmbientOcclusionSlotId = 6; public const string SmoothnessSlotName = "Smoothness"; public const int SmoothnessSlotId = 7; public const string MAOSOpacitySlotName = "MAOSOpacity"; public const string MAOSOpacityDisplaySlotName = "MAOS Opacity"; public const int MAOSOpacitySlotId = 8; public const string EmissionSlotName = "Emission"; public const string EmissionDisplaySlotName = "Emission"; public const int EmissionSlotId = 9; // Just for convenience of doing simple masks. We could run out of bits of course. [Flags] enum SlotMask { None = 0, Position = 1 << PositionSlotId, Albedo = 1 << AlbedoSlotId, AlphaAlbedo = 1 << BaseColorOpacitySlotId, Normal = 1 << NormalSlotId, AlphaNormal = 1 << NormaOpacitySlotId, Metallic = 1 << MetallicSlotId, Occlusion = 1 << AmbientOcclusionSlotId, Smoothness = 1 << SmoothnessSlotId, AlphaMAOS = 1 << MAOSOpacitySlotId, Emission = 1 << EmissionSlotId } const SlotMask decalParameter = SlotMask.Position | SlotMask.Albedo | SlotMask.AlphaAlbedo | SlotMask.Normal | SlotMask.AlphaNormal | SlotMask.Metallic | SlotMask.Occlusion | SlotMask.Smoothness | SlotMask.AlphaMAOS | SlotMask.Emission; // This could also be a simple array. For now, catch any mismatched data. SlotMask GetActiveSlotMask() { return decalParameter; } bool MaterialTypeUsesSlotMask(SlotMask mask) { SlotMask activeMask = GetActiveSlotMask(); return (activeMask & mask) != 0; } public DecalMasterNode() { UpdateNodeAfterDeserialization(); } public override string documentationURL { get { return null; } } public sealed override void UpdateNodeAfterDeserialization() { base.UpdateNodeAfterDeserialization(); name = "Decal Master"; List<int> validSlots = new List<int>(); // Position if (MaterialTypeUsesSlotMask(SlotMask.Position)) { AddSlot(new PositionMaterialSlot(PositionSlotId, PositionSlotName, PositionSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); validSlots.Add(PositionSlotId); } // Albedo if (MaterialTypeUsesSlotMask(SlotMask.Albedo)) { AddSlot(new ColorRGBMaterialSlot(AlbedoSlotId, AlbedoDisplaySlotName, AlbedoSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); validSlots.Add(AlbedoSlotId); } // AlphaAlbedo if (MaterialTypeUsesSlotMask(SlotMask.AlphaAlbedo)) { AddSlot(new Vector1MaterialSlot(BaseColorOpacitySlotId, BaseColorOpacityDisplaySlotName, BaseColorOpacitySlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); validSlots.Add(BaseColorOpacitySlotId); } // Normal if (MaterialTypeUsesSlotMask(SlotMask.Normal)) { AddSlot(new NormalMaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); validSlots.Add(NormalSlotId); } // AlphaNormal if (MaterialTypeUsesSlotMask(SlotMask.AlphaNormal)) { AddSlot(new Vector1MaterialSlot(NormaOpacitySlotId, NormaOpacityDisplaySlotName, NormaOpacitySlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); validSlots.Add(NormaOpacitySlotId); } // Metal if (MaterialTypeUsesSlotMask(SlotMask.Metallic)) { AddSlot(new Vector1MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); validSlots.Add(MetallicSlotId); } // Ambient Occlusion if (MaterialTypeUsesSlotMask(SlotMask.Occlusion)) { AddSlot(new Vector1MaterialSlot(AmbientOcclusionSlotId, AmbientOcclusionDisplaySlotName, AmbientOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); validSlots.Add(AmbientOcclusionSlotId); } // Smoothness if (MaterialTypeUsesSlotMask(SlotMask.Smoothness)) { AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); validSlots.Add(SmoothnessSlotId); } // Alpha MAOS if (MaterialTypeUsesSlotMask(SlotMask.AlphaMAOS)) { AddSlot(new Vector1MaterialSlot(MAOSOpacitySlotId, MAOSOpacityDisplaySlotName, MAOSOpacitySlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); validSlots.Add(MAOSOpacitySlotId); } // Alpha MAOS if (MaterialTypeUsesSlotMask(SlotMask.Emission)) { AddSlot(new ColorRGBMaterialSlot(EmissionSlotId, EmissionDisplaySlotName, EmissionSlotName, SlotType.Input, Color.black, ColorMode.HDR, ShaderStageCapability.Fragment)); validSlots.Add(EmissionSlotId); } RemoveSlotsNameNotMatching(validSlots, true); } protected override VisualElement CreateCommonSettingsElement() { return new DecalSettingsView(this); } public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) { List<MaterialSlot> slots = new List<MaterialSlot>(); GetSlots(slots); List<MaterialSlot> validSlots = new List<MaterialSlot>(); for (int i = 0; i < slots.Count; i++) { if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) continue; validSlots.Add(slots[i]); } return validSlots.OfType<IMayRequireNormal>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); } public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) { List<MaterialSlot> slots = new List<MaterialSlot>(); GetSlots(slots); List<MaterialSlot> validSlots = new List<MaterialSlot>(); for (int i = 0; i < slots.Count; i++) { if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) continue; validSlots.Add(slots[i]); } return validSlots.OfType<IMayRequireTangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); } public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) { List<MaterialSlot> slots = new List<MaterialSlot>(); GetSlots(slots); List<MaterialSlot> validSlots = new List<MaterialSlot>(); for (int i = 0; i < slots.Count; i++) { if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) continue; validSlots.Add(slots[i]); } return validSlots.OfType<IMayRequirePosition>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); } public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) { Vector1ShaderProperty drawOrder = new Vector1ShaderProperty(); drawOrder.overrideReferenceName = "_DrawOrder"; drawOrder.displayName = "Draw Order"; drawOrder.floatType = FloatType.Integer; drawOrder.value = 0; collector.AddShaderProperty(drawOrder); Vector1ShaderProperty decalMeshDepthBias = new Vector1ShaderProperty(); decalMeshDepthBias.overrideReferenceName = "_DecalMeshDepthBias"; decalMeshDepthBias.displayName = "DecalMesh DepthBias"; decalMeshDepthBias.floatType = FloatType.Default; decalMeshDepthBias.value = 0; collector.AddShaderProperty(decalMeshDepthBias); base.CollectShaderProperties(collector, generationMode); } [SerializeField] bool m_AffectsMetal = true; public ToggleData affectsMetal { get { return new ToggleData(m_AffectsMetal); } set { if (m_AffectsMetal == value.isOn) return; m_AffectsMetal = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_AffectsAO = true; public ToggleData affectsAO { get { return new ToggleData(m_AffectsAO); } set { if (m_AffectsAO == value.isOn) return; m_AffectsAO = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_AffectsSmoothness = true; public ToggleData affectsSmoothness { get { return new ToggleData(m_AffectsSmoothness); } set { if (m_AffectsSmoothness == value.isOn) return; m_AffectsSmoothness = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_AffectsAlbedo = true; public ToggleData affectsAlbedo { get { return new ToggleData(m_AffectsAlbedo); } set { if (m_AffectsAlbedo == value.isOn) return; m_AffectsAlbedo = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_AffectsNormal = true; public ToggleData affectsNormal { get { return new ToggleData(m_AffectsNormal); } set { if (m_AffectsNormal == value.isOn) return; m_AffectsNormal = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_AffectsEmission = true; public ToggleData affectsEmission { get { return new ToggleData(m_AffectsEmission); } set { if (m_AffectsEmission == value.isOn) return; m_AffectsEmission = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] int m_DrawOrder; public int drawOrder { get { return m_DrawOrder; } set { if (m_DrawOrder == value) return; m_DrawOrder = value; Dirty(ModificationScope.Graph); } } } }
using System; using System.Diagnostics; using System.IO; using Org.BouncyCastle.Crypto; namespace Org.BouncyCastle.Crypto.IO { public class CipherStream : Stream { internal Stream stream; internal IBufferedCipher inCipher, outCipher; private byte[] mInBuf; private int mInPos; private bool inStreamEnded; public CipherStream( Stream stream, IBufferedCipher readCipher, IBufferedCipher writeCipher) { this.stream = stream; if (readCipher != null) { this.inCipher = readCipher; mInBuf = null; } if (writeCipher != null) { this.outCipher = writeCipher; } } public IBufferedCipher ReadCipher { get { return inCipher; } } public IBufferedCipher WriteCipher { get { return outCipher; } } public override int ReadByte() { if (inCipher == null) return stream.ReadByte(); if (mInBuf == null || mInPos >= mInBuf.Length) { if (!FillInBuf()) return -1; } return mInBuf[mInPos++]; } public override int Read( byte[] buffer, int offset, int count) { if (inCipher == null) return stream.Read(buffer, offset, count); int num = 0; while (num < count) { if (mInBuf == null || mInPos >= mInBuf.Length) { if (!FillInBuf()) break; } int numToCopy = System.Math.Min(count - num, mInBuf.Length - mInPos); Array.Copy(mInBuf, mInPos, buffer, offset + num, numToCopy); mInPos += numToCopy; num += numToCopy; } return num; } private bool FillInBuf() { if (inStreamEnded) return false; mInPos = 0; do { mInBuf = ReadAndProcessBlock(); } while (!inStreamEnded && mInBuf == null); return mInBuf != null; } private byte[] ReadAndProcessBlock() { int blockSize = inCipher.GetBlockSize(); int readSize = (blockSize == 0) ? 256 : blockSize; byte[] block = new byte[readSize]; int numRead = 0; do { int count = stream.Read(block, numRead, block.Length - numRead); if (count < 1) { inStreamEnded = true; break; } numRead += count; } while (numRead < block.Length); Debug.Assert(inStreamEnded || numRead == block.Length); byte[] bytes = inStreamEnded ? inCipher.DoFinal(block, 0, numRead) : inCipher.ProcessBytes(block); if (bytes != null && bytes.Length == 0) { bytes = null; } return bytes; } public override void Write( byte[] buffer, int offset, int count) { Debug.Assert(buffer != null); Debug.Assert(0 <= offset && offset <= buffer.Length); Debug.Assert(count >= 0); int end = offset + count; Debug.Assert(0 <= end && end <= buffer.Length); if (outCipher == null) { stream.Write(buffer, offset, count); return; } byte[] data = outCipher.ProcessBytes(buffer, offset, count); if (data != null) { stream.Write(data, 0, data.Length); } } public override void WriteByte( byte b) { if (outCipher == null) { stream.WriteByte(b); return; } byte[] data = outCipher.ProcessByte(b); if (data != null) { stream.Write(data, 0, data.Length); } } public override bool CanRead { get { return stream.CanRead && (inCipher != null); } } public override bool CanWrite { get { return stream.CanWrite && (outCipher != null); } } public override bool CanSeek { get { return false; } } public sealed override long Length { get { throw new NotSupportedException(); } } public sealed override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override void Close() { if (outCipher != null) { byte[] data = outCipher.DoFinal(); stream.Write(data, 0, data.Length); stream.Flush(); } stream.Close(); } public override void Flush() { // Note: outCipher.DoFinal is only called during Close() stream.Flush(); } public sealed override long Seek( long offset, SeekOrigin origin) { throw new NotSupportedException(); } public sealed override void SetLength( long length) { throw new NotSupportedException(); } } }
// 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.Diagnostics.PerformanceCounter.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.Diagnostics { sealed public partial class PerformanceCounter : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize { #region Methods and constructors public void BeginInit() { } public void Close() { } public static void CloseSharedResources() { } public long Decrement() { Contract.Ensures(-9223372036854775807 <= Contract.Result<long>()); return default(long); } protected override void Dispose(bool disposing) { } public void EndInit() { } public long Increment() { Contract.Ensures(-9223372036854775807 <= Contract.Result<long>()); return default(long); } public long IncrementBy(long value) { Contract.Ensures(-9223372036854775807 <= Contract.Result<long>()); return default(long); } public CounterSample NextSample() { return default(CounterSample); } public float NextValue() { return default(float); } public PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName) { } public PerformanceCounter() { } public PerformanceCounter(string categoryName, string counterName) { } public PerformanceCounter(string categoryName, string counterName, bool readOnly) { } public PerformanceCounter(string categoryName, string counterName, string instanceName) { } public PerformanceCounter(string categoryName, string counterName, string instanceName, bool readOnly) { } public void RemoveInstance() { } #endregion #region Properties and indexers public string CategoryName { get { return default(string); } set { } } public string CounterHelp { get { return default(string); } } public string CounterName { get { return default(string); } set { } } public PerformanceCounterType CounterType { get { return default(PerformanceCounterType); } } public PerformanceCounterInstanceLifetime InstanceLifetime { get { return default(PerformanceCounterInstanceLifetime); } set { } } public string InstanceName { get { return default(string); } set { } } public string MachineName { get { return default(string); } set { } } public long RawValue { get { Contract.Ensures(-9223372036854775807 <= Contract.Result<long>()); return default(long); } set { } } public bool ReadOnly { get { return default(bool); } set { } } #endregion #region Fields public static int DefaultFileMappingSize; #endregion } }
using UnityEngine; using System.Collections; public class MeshCombineUtility { public struct MeshInstance { public Mesh mesh; public int subMeshIndex; public Matrix4x4 transform; } public static Mesh Combine (MeshInstance[] combines, bool generateStrips) { int vertexCount = 0; int triangleCount = 0; int stripCount = 0; foreach( MeshInstance combine in combines ) { if (combine.mesh) { vertexCount += combine.mesh.vertexCount; if (generateStrips) { // int curStripCount = combine.mesh.GetTriangleStrip(combine.subMeshIndex).Length; int curStripCount = combine.mesh.GetTriangles(combine.subMeshIndex).Length; if (curStripCount != 0) { if( stripCount != 0 ) { if ((stripCount & 1) == 1 ) stripCount += 3; else stripCount += 2; } stripCount += curStripCount; } else { generateStrips = false; } } } } // Precomputed how many triangles we need instead if (!generateStrips) { foreach( MeshInstance combine in combines ) { if (combine.mesh) { triangleCount += combine.mesh.GetTriangles(combine.subMeshIndex).Length; } } } Vector3[] vertices = new Vector3[vertexCount] ; Vector3[] normals = new Vector3[vertexCount] ; Vector4[] tangents = new Vector4[vertexCount] ; Vector2[] uv = new Vector2[vertexCount]; Vector2[] uv1 = new Vector2[vertexCount]; Color[] colors = new Color[vertexCount]; int[] triangles = new int[triangleCount]; int[] strip = new int[stripCount]; int offset; offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) Copy(combine.mesh.vertexCount, combine.mesh.vertices, vertices, ref offset, combine.transform); } offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) { Matrix4x4 invTranspose = combine.transform; invTranspose = invTranspose.inverse.transpose; CopyNormal(combine.mesh.vertexCount, combine.mesh.normals, normals, ref offset, invTranspose); } } offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) { Matrix4x4 invTranspose = combine.transform; invTranspose = invTranspose.inverse.transpose; CopyTangents(combine.mesh.vertexCount, combine.mesh.tangents, tangents, ref offset, invTranspose); } } offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) Copy(combine.mesh.vertexCount, combine.mesh.uv, uv, ref offset); } offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) Copy(combine.mesh.vertexCount, combine.mesh.uv2, uv1, ref offset); } offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) CopyColors(combine.mesh.vertexCount, combine.mesh.colors, colors, ref offset); } int triangleOffset=0; int stripOffset=0; int vertexOffset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) { if (generateStrips) { //int[] inputstrip = combine.mesh.GetTriangleStrip(combine.subMeshIndex); int[] inputstrip = combine.mesh.GetTriangles(combine.subMeshIndex); if (stripOffset != 0) { if ((stripOffset & 1) == 1) { strip[stripOffset+0] = strip[stripOffset-1]; strip[stripOffset+1] = inputstrip[0] + vertexOffset; strip[stripOffset+2] = inputstrip[0] + vertexOffset; stripOffset+=3; } else { strip[stripOffset+0] = strip[stripOffset-1]; strip[stripOffset+1] = inputstrip[0] + vertexOffset; stripOffset+=2; } } for (int i=0;i<inputstrip.Length;i++) { strip[i+stripOffset] = inputstrip[i] + vertexOffset; } stripOffset += inputstrip.Length; } else { int[] inputtriangles = combine.mesh.GetTriangles(combine.subMeshIndex); for (int i=0;i<inputtriangles.Length;i++) { triangles[i+triangleOffset] = inputtriangles[i] + vertexOffset; } triangleOffset += inputtriangles.Length; } vertexOffset += combine.mesh.vertexCount; } } Mesh mesh = new Mesh(); mesh.name = "Combined Mesh"; mesh.vertices = vertices; mesh.normals = normals; mesh.colors = colors; mesh.uv = uv; mesh.uv2 = uv1; mesh.tangents = tangents; if (generateStrips) //mesh.SetTriangleStrip(strip, 0); mesh.SetTriangles(strip,0); else mesh.triangles = triangles; return mesh; } static void Copy (int vertexcount, Vector3[] src, Vector3[] dst, ref int offset, Matrix4x4 transform) { for (int i=0;i<src.Length;i++) dst[i+offset] = transform.MultiplyPoint(src[i]); offset += vertexcount; } static void CopyNormal (int vertexcount, Vector3[] src, Vector3[] dst, ref int offset, Matrix4x4 transform) { for (int i=0;i<src.Length;i++) dst[i+offset] = transform.MultiplyVector(src[i]).normalized; offset += vertexcount; } static void Copy (int vertexcount, Vector2[] src, Vector2[] dst, ref int offset) { for (int i=0;i<src.Length;i++) dst[i+offset] = src[i]; offset += vertexcount; } static void CopyColors (int vertexcount, Color[] src, Color[] dst, ref int offset) { for (int i=0;i<src.Length;i++) dst[i+offset] = src[i]; offset += vertexcount; } static void CopyTangents (int vertexcount, Vector4[] src, Vector4[] dst, ref int offset, Matrix4x4 transform) { for (int i=0;i<src.Length;i++) { Vector4 p4 = src[i]; Vector3 p = new Vector3(p4.x, p4.y, p4.z); p = transform.MultiplyVector(p).normalized; dst[i+offset] = new Vector4(p.x, p.y, p.z, p4.w); } offset += vertexcount; } }
using Signum.Engine.Maps; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; namespace Signum.Engine { public static class Synchronizer { public static void Synchronize<K, N, O>( Dictionary<K, N> newDictionary, Dictionary<K, O> oldDictionary, Action<K, N>? createNew, Action<K, O>? removeOld, Action<K, N, O>? merge) where K : notnull { HashSet<K> keys = new HashSet<K>(); keys.UnionWith(oldDictionary.Keys); keys.UnionWith(newDictionary.Keys); foreach (var key in keys) { var oldExists = oldDictionary.TryGetValue(key, out var oldVal); var newExists = newDictionary.TryGetValue(key, out var newVal); if (!oldExists) { createNew?.Invoke(key, newVal!); } else if (!newExists) { removeOld?.Invoke(key, oldVal!); } else { merge?.Invoke(key, newVal!, oldVal!); } } } public static void SynchronizeProgressForeach<K, N, O>( Dictionary<K, N> newDictionary, Dictionary<K, O> oldDictionary, Action<K, N>? createNew, Action<K, O>? removeOld, Action<K, N, O>? merge, bool showProgress = true, bool transactional = true) where K : notnull { HashSet<K> keys = new HashSet<K>(); keys.UnionWith(oldDictionary.Keys); keys.UnionWith(newDictionary.Keys); keys.ProgressForeach(key => key.ToString()!, key => { if (oldDictionary.TryGetValue(key, out var oldVal)) { if (newDictionary.TryGetValue(key, out var newVal)) merge?.Invoke(key, newVal, oldVal); else removeOld?.Invoke(key, oldVal); } else { if (newDictionary.TryGetValue(key, out var newVal)) createNew?.Invoke(key, newVal); else throw new InvalidOperationException("Unexpected key: " + key); } }, showProgress: showProgress, transactional: transactional); } public static void SynchronizeReplacing<N, O>( Replacements replacements, string replacementsKey, Dictionary<string, N> newDictionary, Dictionary<string, O> oldDictionary, Action<string, N>? createNew, Action<string, O>? removeOld, Action<string, N, O>? merge) { replacements.AskForReplacements( oldDictionary.Keys.ToHashSet(), newDictionary.Keys.ToHashSet(), replacementsKey); var repOldDictionary = replacements.ApplyReplacementsToOld(oldDictionary, replacementsKey); HashSet<string> set = new HashSet<string>(); set.UnionWith(repOldDictionary.Keys); set.UnionWith(newDictionary.Keys); foreach (var key in set) { if (repOldDictionary.TryGetValue(key, out var oldVal)) { if (newDictionary.TryGetValue(key, out var newVal)) merge?.Invoke(key, newVal, oldVal); else removeOld?.Invoke(key, oldVal); } else { if (newDictionary.TryGetValue(key, out var newVal)) createNew?.Invoke(key, newVal); else throw new InvalidOperationException("Unexpected key: " + key); } } } public static SqlPreCommand? SynchronizeScript<K, N, O>( Spacing spacing, Dictionary<K, N> newDictionary, Dictionary<K, O> oldDictionary, Func<K, N, SqlPreCommand?>? createNew, Func<K, O, SqlPreCommand?>? removeOld, Func<K, N, O, SqlPreCommand?>? mergeBoth) where O : class where N : class where K : notnull { HashSet<K> set = new HashSet<K>(); set.UnionWith(newDictionary.Keys); set.UnionWith(oldDictionary.Keys); return set.Select(key => { var newVal = newDictionary.TryGetC(key); var oldVal = oldDictionary.TryGetC(key); if (newVal == null) return removeOld == null ? null : removeOld(key, oldVal!); if (oldVal == null) return createNew == null ? null : createNew(key, newVal); return mergeBoth == null ? null : mergeBoth(key, newVal, oldVal); }).Combine(spacing); } public static SqlPreCommand? SynchronizeScriptReplacing<N, O>( Replacements replacements, string replacementsKey, Spacing spacing, Dictionary<string, N> newDictionary, Dictionary<string, O> oldDictionary, Func<string, N, SqlPreCommand?>? createNew, Func<string, O, SqlPreCommand?>? removeOld, Func<string, N, O, SqlPreCommand?>? mergeBoth) where O : class where N : class { replacements.AskForReplacements( oldDictionary.Keys.ToHashSet(), newDictionary.Keys.ToHashSet(), replacementsKey); var repOldDictionary = replacements.ApplyReplacementsToOld(oldDictionary, replacementsKey); return SynchronizeScript(spacing, newDictionary, repOldDictionary, createNew, removeOld, mergeBoth); } public static IDisposable? UseOldTableName(Table table, Replacements replacements) { string? fullName = replacements.TryGetC(Replacements.KeyTablesInverse)?.TryGetC(table.Name.ToString()); if (fullName == null) return null; ObjectName realName = table.Name; table.Name = ObjectName.Parse(fullName, Schema.Current.Settings.IsPostgres); return new Disposable(() => table.Name = realName); } } public class Replacements : Dictionary<string, Dictionary<string, string>> { public static string KeyTables = "Tables"; public static string KeyTablesInverse = "TablesInverse"; public static string KeyColumnsForTable(string tableName) { return "Columns:" + tableName; } public static string KeyEnumsForTable(string tableName) { return "Enums:" + tableName; } public bool Interactive = true; public bool SchemaOnly = false; public string? ReplaceDatabaseName = null; public IDisposable? WithReplacedDatabaseName() { if (ReplaceDatabaseName == null) return null; return ObjectName.OverrideOptions(new ObjectNameOptions { DatabaseNameReplacement = ReplaceDatabaseName }); } public string Apply(string replacementsKey, string textToReplace) { Dictionary<string, string>? repDic = this.TryGetC(replacementsKey); return repDic?.TryGetC(textToReplace) ?? textToReplace; } public virtual Dictionary<string, O> ApplyReplacementsToOld<O>(Dictionary<string, O> oldDictionary, string replacementsKey) { if (!this.ContainsKey(replacementsKey)) return oldDictionary; Dictionary<string, string> replacements = this[replacementsKey]; return oldDictionary.SelectDictionary(a => replacements.TryGetC(a) ?? a, v => v); } public virtual Dictionary<string, O> ApplyReplacementsToNew<O>(Dictionary<string, O> newDictionary, string replacementsKey) { if (!this.ContainsKey(replacementsKey)) return newDictionary; Dictionary<string, string> replacements = this[replacementsKey].Inverse(); return newDictionary.SelectDictionary(a => replacements.TryGetC(a) ?? a, v => v); } public virtual void AskForReplacements( HashSet<string> oldKeys, HashSet<string> newKeys, string replacementsKey) { List<string> oldOnly = oldKeys.Where(k => !newKeys.Contains(k)).ToList(); List<string> newOnly = newKeys.Where(k => !oldKeys.Contains(k)).ToList(); if (oldOnly.Count == 0 || newOnly.Count == 0) return; Dictionary<string, string> replacements = this.TryGetC(replacementsKey) ?? new Dictionary<string, string>(); if (replacements.Any()) { var toRemove = replacements.Where(a => oldOnly.Contains(a.Key) && newOnly.Contains(a.Value)).ToList(); foreach (var kvp in toRemove) { oldOnly.Remove(kvp.Key); newOnly.Remove(kvp.Value); } } if (oldOnly.Count == 0 || newOnly.Count == 0) return; StringDistance sd = new StringDistance(); Dictionary<string, Dictionary<string, float>> distances = oldOnly.ToDictionary(o => o, o => newOnly.ToDictionary(n => n, n => { return Distance(sd, o, n); })); new Dictionary<string, string>(); while (oldOnly.Count > 0 && newOnly.Count > 0) { var oldDist = distances.WithMin(kvp => kvp.Value.Values.Min()); var alternatives = oldDist.Value.OrderBy(a => a.Value).Select(a => a.Key).ToList(); Selection selection = SelectInteractive(oldDist.Key, alternatives, replacementsKey, Interactive); oldOnly.Remove(selection.OldValue); distances.Remove(selection.OldValue); if (selection.NewValue != null) { replacements.Add(selection.OldValue, selection.NewValue); newOnly.Remove(selection.NewValue); foreach (var dic in distances.Values) dic.Remove(selection.NewValue); } } if (replacements.Count != 0 && !this.ContainsKey(replacementsKey)) this.GetOrCreate(replacementsKey).SetRange(replacements); } static float Distance(StringDistance sd, string o, string n) { return sd.LevenshteinDistance(o, n, weight: c => c.Type == StringDistance.ChoiceType.Substitute ? 2 : 1); } public string? SelectInteractive(string oldValue, ICollection<string> newValues, string replacementsKey, StringDistance sd) { if (newValues.Contains(oldValue)) return oldValue; var rep = this.TryGetC(replacementsKey)?.TryGetC(oldValue); if (rep != null && newValues.Contains(rep)) return rep; var dic = newValues.ToDictionary(a => a, a => Distance(sd, oldValue, a)); Selection sel = SelectInteractive(oldValue, dic.OrderBy(a => a.Value).Select(a => a.Key).ToList(), replacementsKey, Interactive); if (sel.NewValue != null) { this.GetOrCreate(replacementsKey).Add(sel.OldValue, sel.NewValue); } return sel.NewValue; } public class AutoReplacementContext { public string ReplacementKey; public string OldValue; public List<string>? NewValues; public AutoReplacementContext(string replacementKey, string oldValue, List<string>? newValues) { ReplacementKey = replacementKey; OldValue = oldValue; NewValues = newValues; } } public static Func<AutoReplacementContext, Selection?>? AutoReplacement; public static Action<string , string , string? >? ResponseRecorder;// replacementsKey,oldValue,newValue //public static Dictionary<String, Replacements.Selection>? cases ; private static Selection SelectInteractive(string oldValue, List<string> newValues, string replacementsKey, bool interactive) { if (AutoReplacement != null) { Selection? selection = AutoReplacement(new AutoReplacementContext(replacementsKey, oldValue, newValues)); if (selection != null) { SafeConsole.WriteLineColor(ConsoleColor.DarkGray, "AutoReplacement:"); SafeConsole.WriteLineColor(ConsoleColor.DarkRed, " OLD " + selection.Value.OldValue); SafeConsole.WriteLineColor(ConsoleColor.DarkGreen, " NEW " + selection.Value.NewValue); return selection.Value; } } if (!interactive) throw new InvalidOperationException($"Unable to ask for renames for '{oldValue}' (in {replacementsKey}) without interactive Console. Please use your Terminal application"); int startingIndex = 0; Console.WriteLine(); SafeConsole.WriteLineColor(ConsoleColor.White, " '{0}' has been renamed in {1}?".FormatWith(oldValue, replacementsKey)); retry: int maxElement = Console.LargestWindowHeight - 7; int i = 0; foreach (var v in newValues.Skip(startingIndex).Take(maxElement).ToList()) { SafeConsole.WriteColor(ConsoleColor.White, "{0,2}: ", i); SafeConsole.WriteColor(ConsoleColor.Gray, v); if (i == 0) SafeConsole.WriteColor(ConsoleColor.White, " (hit [Enter])"); Console.WriteLine(); i++; } SafeConsole.WriteColor(ConsoleColor.White, " n: ", i); SafeConsole.WriteColor(ConsoleColor.Gray, "No rename, '{0}' was removed", oldValue); Console.WriteLine(); int remaining = newValues.Count - startingIndex - maxElement; if (remaining > 0) { SafeConsole.WriteColor(ConsoleColor.White, " +: ", i); SafeConsole.WriteColor(ConsoleColor.Gray, "Show more values ({0} remaining)", remaining); Console.WriteLine(); } while (true) { //var key = replacementsKey + "." + oldValue; //string? answer = cases!.ContainsKey(key) ? cases[key].NewValue: Console.ReadLine(); string answer = Console.ReadLine(); if (answer == null) answer = "n"; answer = answer.ToLower(); Selection? response = null; if (answer == "+" && remaining > 0) { startingIndex += maxElement; goto retry; } if (answer == "n") response= new Selection(oldValue, null); if (answer == "") response= new Selection(oldValue, newValues[0]); if (int.TryParse(answer, out int option)) response= new Selection(oldValue, newValues[option]); if (response != null) { if (ResponseRecorder != null) ResponseRecorder.Invoke(replacementsKey, response.Value.OldValue, response.Value.NewValue); return response.Value; } Console.WriteLine("Error"); } } public struct Selection { /// <param name="newValue">Null for removed</param> public Selection(string oldValue, string? newValue) { this.OldValue = oldValue; this.NewValue = newValue; } public readonly string OldValue; public readonly string? NewValue; } } }
using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using Windows.ApplicationModel; using Windows.Devices.Bluetooth.Advertisement; using Windows.Foundation; using Windows.Storage.Streams; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using BeaconTracker; using BeaconTracker.Models; using SDKTemplate; namespace BluetoothAdvertisement { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario6_ActiveAggregatingWatcher : Page { private readonly Tracker _tracker; // The Bluetooth LE advertisement watcher class is used to control and customize Bluetooth LE scanning. private readonly BluetoothLEAdvertisementWatcher watcher; private Timer _timer; // A pointer back to the main page is required to display status messages. private MainPage rootPage; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public Scenario6_ActiveAggregatingWatcher() { InitializeComponent(); _tracker = new Tracker(); _timer = new Timer(PrintUpdatedBeaconInfo, _tracker, 0, 30000); // Create and initialize a new watcher instance. watcher = new BluetoothLEAdvertisementWatcher(); // Begin of watcher configuration. Configure the advertisement filter to look for the data advertised by the publisher // in Scenario 2 or 4. You need to run Scenario 2 on another Windows platform within proximity of this one for Scenario 1 to // take effect. The APIs shown in this Scenario are designed to operate only if the App is in the foreground. For background // watcher operation, please refer to Scenario 3. // Please comment out this following section (watcher configuration) if you want to remove all filters. By not specifying // any filters, all advertisements received will be notified to the App through the event handler. You should comment out the following // section if you do not have another Windows platform to run Scenario 2 alongside Scenario 1 or if you want to scan for // all LE advertisements around you. // For determining the filter restrictions programatically across APIs, use the following properties: // MinSamplingInterval, MaxSamplingInterval, MinOutOfRangeTimeout, MaxOutOfRangeTimeout // Part 1A: Configuring the advertisement filter to watch for a particular advertisement payload // First, let create a manufacturer data section we wanted to match for. These are the same as the one // created in Scenario 2 and 4. var manufacturerData = new BluetoothLEManufacturerData(); // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE manufacturerData.CompanyId = 349; //Estimote 349 (Use for stamps) manufacturerData.CompanyId = 76; //Apple 76 (Use for the old Estimote iBeacon compatible beacons) // Finally set the data payload within the manufacturer-specific section // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian) //var writer = new DataWriter(); //writer.WriteUInt16(0x1234); // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception. //manufacturerData.Data = writer.DetachBuffer(); // Add the manufacturer data to the advertisement filter on the watcher: watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData); // Part 1B: Configuring the signal strength filter for proximity scenarios // Configure the signal strength filter to only propagate events when in-range // Please adjust these values if you cannot receive any advertisement // Set the in-range threshold to -70dBm. This means advertisements with RSSI >= -70dBm // will start to be considered "in-range". watcher.SignalStrengthFilter.InRangeThresholdInDBm = -70; // Set the out-of-range threshold to -75dBm (give some buffer). Used in conjunction with OutOfRangeTimeout // to determine when an advertisement is no longer considered "in-range" //watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -75; // Set the out-of-range timeout to be 2 seconds. Used in conjunction with OutOfRangeThresholdInDBm // to determine when an advertisement is no longer considered "in-range" //watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(2000); // By default, the sampling interval is set to zero, which means there is no sampling and all // the advertisement received is returned in the Received event // End of watcher configuration. There is no need to comment out any code beyond this point. } private void PrintUpdatedBeaconInfo(object state) { var readings = ((Tracker)state)?.GetAllReadings().ToImmutableList(); var updatedInfo = string.Join(Environment.NewLine, readings); var asyncTask = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ReceivedAdvertisementListBox.Items?.Add(updatedInfo)); while(asyncTask.Status != AsyncStatus.Completed) { } } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// /// We will enable/disable parts of the UI if the device doesn't support it. /// </summary> /// <param name="eventArgs">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; // Attach a handler to process the received advertisement. // The watcher cannot be started without a Received handler attached watcher.Received += OnAdvertisementReceived; // Attach a handler to process watcher stopping due to various conditions, // such as the Bluetooth radio turning off or the Stop method was called watcher.Stopped += OnAdvertisementWatcherStopped; // Attach handlers for suspension to stop the watcher when the App is suspended. App.Current.Suspending += App_Suspending; App.Current.Resuming += App_Resuming; rootPage.NotifyUser("Press Run to start watcher.", NotifyType.StatusMessage); } /// <summary> /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame. /// </summary> /// <param name="e"> /// Event data that can be examined by overriding code. The event data is representative /// of the navigation that will unload the current Page unless canceled. The /// navigation can potentially be canceled by setting Cancel. /// </param> protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { // Remove local suspension handlers from the App since this page is no longer active. App.Current.Suspending -= App_Suspending; App.Current.Resuming -= App_Resuming; // Make sure to stop the watcher when leaving the context. Even if the watcher is not stopped, // scanning will be stopped automatically if the watcher is destroyed. watcher.Stop(); // Always unregister the handlers to release the resources to prevent leaks. watcher.Received -= OnAdvertisementReceived; watcher.Stopped -= OnAdvertisementWatcherStopped; rootPage.NotifyUser("Navigating away. Watcher stopped.", NotifyType.StatusMessage); base.OnNavigatingFrom(e); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void App_Suspending(object sender, SuspendingEventArgs e) { // Make sure to stop the watcher on suspend. watcher.Stop(); // Always unregister the handlers to release the resources to prevent leaks. watcher.Received -= OnAdvertisementReceived; watcher.Stopped -= OnAdvertisementWatcherStopped; rootPage.NotifyUser("App suspending. Watcher stopped.", NotifyType.StatusMessage); } /// <summary> /// Invoked when application execution is being resumed. /// </summary> /// <param name="sender">The source of the resume request.</param> /// <param name="e"></param> private void App_Resuming(object sender, object e) { watcher.Received += OnAdvertisementReceived; watcher.Stopped += OnAdvertisementWatcherStopped; } /// <summary> /// Invoked as an event handler when the Run button is pressed. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private void RunButton_Click(object sender, RoutedEventArgs e) { // Calling watcher start will start the scanning if not already initiated by another client watcher.Start(); rootPage.NotifyUser("Watcher started.", NotifyType.StatusMessage); } /// <summary> /// Invoked as an event handler when the Stop button is pressed. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private void StopButton_Click(object sender, RoutedEventArgs e) { // Stopping the watcher will stop scanning if this is the only client requesting scan watcher.Stop(); rootPage.NotifyUser("Watcher stopped.", NotifyType.StatusMessage); } /// <summary> /// Invoked as an event handler when an advertisement is received. /// </summary> /// <param name="watcher">Instance of watcher that triggered the event.</param> /// <param name="eventArgs">Event data containing information about the advertisement event.</param> private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { // We can obtain various information about the advertisement we just received by accessing // the properties of the EventArgs class // The timestamp of the event DateTimeOffset timestamp = eventArgs.Timestamp; // The type of advertisement BluetoothLEAdvertisementType advertisementType = eventArgs.AdvertisementType; // The received signal strength indicator (RSSI) Int16 rssi = eventArgs.RawSignalStrengthInDBm; // The local name of the advertising device contained within the payload, if any string localName = eventArgs.Advertisement.LocalName; // Check if there are any manufacturer-specific sections. // If there is, print the raw data of the first manufacturer section (if there are multiple). string manufacturerDataString = ""; var manufacturerSections = eventArgs.Advertisement.ManufacturerData; if(manufacturerSections.Count > 0) { // Only print the first one of the list var manufacturerData = manufacturerSections[0]; var data = new byte[manufacturerData.Data.Length]; using(var reader = DataReader.FromBuffer(manufacturerData.Data)) reader.ReadBytes(data); // Print the company ID + the raw data in hex format manufacturerDataString = string.Format("0x{0}: {1}", manufacturerData.CompanyId, BitConverter.ToString(data)); } var eventMessage = $"[{timestamp.ToString("hh\\:mm\\:ss\\.fff")}]: " + $"type={advertisementType}, " + $"rssi={rssi}, " + $"name={localName}, " + $"manufacturerData=[{manufacturerDataString}]"; _tracker.AddBeaconReading(new BeaconReading { Beacon = new Beacon(eventArgs.BluetoothAddress.ToString()) { ManufacturerCode = manufacturerSections[0].CompanyId.ToString() }, MeasurementTime = eventArgs.Timestamp, RawSignalStrengthInDBm = eventArgs.RawSignalStrengthInDBm, RawData = manufacturerDataString, EventMessage = eventMessage }); // Serialize UI update to the main UI thread await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ReceivedAdvertisementListBox.Items?.Add(eventMessage)); } /// <summary> /// Invoked as an event handler when the watcher is stopped or aborted. /// </summary> /// <param name="watcher">Instance of watcher that triggered the event.</param> /// <param name="eventArgs">Event data containing information about why the watcher stopped or aborted.</param> private async void OnAdvertisementWatcherStopped(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementWatcherStoppedEventArgs eventArgs) { // Notify the user that the watcher was stopped await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => rootPage.NotifyUser($"Watcher stopped or aborted: {eventArgs.Error}", NotifyType.StatusMessage)); } } }
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 JwtWebApi.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; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MyWebAPIServer.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Drawing; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Windows.Forms; namespace m { /// <summary> /// Summary description for EditSwitchForm. /// </summary> public class SwitchesForm : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.Button buttonNew; private System.Windows.Forms.Button buttonModify; private System.Windows.Forms.Button buttonDelete; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public SwitchesForm(string strTitle, string strCurrent, StringCollection strc) { // // Required for Windows Form Designer support // InitializeComponent(); // foreach (string str in strc) listBox1.Items.Add(str); listBox1.SelectedIndex = strCurrent == "" ? -1 : listBox1.Items.IndexOf(strCurrent); Text = strTitle; label1.Text = label1.Text.Replace("$1", strTitle); } public Switch GetSelectedSwitch() { if (listBox1.SelectedIndex == -1) return null; SwitchManager swm = ((LevelDoc)DocManager.GetActiveDocument(typeof(LevelDoc))).SwitchManager; return swm[(string)listBox1.SelectedItem]; } static public Switch DoModal(string strTitle, string strCurrent, StringCollection strc) { SwitchesForm frm = new SwitchesForm(strTitle, strCurrent, strc); DialogResult res = frm.ShowDialog(); if (res == DialogResult.Cancel) return null; return frm.GetSelectedSwitch(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.buttonOk = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.listBox1 = new System.Windows.Forms.ListBox(); this.buttonNew = new System.Windows.Forms.Button(); this.buttonModify = new System.Windows.Forms.Button(); this.buttonDelete = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(160, 16); this.label1.TabIndex = 0; this.label1.Text = "Choose one $1:"; // // buttonOk // this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOk.Location = new System.Drawing.Point(184, 8); this.buttonOk.Name = "buttonOk"; this.buttonOk.TabIndex = 2; this.buttonOk.Text = "OK"; this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click); // // buttonCancel // this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(184, 40); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.TabIndex = 2; this.buttonCancel.Text = "Cancel"; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // listBox1 // this.listBox1.Location = new System.Drawing.Point(8, 24); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(168, 173); this.listBox1.Sorted = true; this.listBox1.TabIndex = 3; this.listBox1.DoubleClick += new System.EventHandler(this.listBox1_DoubleClick); // // buttonNew // this.buttonNew.Location = new System.Drawing.Point(184, 96); this.buttonNew.Name = "buttonNew"; this.buttonNew.TabIndex = 4; this.buttonNew.Text = "New..."; this.buttonNew.Click += new System.EventHandler(this.buttonNew_Click); // // buttonModify // this.buttonModify.Location = new System.Drawing.Point(184, 128); this.buttonModify.Name = "buttonModify"; this.buttonModify.TabIndex = 5; this.buttonModify.Text = "Modify..."; this.buttonModify.Click += new System.EventHandler(this.buttonModify_Click); // // buttonDelete // this.buttonDelete.Location = new System.Drawing.Point(184, 160); this.buttonDelete.Name = "buttonDelete"; this.buttonDelete.TabIndex = 6; this.buttonDelete.Text = "Delete"; this.buttonDelete.Click += new System.EventHandler(this.buttonDelete_Click); // // SwitchesForm // this.AcceptButton = this.buttonOk; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(266, 208); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.buttonDelete, this.buttonModify, this.buttonNew, this.listBox1, this.buttonOk, this.label1, this.buttonCancel}); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SwitchesForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "EditSwitchForm"; this.ResumeLayout(false); } #endregion private void buttonOk_Click(object sender, System.EventArgs e) { DialogResult = DialogResult.OK; } private void buttonCancel_Click(object sender, System.EventArgs e) { DialogResult = DialogResult.Cancel; } private void listBox1_DoubleClick(object sender, System.EventArgs e) { DialogResult = DialogResult.OK; } private void buttonNew_Click(object sender, System.EventArgs e) { string str = EditStringForm.DoModal("New Switch", "New switch name:", null); if (str != null) { SwitchManager swm = ((LevelDoc)DocManager.GetActiveDocument(typeof(LevelDoc))).SwitchManager; if (swm[str] == null) { swm.AddSwitch(new Switch(str)); int i = listBox1.Items.Add(str); listBox1.SelectedIndex = i; // UNDONE: doc is modified } } } private void buttonModify_Click(object sender, System.EventArgs e) { string str = (string)listBox1.SelectedItem; if (str == null) return; SwitchManager swm = ((LevelDoc)DocManager.GetActiveDocument(typeof(LevelDoc))).SwitchManager; Switch sw = swm[str]; string strNew = EditStringForm.DoModal("Modify Switch", "New switch name:", str); if (strNew == null) return; if (strNew != str) { sw.Name = strNew; listBox1.Items.Remove(str); int i = listBox1.Items.Add(strNew); listBox1.SelectedIndex = i; // UNDONE: doc is modified } } private void buttonDelete_Click(object sender, System.EventArgs e) { string str = (string)listBox1.SelectedItem; if (str == null) return; SwitchManager swm = ((LevelDoc)DocManager.GetActiveDocument(typeof(LevelDoc))).SwitchManager; Switch sw = swm[str]; swm.RemoveSwitch(sw); listBox1.Items.Remove(str); // UNDONE: doc is modified } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CSharp.RuntimeBinder; using Xunit; using static Dynamic.Operator.Tests.TypeCommon; namespace Dynamic.Operator.Tests { public class ModEqualTypeTests { [Fact] public static void Bool() { dynamic d = true; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); Assert.Throws<RuntimeBinderException>(() => d %= s_byte); Assert.Throws<RuntimeBinderException>(() => d %= s_char); Assert.Throws<RuntimeBinderException>(() => d %= s_decimal); Assert.Throws<RuntimeBinderException>(() => d %= s_double); Assert.Throws<RuntimeBinderException>(() => d %= s_float); Assert.Throws<RuntimeBinderException>(() => d %= s_int); Assert.Throws<RuntimeBinderException>(() => d %= s_long); Assert.Throws<RuntimeBinderException>(() => d %= s_object); Assert.Throws<RuntimeBinderException>(() => d %= s_sbyte); Assert.Throws<RuntimeBinderException>(() => d %= s_short); Assert.Throws<RuntimeBinderException>(() => d %= s_string); Assert.Throws<RuntimeBinderException>(() => d %= s_uint); Assert.Throws<RuntimeBinderException>(() => d %= s_ulong); Assert.Throws<RuntimeBinderException>(() => d %= s_ushort); } [Fact] public static void Byte() { dynamic d = (byte)1; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = (byte)1; d %= s_byte; d = (byte)1; d %= s_char; d = (byte)1; d %= s_decimal; d = (byte)1; d %= s_double; d = (byte)1; d %= s_float; d = (byte)1; d %= s_int; d = (byte)1; d %= s_long; d = (byte)1; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = (byte)1; d %= s_sbyte; d = (byte)1; d %= s_short; d = (byte)1; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = (byte)1; d %= s_uint; d = (byte)1; d %= s_ulong; d = (byte)1; d %= s_ushort; } [Fact] public static void Char() { dynamic d = 'a'; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = 'a'; d %= s_byte; d = 'a'; d %= s_char; d = 'a'; d %= s_decimal; d = 'a'; d %= s_double; d = 'a'; d %= s_float; d = 'a'; d %= s_int; d = 'a'; d %= s_long; d = 'a'; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = 'a'; d %= s_sbyte; d = 'a'; d %= s_short; d = 'a'; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = 'a'; d %= s_uint; d = 'a'; d %= s_ulong; d = 'a'; d %= s_ushort; } [Fact] public static void Decimal() { dynamic d = 10m; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = 10m; d %= s_byte; d = 10m; d %= s_char; d = 10m; d %= s_decimal; d = 10m; Assert.Throws<RuntimeBinderException>(() => d %= s_double); Assert.Throws<RuntimeBinderException>(() => d %= s_float); d = 10m; d %= s_int; d = 10m; d %= s_long; d = 10m; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = 10m; d %= s_sbyte; d = 10m; d %= s_short; d = 10m; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = 10m; d %= s_uint; d = 10m; d %= s_ulong; d = 10m; d %= s_ushort; } [Fact] public static void Double() { dynamic d = 10d; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = 10d; d %= s_byte; d = 10d; d %= s_char; d = 10d; Assert.Throws<RuntimeBinderException>(() => d %= s_decimal); d = 10d; d %= s_double; d = 10d; d %= s_float; d = 10d; d %= s_int; d = 10d; d %= s_long; d = 10d; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = 10d; d %= s_sbyte; d = 10d; d %= s_short; d = 10d; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = 10d; d %= s_uint; d = 10d; d %= s_ulong; d = 10d; d %= s_ushort; } [Fact] public static void Float() { dynamic d = 10f; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = 10f; d %= s_byte; d = 10f; d %= s_char; d = 10f; Assert.Throws<RuntimeBinderException>(() => d %= s_decimal); d = 10f; d %= s_double; d = 10f; d %= s_float; d = 10f; d %= s_int; d = 10f; d %= s_long; d = 10f; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = 10f; d %= s_sbyte; d = 10f; d %= s_short; d = 10f; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = 10f; d %= s_uint; d = 10f; d %= s_ulong; d = 10f; d %= s_ushort; } [Fact] public static void Int() { dynamic d = 10; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = 10; d %= s_byte; d = 10; d %= s_char; d = 10; d %= s_decimal; d = 10; d %= s_double; d = 10; d %= s_float; d = 10; d %= s_int; d = 10; d %= s_long; d = 10; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = 10; d %= s_sbyte; d = 10; d %= s_short; d = 10; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = 10; d %= s_uint; d = 10; Assert.Throws<RuntimeBinderException>(() => d %= s_ulong); d = 10; d %= s_ushort; } [Fact] public static void Long() { dynamic d = 10L; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = 10L; d %= s_byte; d = 10L; d %= s_char; d = 10L; d %= s_decimal; d = 10L; d %= s_double; d = 10L; d %= s_float; d = 10L; d %= s_int; d = 10L; d %= s_long; d = 10L; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = 10L; d %= s_sbyte; d = 10L; d %= s_short; d = 10L; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = 10L; d %= s_uint; d = 10L; Assert.Throws<RuntimeBinderException>(() => d %= s_ulong); d = 10L; d %= s_ushort; } [Fact] public static void Object() { dynamic d = new object(); Assert.Throws<RuntimeBinderException>(() => d %= s_bool); Assert.Throws<RuntimeBinderException>(() => d %= s_byte); Assert.Throws<RuntimeBinderException>(() => d %= s_char); Assert.Throws<RuntimeBinderException>(() => d %= s_decimal); Assert.Throws<RuntimeBinderException>(() => d %= s_double); Assert.Throws<RuntimeBinderException>(() => d %= s_float); Assert.Throws<RuntimeBinderException>(() => d %= s_int); Assert.Throws<RuntimeBinderException>(() => d %= s_long); Assert.Throws<RuntimeBinderException>(() => d %= s_object); Assert.Throws<RuntimeBinderException>(() => d %= s_sbyte); Assert.Throws<RuntimeBinderException>(() => d %= s_short); Assert.Throws<RuntimeBinderException>(() => d %= s_string); Assert.Throws<RuntimeBinderException>(() => d %= s_uint); Assert.Throws<RuntimeBinderException>(() => d %= s_ulong); Assert.Throws<RuntimeBinderException>(() => d %= s_ushort); } [Fact] public static void SByte() { dynamic d = (sbyte)10; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = (sbyte)10; d %= s_byte; d = (sbyte)10; d %= s_char; d = (sbyte)10; d %= s_decimal; d = (sbyte)10; d %= s_double; d = (sbyte)10; d %= s_float; d = (sbyte)10; d %= s_int; d = (sbyte)10; d %= s_long; d = (sbyte)10; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = (sbyte)10; d %= s_sbyte; d = (sbyte)10; d %= s_short; d = (sbyte)10; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = (sbyte)10; d %= s_uint; d = (sbyte)10; Assert.Throws<RuntimeBinderException>(() => d %= s_ulong); d = (sbyte)10; d %= s_ushort; } [Fact] public static void Short() { dynamic d = (short)10; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = (short)10; d %= s_byte; d = (short)10; d %= s_char; d = (short)10; d %= s_decimal; d = (short)10; d %= s_double; d = (short)10; d %= s_float; d = (short)10; d %= s_int; d = (short)10; d %= s_long; d = (short)10; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = (short)10; d %= s_sbyte; d = (short)10; d %= s_short; d = (short)10; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = (short)10; d %= s_uint; d = (short)10; Assert.Throws<RuntimeBinderException>(() => d %= s_ulong); d = (short)10; d %= s_ushort; } [Fact] public static void String() { dynamic d = "a"; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); Assert.Throws<RuntimeBinderException>(() => d %= s_byte); Assert.Throws<RuntimeBinderException>(() => d %= s_char); Assert.Throws<RuntimeBinderException>(() => d %= s_decimal); Assert.Throws<RuntimeBinderException>(() => d %= s_double); Assert.Throws<RuntimeBinderException>(() => d %= s_float); Assert.Throws<RuntimeBinderException>(() => d %= s_int); Assert.Throws<RuntimeBinderException>(() => d %= s_long); Assert.Throws<RuntimeBinderException>(() => d %= s_object); Assert.Throws<RuntimeBinderException>(() => d %= s_sbyte); Assert.Throws<RuntimeBinderException>(() => d %= s_short); Assert.Throws<RuntimeBinderException>(() => d %= s_string); Assert.Throws<RuntimeBinderException>(() => d %= s_uint); Assert.Throws<RuntimeBinderException>(() => d %= s_ulong); Assert.Throws<RuntimeBinderException>(() => d %= s_ushort); } [Fact] public static void UInt() { dynamic d = (uint)10; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = (uint)10; d %= s_byte; d = (uint)10; d %= s_char; d = (uint)10; d %= s_decimal; d = (uint)10; d %= s_double; d = (uint)10; d %= s_float; d = (uint)10; d %= s_int; d = (uint)10; d %= s_long; d = (uint)10; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = (uint)10; d %= s_sbyte; d = (uint)10; d %= s_short; d = (uint)10; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = (uint)10; d %= s_uint; d = (uint)10; d %= s_ulong; d = (uint)10; d %= s_ushort; } [Fact] public static void ULong() { dynamic d = (ulong)10; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = (ulong)10; d %= s_byte; d = (ulong)10; d %= s_char; d = (ulong)10; d %= s_decimal; d = (ulong)10; d %= s_double; d = (ulong)10; d %= s_float; d = (ulong)10; Assert.Throws<RuntimeBinderException>(() => d %= s_int); Assert.Throws<RuntimeBinderException>(() => d %= s_long); Assert.Throws<RuntimeBinderException>(() => d %= s_object); Assert.Throws<RuntimeBinderException>(() => d %= s_sbyte); Assert.Throws<RuntimeBinderException>(() => d %= s_short); Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = (ulong)10; d %= s_uint; d = (ulong)10; d %= s_ulong; d = (ulong)10; d %= s_ushort; } [Fact] public static void UShort() { dynamic d = (ushort)10; Assert.Throws<RuntimeBinderException>(() => d %= s_bool); d = (ushort)10; d %= s_byte; d = (ushort)10; d %= s_char; d = (ushort)10; d %= s_decimal; d = (ushort)10; d %= s_double; d = (ushort)10; d %= s_float; d = (ushort)10; d %= s_int; d = (ushort)10; d %= s_long; d = (ushort)10; Assert.Throws<RuntimeBinderException>(() => d %= s_object); d = (ushort)10; d %= s_sbyte; d = (ushort)10; d %= s_short; d = (ushort)10; Assert.Throws<RuntimeBinderException>(() => d %= s_string); d = (ushort)10; d %= s_uint; d = (ushort)10; d %= s_ulong; d = (ushort)10; d %= s_ushort; } } }
using System; using Avalonia.Input; using Avalonia.Layout; namespace Avalonia.Controls { /// <summary> /// A panel that displays child controls at arbitrary locations. /// </summary> /// <remarks> /// Unlike other <see cref="Panel"/> implementations, the <see cref="Canvas"/> doesn't lay out /// its children in any particular layout. Instead, the positioning of each child control is /// defined by the <code>Canvas.Left</code>, <code>Canvas.Top</code>, <code>Canvas.Right</code> /// and <code>Canvas.Bottom</code> attached properties. /// </remarks> public class Canvas : Panel, INavigableContainer { /// <summary> /// Defines the Left attached property. /// </summary> public static readonly AttachedProperty<double> LeftProperty = AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Left", double.NaN); /// <summary> /// Defines the Top attached property. /// </summary> public static readonly AttachedProperty<double> TopProperty = AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Top", double.NaN); /// <summary> /// Defines the Right attached property. /// </summary> public static readonly AttachedProperty<double> RightProperty = AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Right", double.NaN); /// <summary> /// Defines the Bottom attached property. /// </summary> public static readonly AttachedProperty<double> BottomProperty = AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Bottom", double.NaN); /// <summary> /// Initializes static members of the <see cref="Canvas"/> class. /// </summary> static Canvas() { ClipToBoundsProperty.OverrideDefaultValue<Canvas>(false); AffectsParentArrange<Canvas>(LeftProperty, TopProperty, RightProperty, BottomProperty); } /// <summary> /// Gets the value of the Left attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's left coordinate.</returns> public static double GetLeft(AvaloniaObject element) { return element.GetValue(LeftProperty); } /// <summary> /// Sets the value of the Left attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The left value.</param> public static void SetLeft(AvaloniaObject element, double value) { element.SetValue(LeftProperty, value); } /// <summary> /// Gets the value of the Top attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's top coordinate.</returns> public static double GetTop(AvaloniaObject element) { return element.GetValue(TopProperty); } /// <summary> /// Sets the value of the Top attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The top value.</param> public static void SetTop(AvaloniaObject element, double value) { element.SetValue(TopProperty, value); } /// <summary> /// Gets the value of the Right attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's right coordinate.</returns> public static double GetRight(AvaloniaObject element) { return element.GetValue(RightProperty); } /// <summary> /// Sets the value of the Right attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The right value.</param> public static void SetRight(AvaloniaObject element, double value) { element.SetValue(RightProperty, value); } /// <summary> /// Gets the value of the Bottom attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's bottom coordinate.</returns> public static double GetBottom(AvaloniaObject element) { return element.GetValue(BottomProperty); } /// <summary> /// Sets the value of the Bottom attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The bottom value.</param> public static void SetBottom(AvaloniaObject element, double value) { element.SetValue(BottomProperty, value); } /// <summary> /// Gets the next control in the specified direction. /// </summary> /// <param name="direction">The movement direction.</param> /// <param name="from">The control from which movement begins.</param> /// <param name="wrap">Whether to wrap around when the first or last item is reached.</param> /// <returns>The control.</returns> IInputElement? INavigableContainer.GetControl(NavigationDirection direction, IInputElement? from, bool wrap) { // TODO: Implement this return null; } /// <summary> /// Measures the control. /// </summary> /// <param name="availableSize">The available size.</param> /// <returns>The desired size of the control.</returns> protected override Size MeasureOverride(Size availableSize) { availableSize = new Size(double.PositiveInfinity, double.PositiveInfinity); foreach (Control child in Children) { child.Measure(availableSize); } return new Size(); } /// <summary> /// Arranges the control's children. /// </summary> /// <param name="finalSize">The size allocated to the control.</param> /// <returns>The space taken.</returns> protected override Size ArrangeOverride(Size finalSize) { foreach (Control child in Children) { double x = 0.0; double y = 0.0; double elementLeft = GetLeft(child); if (!double.IsNaN(elementLeft)) { x = elementLeft; } else { // Arrange with right. double elementRight = GetRight(child); if (!double.IsNaN(elementRight)) { x = finalSize.Width - child.DesiredSize.Width - elementRight; } } double elementTop = GetTop(child); if (!double.IsNaN(elementTop) ) { y = elementTop; } else { double elementBottom = GetBottom(child); if (!double.IsNaN(elementBottom)) { y = finalSize.Height - child.DesiredSize.Height - elementBottom; } } child.Arrange(new Rect(new Point(x, y), child.DesiredSize)); } return finalSize; } } }
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// How the Batch service should respond when a task completes. /// </summary> public partial class ExitConditions : ITransportObjectProvider<Models.ExitConditions>, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<ExitOptions> DefaultProperty; public readonly PropertyAccessor<IList<ExitCodeRangeMapping>> ExitCodeRangesProperty; public readonly PropertyAccessor<IList<ExitCodeMapping>> ExitCodesProperty; public readonly PropertyAccessor<ExitOptions> FileUploadErrorProperty; public readonly PropertyAccessor<ExitOptions> PreProcessingErrorProperty; public PropertyContainer() : base(BindingState.Unbound) { this.DefaultProperty = this.CreatePropertyAccessor<ExitOptions>(nameof(Default), BindingAccess.Read | BindingAccess.Write); this.ExitCodeRangesProperty = this.CreatePropertyAccessor<IList<ExitCodeRangeMapping>>(nameof(ExitCodeRanges), BindingAccess.Read | BindingAccess.Write); this.ExitCodesProperty = this.CreatePropertyAccessor<IList<ExitCodeMapping>>(nameof(ExitCodes), BindingAccess.Read | BindingAccess.Write); this.FileUploadErrorProperty = this.CreatePropertyAccessor<ExitOptions>(nameof(FileUploadError), BindingAccess.Read | BindingAccess.Write); this.PreProcessingErrorProperty = this.CreatePropertyAccessor<ExitOptions>(nameof(PreProcessingError), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.ExitConditions protocolObject) : base(BindingState.Bound) { this.DefaultProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.DefaultProperty, o => new ExitOptions(o).Freeze()), nameof(Default), BindingAccess.Read); this.ExitCodeRangesProperty = this.CreatePropertyAccessor( ExitCodeRangeMapping.ConvertFromProtocolCollectionAndFreeze(protocolObject.ExitCodeRanges), nameof(ExitCodeRanges), BindingAccess.Read); this.ExitCodesProperty = this.CreatePropertyAccessor( ExitCodeMapping.ConvertFromProtocolCollectionAndFreeze(protocolObject.ExitCodes), nameof(ExitCodes), BindingAccess.Read); this.FileUploadErrorProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.FileUploadError, o => new ExitOptions(o).Freeze()), nameof(FileUploadError), BindingAccess.Read); this.PreProcessingErrorProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.PreProcessingError, o => new ExitOptions(o).Freeze()), nameof(PreProcessingError), BindingAccess.Read); } } private readonly PropertyContainer propertyContainer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ExitConditions"/> class. /// </summary> public ExitConditions() { this.propertyContainer = new PropertyContainer(); } internal ExitConditions(Models.ExitConditions protocolObject) { this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region ExitConditions /// <summary> /// Gets or sets how the Batch service should respond if the task fails with an exit condition not covered by any /// of the other properties. /// </summary> /// <remarks> /// This value is used if the task exits with any nonzero exit code not listed in the <see cref="ExitCodes"/> or /// <see cref="ExitCodeRanges"/> collection, with a preprocessing error if the <see cref="PreProcessingError"/> property /// is not present, or with a file upload failure if the <see cref="FileUploadError"/> property is not present. /// </remarks> public ExitOptions Default { get { return this.propertyContainer.DefaultProperty.Value; } set { this.propertyContainer.DefaultProperty.Value = value; } } /// <summary> /// Gets or sets a list of task exit code ranges and how the Batch service should respond to them. /// </summary> public IList<ExitCodeRangeMapping> ExitCodeRanges { get { return this.propertyContainer.ExitCodeRangesProperty.Value; } set { this.propertyContainer.ExitCodeRangesProperty.Value = ConcurrentChangeTrackedModifiableList<ExitCodeRangeMapping>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets a list of task exit codes and how the Batch service should respond to them. /// </summary> public IList<ExitCodeMapping> ExitCodes { get { return this.propertyContainer.ExitCodesProperty.Value; } set { this.propertyContainer.ExitCodesProperty.Value = ConcurrentChangeTrackedModifiableList<ExitCodeMapping>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets how the Batch service should respond if a file upload error occurs. /// </summary> /// <remarks> /// If the task exited with an exit code that was specified via <see cref="ExitCodes" /> or <see cref="ExitCodeRanges" /// />, and then encountered a file upload error, then the action specified by the exit code takes precedence. /// </remarks> public ExitOptions FileUploadError { get { return this.propertyContainer.FileUploadErrorProperty.Value; } set { this.propertyContainer.FileUploadErrorProperty.Value = value; } } /// <summary> /// Gets or sets how the Batch service should respond if the task fails to start due to an error. /// </summary> public ExitOptions PreProcessingError { get { return this.propertyContainer.PreProcessingErrorProperty.Value; } set { this.propertyContainer.PreProcessingErrorProperty.Value = value; } } #endregion // ExitConditions #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.ExitConditions ITransportObjectProvider<Models.ExitConditions>.GetTransportObject() { Models.ExitConditions result = new Models.ExitConditions() { DefaultProperty = UtilitiesInternal.CreateObjectWithNullCheck(this.Default, (o) => o.GetTransportObject()), ExitCodeRanges = UtilitiesInternal.ConvertToProtocolCollection(this.ExitCodeRanges), ExitCodes = UtilitiesInternal.ConvertToProtocolCollection(this.ExitCodes), FileUploadError = UtilitiesInternal.CreateObjectWithNullCheck(this.FileUploadError, (o) => o.GetTransportObject()), PreProcessingError = UtilitiesInternal.CreateObjectWithNullCheck(this.PreProcessingError, (o) => o.GetTransportObject()), }; return result; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects. /// </summary> internal static IList<ExitConditions> ConvertFromProtocolCollection(IEnumerable<Models.ExitConditions> protoCollection) { ConcurrentChangeTrackedModifiableList<ExitConditions> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable( items: protoCollection, objectCreationFunc: o => new ExitConditions(o)); return converted; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects, in a frozen state. /// </summary> internal static IList<ExitConditions> ConvertFromProtocolCollectionAndFreeze(IEnumerable<Models.ExitConditions> protoCollection) { ConcurrentChangeTrackedModifiableList<ExitConditions> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable( items: protoCollection, objectCreationFunc: o => new ExitConditions(o).Freeze()); converted = UtilitiesInternal.CreateObjectWithNullCheck(converted, o => o.Freeze()); return converted; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects, with each object marked readonly /// and returned as a readonly collection. /// </summary> internal static IReadOnlyList<ExitConditions> ConvertFromProtocolCollectionReadOnly(IEnumerable<Models.ExitConditions> protoCollection) { IReadOnlyList<ExitConditions> converted = UtilitiesInternal.CreateObjectWithNullCheck( UtilitiesInternal.CollectionToNonThreadSafeCollection( items: protoCollection, objectCreationFunc: o => new ExitConditions(o).Freeze()), o => o.AsReadOnly()); return converted; } #endregion // Internal/private methods } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Security.Principal; using EventStore.Core.Bus; using EventStore.Core.Data; using EventStore.Core.Helpers; using EventStore.Core.Messages; using EventStore.Core.Messaging; using EventStore.Core.Services.TimerService; using EventStore.Core.TransactionLog.LogRecords; using EventStore.Projections.Core.Messages; namespace EventStore.Projections.Core.Services.Processing { public class TransactionFileEventReader : EventReader, IHandle<ClientMessage.ReadAllEventsForwardCompleted> { private bool _eventsRequested; private int _maxReadCount = 250; private TFPos _from; private readonly bool _deliverEndOfTfPosition; private readonly bool _resolveLinkTos; private readonly ITimeProvider _timeProvider; private int _deliveredEvents; public TransactionFileEventReader( IODispatcher ioDispatcher, IPublisher publisher, Guid eventReaderCorrelationId, IPrincipal readAs, TFPos @from, ITimeProvider timeProvider, bool stopOnEof = false, bool deliverEndOfTFPosition = true, bool resolveLinkTos = true, int? stopAfterNEvents = null) : base(ioDispatcher, publisher, eventReaderCorrelationId, readAs, stopOnEof, stopAfterNEvents) { if (publisher == null) throw new ArgumentNullException("publisher"); _from = @from; _deliverEndOfTfPosition = deliverEndOfTFPosition; _resolveLinkTos = resolveLinkTos; _timeProvider = timeProvider; } protected override bool AreEventsRequested() { return _eventsRequested; } public void Handle(ClientMessage.ReadAllEventsForwardCompleted message) { if (_disposed) return; if (!_eventsRequested) throw new InvalidOperationException("Read events has not been requested"); if (Paused) throw new InvalidOperationException("Paused"); _eventsRequested = false; if (message.Result == ReadAllResult.AccessDenied) { SendNotAuthorized(); return; } var eof = message.Events.Length == 0; var willDispose = _stopOnEof && eof; var oldFrom = _from; _from = message.NextPos; if (!willDispose) { PauseOrContinueProcessing(delay: eof); } if (eof) { // the end if (_deliverEndOfTfPosition) DeliverLastCommitPosition(_from); // allow joining heading distribution SendIdle(); SendEof(); } else { for (int index = 0; index < message.Events.Length; index++) { var @event = message.Events[index]; DeliverEvent(@event, message.TfLastCommitPosition, oldFrom); if (CheckEnough()) return; } } } private bool CheckEnough() { if (_stopAfterNEvents != null && _deliveredEvents >= _stopAfterNEvents) { _publisher.Publish(new ReaderSubscriptionMessage.EventReaderEof(EventReaderCorrelationId, maxEventsReached: true)); Dispose(); return true; } return false; } private void SendIdle() { _publisher.Publish( new ReaderSubscriptionMessage.EventReaderIdle(EventReaderCorrelationId, _timeProvider.Now)); } protected override void RequestEvents(bool delay) { if (_disposed) throw new InvalidOperationException("Disposed"); if (_eventsRequested) throw new InvalidOperationException("Read operation is already in progress"); if (PauseRequested || Paused) throw new InvalidOperationException("Paused or pause requested"); _eventsRequested = true; var readEventsForward = CreateReadEventsMessage(); if (delay) _publisher.Publish( TimerMessage.Schedule.Create( TimeSpan.FromMilliseconds(250), new PublishEnvelope(_publisher, crossThread: true), readEventsForward)); else _publisher.Publish(readEventsForward); } private Message CreateReadEventsMessage() { return new ClientMessage.ReadAllEventsForward( Guid.NewGuid(), EventReaderCorrelationId, new SendToThisEnvelope(this), _from.CommitPosition, _from.PreparePosition == -1 ? _from.CommitPosition : _from.PreparePosition, _maxReadCount, _resolveLinkTos, false, null, ReadAs); } private void DeliverLastCommitPosition(TFPos lastPosition) { if (_stopOnEof || _stopAfterNEvents != null) return; _publisher.Publish( new ReaderSubscriptionMessage.CommittedEventDistributed( EventReaderCorrelationId, null, lastPosition.PreparePosition, 100.0f, source: this.GetType())); //TODO: check was is passed here } private void DeliverEvent( EventStore.Core.Data.ResolvedEvent @event, long lastCommitPosition, TFPos currentFrom) { _deliveredEvents++; EventRecord positionEvent = (@event.Link ?? @event.Event); TFPos receivedPosition = @event.OriginalPosition.Value; if (currentFrom > receivedPosition) throw new Exception( string.Format( "ReadFromTF returned events in incorrect order. Last known position is: {0}. Received position is: {1}", currentFrom, receivedPosition)); TFPos originalPosition; if (@event.IsResolved) { if (positionEvent.Metadata != null && positionEvent.Metadata.Length > 0) { var parsedPosition = positionEvent.Metadata.ParseCheckpointTagJson().Position; originalPosition = parsedPosition != new TFPos(long.MinValue, long.MinValue) ? parsedPosition : new TFPos(-1, @event.OriginalEvent.LogPosition); } else originalPosition = new TFPos(-1, @event.OriginalEvent.LogPosition); } else { originalPosition = receivedPosition; } _publisher.Publish( new ReaderSubscriptionMessage.CommittedEventDistributed( EventReaderCorrelationId, new ResolvedEvent( positionEvent.EventStreamId, positionEvent.EventNumber, @event.Event.EventStreamId, @event.Event.EventNumber, @event.Link != null, receivedPosition, originalPosition, @event.Event.EventId, @event.Event.EventType, (@event.Event.Flags & PrepareFlags.IsJson) != 0, @event.Event.Data, @event.Event.Metadata, @event.Link == null ? null : @event.Link.Metadata, null, positionEvent.TimeStamp), _stopOnEof ? (long?) null : receivedPosition.PreparePosition, 100.0f*positionEvent.LogPosition/lastCommitPosition, source: this.GetType())); } } }
using System; using System.Buffers; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using SourceCode.Clay; using crypt = System.Security.Cryptography; namespace SourceCode.Chasm.Repository.Disk { partial class DiskChasmRepo // .File { /// <summary> /// Writes a file to disk, returning the content's <see cref="Sha1"/> value. /// The <paramref name="onWrite"/> function permits a transformation operation /// on the source value before calculating the hash and writing to the destination. /// For example, the source stream may be encoded as Json. /// The <paramref name="afterWrite"/> function permits an operation to be /// performed on the file immediately after writing it. For example, the file /// may be uploaded to the cloud. /// </summary> /// <param name="onWrite">An action to take on the internal hashing stream.</param> /// <param name="afterWrite">An action to take on the file after writing has finished.</param> /// <param name="cancellationToken">Allows the operation to be cancelled.</param> /// <remarks>Note that the <paramref name="onWrite"/> function should maintain the integrity /// of the source stream: the hash will be taken on the result of this operation. /// For example, transforming to Json is appropriate but compression is not since the latter /// is not a representative model of the original content, but rather a storage optimization.</remarks> public static async Task<Sha1> StageFileAsync(Func<Stream, ValueTask> onWrite, Func<Sha1, string, ValueTask> afterWrite, CancellationToken cancellationToken) { if (onWrite == null) throw new ArgumentNullException(nameof(onWrite)); // Note that an empty file is physically created var filePath = Path.GetTempFileName(); try { Sha1 sha1; using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Write, FileShare.Read)) using (var ct = crypt.SHA1.Create()) { using (var cs = new crypt.CryptoStream(fs, ct, crypt.CryptoStreamMode.Write)) { await onWrite(cs) .ConfigureAwait(false); } sha1 = new Sha1(ct.Hash); } if (afterWrite != null) { await afterWrite(sha1, filePath) .ConfigureAwait(false); } return sha1; } finally { if (File.Exists(filePath)) { File.Delete(filePath); } } } /// <summary> /// Writes a file to disk, returning the content's <see cref="Sha1"/> value. /// The <paramref name="afterWrite"/> function permits an operation to be /// performed on the file immediately after writing it. For example, the file /// may be uploaded to the cloud. /// </summary> /// <param name="stream">The content to hash and write.</param> /// <param name="afterWrite">An action to take on the file, after writing has finished.</param> /// <param name="cancellationToken">Allows the operation to be cancelled.</param> public static Task<Sha1> WriteFileAsync(Stream stream, Func<Sha1, string, ValueTask> afterWrite, CancellationToken cancellationToken) { if (stream == null) throw new ArgumentNullException(nameof(stream)); ValueTask HashWriter(Stream output) => new ValueTask(stream.CopyToAsync(output, cancellationToken)); return StageFileAsync(HashWriter, afterWrite, cancellationToken); } /// <summary> /// Writes a file to disk, returning the content's <see cref="Sha1"/> value. /// The <paramref name="afterWrite"/> function permits an operation to be /// performed on the file immediately after writing it. For example, the file /// may be uploaded to the cloud. /// </summary> /// <param name="buffer">The content to hash and write.</param> /// <param name="afterWrite">An action to take on the file, after writing has finished.</param> /// <param name="cancellationToken">Allows the operation to be cancelled.</param> public static Task<Sha1> WriteFileAsync(ReadOnlyMemory<byte> buffer, Func<Sha1, string, ValueTask> afterWrite, CancellationToken cancellationToken) { ValueTask HashWriter(Stream output) => output.WriteAsync(buffer, cancellationToken); return StageFileAsync(HashWriter, afterWrite, cancellationToken); } private static async Task<IMemoryOwner<byte>> ReadFileAsync(string path, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrWhiteSpace(path)); string dir = Path.GetDirectoryName(path); if (!Directory.Exists(dir)) return default; if (!File.Exists(path)) return default; using (FileStream fileStream = await WaitForFileAsync(path, FileMode.Open, FileAccess.Read, FileShare.Read, cancellationToken) .ConfigureAwait(false)) { IMemoryOwner<byte> owned = await ReadBytesAsync(fileStream, cancellationToken) .ConfigureAwait(false); return owned; } } private static async Task<IMemoryOwner<byte>> ReadBytesAsync(Stream stream, CancellationToken cancellationToken) { Debug.Assert(stream != null); int offset = 0; int remaining = (int)stream.Length; IMemoryOwner<byte> owned = MemoryPool<byte>.Shared.Rent(remaining); while (remaining > 0) { int count = await stream.ReadAsync(owned.Memory.Slice(offset, remaining), cancellationToken) .ConfigureAwait(false); if (count == 0) throw new EndOfStreamException("End of file"); offset += count; remaining -= count; } return owned; } private static async Task TouchFileAsync(string path, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrWhiteSpace(path)); if (!File.Exists(path)) return; for (int retryCount = 0; retryCount < RetryMax; retryCount++) { try { File.SetLastAccessTimeUtc(path, DateTime.UtcNow); break; } catch (IOException) { await Task.Delay(RetryMs, cancellationToken) .ConfigureAwait(false); } } } private static async Task<FileStream> WaitForFileAsync(string path, FileMode mode, FileAccess access, FileShare share, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrWhiteSpace(path)); int retryCount = 0; while (true) { FileStream fs = null; try { fs = new FileStream(path, mode, access, share); return fs; } catch (IOException) when (++retryCount < RetryMax) { fs?.Dispose(); await Task.Delay(RetryMs, cancellationToken) .ConfigureAwait(false); } } } private static void WriteMetadata(ChasmMetadata metadata, string path) { var dto = new JsonMetadata(metadata?.ContentType, metadata?.Filename); var json = dto.ToJson(); File.WriteAllText(path, json, s_utf8noBom); } private static ChasmMetadata ReadMetadata(string path) { if (!File.Exists(path)) return null; string json = File.ReadAllText(path, s_utf8noBom); var dto = JsonMetadata.FromJson(json); return new ChasmMetadata(dto.ContentType, dto.Filename); } public static (string filePath, string metaPath) DeriveFileNames(string root, Sha1 sha1) { System.Collections.Generic.KeyValuePair<string, string> tokens = sha1.Split(PrefixLength); string fileName = Path.Combine(tokens.Key, tokens.Value); string filePath = Path.Combine(root, fileName); string metaPath = filePath + ".metadata"; return (filePath, metaPath); } } }
//--------------------------------------------------------------------------- // // <copyright file="Size3D.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Markup; using System.Windows.Media.Media3D.Converters; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Media3D { [Serializable] [TypeConverter(typeof(Size3DConverter))] [ValueSerializer(typeof(Size3DValueSerializer))] // Used by MarkupWriter partial struct Size3D : IFormattable { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Compares two Size3D instances for exact equality. /// Note that double values can acquire error when operated upon, such that /// an exact comparison between two values which are logically equal may fail. /// Furthermore, using this equality operator, Double.NaN is not equal to itself. /// </summary> /// <returns> /// bool - true if the two Size3D instances are exactly equal, false otherwise /// </returns> /// <param name='size1'>The first Size3D to compare</param> /// <param name='size2'>The second Size3D to compare</param> public static bool operator == (Size3D size1, Size3D size2) { return size1.X == size2.X && size1.Y == size2.Y && size1.Z == size2.Z; } /// <summary> /// Compares two Size3D instances for exact inequality. /// Note that double values can acquire error when operated upon, such that /// an exact comparison between two values which are logically equal may fail. /// Furthermore, using this equality operator, Double.NaN is not equal to itself. /// </summary> /// <returns> /// bool - true if the two Size3D instances are exactly unequal, false otherwise /// </returns> /// <param name='size1'>The first Size3D to compare</param> /// <param name='size2'>The second Size3D to compare</param> public static bool operator != (Size3D size1, Size3D size2) { return !(size1 == size2); } /// <summary> /// Compares two Size3D instances for object equality. In this equality /// Double.NaN is equal to itself, unlike in numeric equality. /// Note that double values can acquire error when operated upon, such that /// an exact comparison between two values which /// are logically equal may fail. /// </summary> /// <returns> /// bool - true if the two Size3D instances are exactly equal, false otherwise /// </returns> /// <param name='size1'>The first Size3D to compare</param> /// <param name='size2'>The second Size3D to compare</param> public static bool Equals (Size3D size1, Size3D size2) { if (size1.IsEmpty) { return size2.IsEmpty; } else { return size1.X.Equals(size2.X) && size1.Y.Equals(size2.Y) && size1.Z.Equals(size2.Z); } } /// <summary> /// Equals - compares this Size3D with the passed in object. In this equality /// Double.NaN is equal to itself, unlike in numeric equality. /// Note that double values can acquire error when operated upon, such that /// an exact comparison between two values which /// are logically equal may fail. /// </summary> /// <returns> /// bool - true if the object is an instance of Size3D and if it's equal to "this". /// </returns> /// <param name='o'>The object to compare to "this"</param> public override bool Equals(object o) { if ((null == o) || !(o is Size3D)) { return false; } Size3D value = (Size3D)o; return Size3D.Equals(this,value); } /// <summary> /// Equals - compares this Size3D with the passed in object. In this equality /// Double.NaN is equal to itself, unlike in numeric equality. /// Note that double values can acquire error when operated upon, such that /// an exact comparison between two values which /// are logically equal may fail. /// </summary> /// <returns> /// bool - true if "value" is equal to "this". /// </returns> /// <param name='value'>The Size3D to compare to "this"</param> public bool Equals(Size3D value) { return Size3D.Equals(this, value); } /// <summary> /// Returns the HashCode for this Size3D /// </summary> /// <returns> /// int - the HashCode for this Size3D /// </returns> public override int GetHashCode() { if (IsEmpty) { return 0; } else { // Perform field-by-field XOR of HashCodes return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); } } /// <summary> /// Parse - returns an instance converted from the provided string using /// the culture "en-US" /// <param name="source"> string with Size3D data </param> /// </summary> public static Size3D Parse(string source) { IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS; TokenizerHelper th = new TokenizerHelper(source, formatProvider); Size3D value; String firstToken = th.NextTokenRequired(); // The token will already have had whitespace trimmed so we can do a // simple string compare. if (firstToken == "Empty") { value = Empty; } else { value = new Size3D( Convert.ToDouble(firstToken, formatProvider), Convert.ToDouble(th.NextTokenRequired(), formatProvider), Convert.ToDouble(th.NextTokenRequired(), formatProvider)); } // There should be no more tokens in this string. th.LastTokenRequired(); return value; } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties /// <summary> /// Creates a string representation of this object based on the current culture. /// </summary> /// <returns> /// A string representation of this object. /// </returns> public override string ToString() { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, null /* format provider */); } /// <summary> /// Creates a string representation of this object based on the IFormatProvider /// passed in. If the provider is null, the CurrentCulture is used. /// </summary> /// <returns> /// A string representation of this object. /// </returns> public string ToString(IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, provider); } /// <summary> /// Creates a string representation of this object based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <returns> /// A string representation of this object. /// </returns> string IFormattable.ToString(string format, IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(format, provider); } /// <summary> /// Creates a string representation of this object based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <returns> /// A string representation of this object. /// </returns> internal string ConvertToString(string format, IFormatProvider provider) { if (IsEmpty) { return "Empty"; } // Helper to get the numeric list separator for a given culture. char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider); return String.Format(provider, "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}", separator, _x, _y, _z); } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal double _x; internal double _y; internal double _z; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #endregion Constructors } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using Microsoft.Security.Application; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Metadata; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Sdk; namespace Microsoft.Xrm.Portal.Web.Data.Services { /// <summary> /// Extension methods for <see cref="Entity"/> for building <see cref="CmsDataService{TDataContext}"/> service URIs. /// </summary> internal static class EntityExtensions { public static string GetDataServiceUri(this Entity entity, string serviceBaseUri) { if (string.IsNullOrEmpty(serviceBaseUri)) { return null; } var uriInfo = new EntityDataServiceUriInfo(entity); if (!uriInfo.Valid) { return null; } return "{0}/{1}(guid'{2}')".FormatWith(serviceBaseUri.TrimEnd('/'), UrlEncode(uriInfo.EntitySetName), UrlEncode(uriInfo.PrimaryKey.ToString())); } public static string GetDataServiceUri(this Entity entity) { return GetDataServiceUri(entity, GetCmsServiceBaseUri()); } public static string GetDataServicePropertyUri(this Entity entity, string propertyName, string serviceBaseUri) { if (string.IsNullOrEmpty(propertyName)) { return null; } var entityUri = GetDataServiceUri(entity, serviceBaseUri); if (entityUri == null) { return null; } return "{0}/{1}".FormatWith(entityUri, UrlEncode(propertyName)); } public static string GetDataServicePropertyUri(this Entity entity, string propertyName) { return GetDataServicePropertyUri(entity, propertyName, GetCmsServiceBaseUri()); } public static string GetDataServiceCrmAssociationSetUri(this Entity entity, string portalName, Relationship relationship) { return GetDataServiceCrmAssociationSetUri(entity, portalName, relationship, GetCmsServiceBaseUri()); } public static string GetDataServiceCrmAssociationSetUri(this Entity entity, string portalName, Relationship relationship, string serviceBaseUri) { if (string.IsNullOrEmpty(relationship.SchemaName)) { return null; } try { var portal = PortalCrmConfigurationManager.CreatePortalContext(portalName); var context = portal.ServiceContext; EntitySetInfo entitySetInfo; RelationshipInfo associationInfo; if (!OrganizationServiceContextInfo.TryGet(context, entity, out entitySetInfo) || !entitySetInfo.Entity.RelationshipsBySchemaName.TryGetValue(relationship, out associationInfo)) { return null; } return GetDataServicePropertyUri(entity, associationInfo.Property.Name, serviceBaseUri); } catch (InvalidOperationException) { return null; } } public static string GetEntityDeleteDataServiceUri(this Entity entity) { return GetEntityDeleteDataServiceUri(entity, GetCmsServiceBaseUri()); } public static string GetEntityDeleteDataServiceUri(this Entity entity, string serviceBaseUri) { if (string.IsNullOrEmpty(serviceBaseUri)) { return null; } var uriInfo = new EntityDataServiceUriInfo(entity); if (!uriInfo.Valid) { return null; } return "{0}/DeleteEntity?entitySet='{1}'&entityID=guid'{2}'".FormatWith(serviceBaseUri.TrimEnd('/'), UrlEncode(uriInfo.EntitySetName), UrlEncode(uriInfo.PrimaryKey.ToString())); } public static string GetEntityUrlDataServiceUri(this Entity entity) { return GetEntityUrlDataServiceUri(entity, GetCmsServiceBaseUri()); } public static string GetEntityUrlDataServiceUri(this Entity entity, string serviceBaseUri) { if (string.IsNullOrEmpty(serviceBaseUri)) { return null; } var uriInfo = new EntityDataServiceUriInfo(entity); if (!uriInfo.Valid) { return null; } return "{0}/GetEntityUrl?entitySet='{1}'&entityID=guid'{2}'".FormatWith(serviceBaseUri.TrimEnd('/'), UrlEncode(uriInfo.EntitySetName), UrlEncode(uriInfo.PrimaryKey.ToString())); } public static string GetEntityFileAttachmentDataServiceUri(this Entity entity) { return GetEntityFileAttachmentDataServiceUri(entity, GetCmsServiceBaseUri()); } public static string GetEntityFileAttachmentDataServiceUri(this Entity entity, string serviceBaseUri) { if (string.IsNullOrEmpty(serviceBaseUri)) { return null; } var uriInfo = new EntityDataServiceUriInfo(entity); if (!uriInfo.Valid) { return null; } return "{0}/AttachFilesToEntity?entitySet='{1}'&entityID=guid'{2}'".FormatWith(serviceBaseUri.TrimEnd('/'), UrlEncode(uriInfo.EntitySetName), UrlEncode(uriInfo.PrimaryKey.ToString())); } private static string UrlEncode(string s) { return Encoder.UrlEncode(s); } private class EntityDataServiceUriInfo { public EntityDataServiceUriInfo(Entity entity) { if (entity == null) { Valid = false; return; } var entityAttribute = entity.GetType().GetFirstOrDefaultCustomAttribute<EntityAttribute>(); if (entityAttribute == null || string.IsNullOrEmpty(entityAttribute.EntitySetName)) { Valid = false; return; } EntitySetName = entityAttribute.EntitySetName; PrimaryKey = entity.Id; Valid = true; } public string EntitySetName { get; private set; } public Guid PrimaryKey { get; private set; } public bool Valid { get; private set; } } private static string GetCmsServiceBaseUri(string portalName = null) { // TODO: allow the portalName to be specified return PortalCrmConfigurationManager.GetCmsServiceBaseUri(portalName); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Xunit; namespace Endless.Tests { public partial class EnumerableExtensionsTests { [Fact] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void Scan_Seed_Test1() { // arrange var list = new List<int> { 4, 2, 4 }; Func<float, int, float> f = (x, y) => x / y; const int seed = 64; // action var result = list.Scan(seed, f).ToList(); // assert Assert.Equal(new List<float> { 64, 16, 8, 2 }, result); } [Fact] [SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void Scan_Seed_Test2() { // arrange var list = new List<int>(); Func<float, int, float> f = (x, y) => x / y; const int seed = 3; // action var result = list.Scan(seed, f).ToList(); // assert Assert.Equal(new List<float> { 3 }, result); } [Fact] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void Scan_Test1() { // arrange var list = new List<int> { 1, 2, 3, 4 }; Func<int, int, int> f = (x, y) => x + y; // action var result = list.Scan(f).ToList(); // assert Assert.Equal(new List<int> { 1, 3, 6, 10 }, result); } [Fact] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void Scan_Test2() { // arrange var list = new List<float> { 64, 4, 2, 8 }; Func<float, float, float> f = (x, y) => x / y; // action var result = list.Scan(f).ToList(); // assert Assert.Equal(new List<float> { 64f, 16f, 8f, 1f }, result); } [Fact] [SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void Scan_Test3() { // arrange var list = new List<float>(); Func<float, float, float> f = (x, y) => x / y; // action var result = list.Scan(f).ToList(); // assert Assert.Equal(new List<float>(), result); } [Fact] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void Scan_Test4() { // arrange var list = new List<float> { 10 }; Func<float, float, float> f = (x, y) => x / y; // action var result = list.Scan(f).ToList(); // assert Assert.Equal(new List<float> { 10 }, result); } [Fact] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void ScanRight_Seed_Test1() { // arrange var list = new List<int> { 1, 2, 3, 4 }; Func<int, int, int> f = (x, y) => x + y; const int seed = 5; // action var result = list.ScanRight(seed, f).ToList(); // assert Assert.Equal(new List<int> { 15, 14, 12, 9, 5 }, result); } [Fact] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void ScanRight_Seed_Test2() { // arrange var list = new List<int> { 8, 12, 24, 4 }; Func<int, float, float> f = (x, y) => x / y; const float seed = 2f; // action var result = list.ScanRight(seed, f).ToList(); // assert Assert.Equal(new List<float> { 8f, 1f, 12f, 2f, 2f }, result); } [Fact] [SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void ScanRight_Seed_Test3() { // arrange var list = new List<int>(); Func<int, float, float> f = (x, y) => x / y; const float seed = 2f; // action var result = list.ScanRight(seed, f).ToList(); // assert Assert.Equal(new List<float> { 2f }, result); } [Fact] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void ScanRight_Test1() { // arrange var list = new List<int> { 1, 2, 3, 4 }; Func<int, int, int> f = (x, y) => x + y; // action var result = list.ScanRight(f).ToList(); // assert Assert.Equal(new List<int> { 10, 9, 7, 4 }, result); } [Fact] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void ScanRight_Test2() { // arrange var list = new List<float> { 8, 12, 24, 2 }; Func<float, float, float> f = (x, y) => x / y; // action var result = list.ScanRight(f).ToList(); // assert Assert.Equal(new List<float> { 8, 1, 12, 2 }, result); } [Fact] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void ScanRight_Test3() { // arrange var list = new List<float> { 12 }; Func<float, float, float> f = (x, y) => x / y; // action var result = list.ScanRight(f).ToList(); // assert Assert.Equal(new List<float> { 12 }, result); } [Fact] [SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")] [SuppressMessage("ReSharper", "ConvertToLocalFunction")] public void ScanRight_Test4() { // arrange var list = new List<float>(); Func<float, float, float> f = (x, y) => x / y; // action var result = list.ScanRight(f).ToList(); // assert Assert.Equal(new List<float>(), result); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.Security.Claims; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.JSInterop; using Microsoft.JSInterop.Infrastructure; namespace Microsoft.AspNetCore.Components.Server.Circuits { internal partial class CircuitHost : IAsyncDisposable { private readonly AsyncServiceScope _scope; private readonly CircuitOptions _options; private readonly CircuitHandler[] _circuitHandlers; private readonly ILogger _logger; private bool _initialized; private bool _disposed; // This event is fired when there's an unrecoverable exception coming from the circuit, and // it need so be torn down. The registry listens to this even so that the circuit can // be torn down even when a client is not connected. // // We don't expect the registry to do anything with the exception. We only provide it here // for testability. public event UnhandledExceptionEventHandler UnhandledException; public CircuitHost( CircuitId circuitId, AsyncServiceScope scope, CircuitOptions options, CircuitClientProxy client, RemoteRenderer renderer, IReadOnlyList<ComponentDescriptor> descriptors, RemoteJSRuntime jsRuntime, CircuitHandler[] circuitHandlers, ILogger logger) { CircuitId = circuitId; if (CircuitId.Secret is null) { // Prevent the use of a 'default' secret. throw new ArgumentException($"Property '{nameof(CircuitId.Secret)}' cannot be null.", nameof(circuitId)); } _scope = scope; _options = options ?? throw new ArgumentNullException(nameof(options)); Client = client ?? throw new ArgumentNullException(nameof(client)); Renderer = renderer ?? throw new ArgumentNullException(nameof(renderer)); Descriptors = descriptors ?? throw new ArgumentNullException(nameof(descriptors)); JSRuntime = jsRuntime ?? throw new ArgumentNullException(nameof(jsRuntime)); _circuitHandlers = circuitHandlers ?? throw new ArgumentNullException(nameof(circuitHandlers)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); Services = scope.ServiceProvider; Circuit = new Circuit(this); Handle = new CircuitHandle() { CircuitHost = this, }; // An unhandled exception from the renderer is always fatal because it came from user code. Renderer.UnhandledException += ReportAndInvoke_UnhandledException; Renderer.UnhandledSynchronizationException += SynchronizationContext_UnhandledException; JSRuntime.UnhandledException += ReportAndInvoke_UnhandledException; } public CircuitHandle Handle { get; } public CircuitId CircuitId { get; } public Circuit Circuit { get; } public CircuitClientProxy Client { get; set; } public RemoteJSRuntime JSRuntime { get; } public RemoteRenderer Renderer { get; } public IReadOnlyList<ComponentDescriptor> Descriptors { get; } public IServiceProvider Services { get; } // InitializeAsync is used in a fire-and-forget context, so it's responsible for its own // error handling. public Task InitializeAsync(ProtectedPrerenderComponentApplicationStore store, CancellationToken cancellationToken) { Log.InitializationStarted(_logger); return Renderer.Dispatcher.InvokeAsync(async () => { if (_initialized) { throw new InvalidOperationException("The circuit host is already initialized."); } try { _initialized = true; // We're ready to accept incoming JSInterop calls from here on await OnCircuitOpenedAsync(cancellationToken); await OnConnectionUpAsync(cancellationToken); // Here, we add each root component but don't await the returned tasks so that the // components can be processed in parallel. var count = Descriptors.Count; var pendingRenders = new Task[count]; for (var i = 0; i < count; i++) { var (componentType, parameters, sequence) = Descriptors[i]; pendingRenders[i] = Renderer.AddComponentAsync(componentType, parameters, sequence.ToString(CultureInfo.InvariantCulture)); } // Now we wait for all components to finish rendering. await Task.WhenAll(pendingRenders); // At this point all components have successfully produced an initial render and we can clear the contents of the component // application state store. This ensures the memory that was not used during the initial render of these components gets // reclaimed since no-one else is holding on to it any longer. store.ExistingState.Clear(); Log.InitializationSucceeded(_logger); } catch (Exception ex) { // Report errors asynchronously. InitializeAsync is designed not to throw. Log.InitializationFailed(_logger, ex); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex), ex); } }); } // We handle errors in DisposeAsync because there's no real value in letting it propagate. // We run user code here (CircuitHandlers) and it's reasonable to expect some might throw, however, // there isn't anything better to do than log when one of these exceptions happens - because the // client is already gone. public async ValueTask DisposeAsync() { Log.DisposeStarted(_logger, CircuitId); await Renderer.Dispatcher.InvokeAsync(async () => { if (_disposed) { return; } // Make sure that no hub or connection can refer to this circuit anymore now that it's shutting down. Handle.CircuitHost = null; _disposed = true; try { await OnConnectionDownAsync(CancellationToken.None); } catch { // Individual exceptions logged as part of OnConnectionDownAsync - nothing to do here // since we're already shutting down. } try { await OnCircuitDownAsync(CancellationToken.None); } catch { // Individual exceptions logged as part of OnCircuitDownAsync - nothing to do here // since we're already shutting down. } try { // Prevent any further JS interop calls // Helps with scenarios like https://github.com/dotnet/aspnetcore/issues/32808 JSRuntime.MarkPermanentlyDisconnected(); await Renderer.DisposeAsync(); await _scope.DisposeAsync(); Log.DisposeSucceeded(_logger, CircuitId); } catch (Exception ex) { Log.DisposeFailed(_logger, CircuitId, ex); } }); } // Note: we log exceptions and re-throw while running handlers, because there may be multiple // exceptions. private async Task OnCircuitOpenedAsync(CancellationToken cancellationToken) { Log.CircuitOpened(_logger, CircuitId); Renderer.Dispatcher.AssertAccess(); List<Exception> exceptions = null; for (var i = 0; i < _circuitHandlers.Length; i++) { var circuitHandler = _circuitHandlers[i]; try { await circuitHandler.OnCircuitOpenedAsync(Circuit, cancellationToken); } catch (Exception ex) { Log.CircuitHandlerFailed(_logger, circuitHandler, nameof(CircuitHandler.OnCircuitOpenedAsync), ex); exceptions ??= new List<Exception>(); exceptions.Add(ex); } } if (exceptions != null) { throw new AggregateException("Encountered exceptions while executing circuit handlers.", exceptions); } } public async Task OnConnectionUpAsync(CancellationToken cancellationToken) { Log.ConnectionUp(_logger, CircuitId, Client.ConnectionId); Renderer.Dispatcher.AssertAccess(); List<Exception> exceptions = null; for (var i = 0; i < _circuitHandlers.Length; i++) { var circuitHandler = _circuitHandlers[i]; try { await circuitHandler.OnConnectionUpAsync(Circuit, cancellationToken); } catch (Exception ex) { Log.CircuitHandlerFailed(_logger, circuitHandler, nameof(CircuitHandler.OnConnectionUpAsync), ex); exceptions ??= new List<Exception>(); exceptions.Add(ex); } } if (exceptions != null) { throw new AggregateException("Encountered exceptions while executing circuit handlers.", exceptions); } } public async Task OnConnectionDownAsync(CancellationToken cancellationToken) { Log.ConnectionDown(_logger, CircuitId, Client.ConnectionId); Renderer.Dispatcher.AssertAccess(); List<Exception> exceptions = null; for (var i = 0; i < _circuitHandlers.Length; i++) { var circuitHandler = _circuitHandlers[i]; try { await circuitHandler.OnConnectionDownAsync(Circuit, cancellationToken); } catch (Exception ex) { Log.CircuitHandlerFailed(_logger, circuitHandler, nameof(CircuitHandler.OnConnectionDownAsync), ex); exceptions ??= new List<Exception>(); exceptions.Add(ex); } } if (exceptions != null) { throw new AggregateException("Encountered exceptions while executing circuit handlers.", exceptions); } } private async Task OnCircuitDownAsync(CancellationToken cancellationToken) { Log.CircuitClosed(_logger, CircuitId); List<Exception> exceptions = null; for (var i = 0; i < _circuitHandlers.Length; i++) { var circuitHandler = _circuitHandlers[i]; try { await circuitHandler.OnCircuitClosedAsync(Circuit, cancellationToken); } catch (Exception ex) { Log.CircuitHandlerFailed(_logger, circuitHandler, nameof(CircuitHandler.OnCircuitClosedAsync), ex); exceptions ??= new List<Exception>(); exceptions.Add(ex); } } if (exceptions != null) { throw new AggregateException("Encountered exceptions while executing circuit handlers.", exceptions); } } // Called by the client when it completes rendering a batch. // OnRenderCompletedAsync is used in a fire-and-forget context, so it's responsible for its own // error handling. public async Task OnRenderCompletedAsync(long renderId, string errorMessageOrNull) { AssertInitialized(); AssertNotDisposed(); try { _ = Renderer.OnRenderCompletedAsync(renderId, errorMessageOrNull); } catch (Exception e) { // Captures sync exceptions when invoking OnRenderCompletedAsync. // An exception might be throw synchronously when we receive an ack for a batch we never produced. Log.OnRenderCompletedFailed(_logger, renderId, CircuitId, e); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(e, $"Failed to complete render batch '{renderId}'.")); UnhandledException(this, new UnhandledExceptionEventArgs(e, isTerminating: false)); } } // BeginInvokeDotNetFromJS is used in a fire-and-forget context, so it's responsible for its own // error handling. public async Task BeginInvokeDotNetFromJS(string callId, string assemblyName, string methodIdentifier, long dotNetObjectId, string argsJson) { AssertInitialized(); AssertNotDisposed(); try { await Renderer.Dispatcher.InvokeAsync(() => { Log.BeginInvokeDotNet(_logger, callId, assemblyName, methodIdentifier, dotNetObjectId); var invocationInfo = new DotNetInvocationInfo(assemblyName, methodIdentifier, dotNetObjectId, callId); DotNetDispatcher.BeginInvokeDotNet(JSRuntime, invocationInfo, argsJson); }); } catch (Exception ex) { // We don't expect any of this code to actually throw, because DotNetDispatcher.BeginInvoke doesn't throw // however, we still want this to get logged if we do. Log.BeginInvokeDotNetFailed(_logger, callId, assemblyName, methodIdentifier, dotNetObjectId, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Interop call failed.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); } } // EndInvokeJSFromDotNet is used in a fire-and-forget context, so it's responsible for its own // error handling. public async Task EndInvokeJSFromDotNet(long asyncCall, bool succeeded, string arguments) { AssertInitialized(); AssertNotDisposed(); try { await Renderer.Dispatcher.InvokeAsync(() => { if (!succeeded) { // We can log the arguments here because it is simply the JS error with the call stack. Log.EndInvokeJSFailed(_logger, asyncCall, arguments); } else { Log.EndInvokeJSSucceeded(_logger, asyncCall); } DotNetDispatcher.EndInvokeJS(JSRuntime, arguments); }); } catch (Exception ex) { // An error completing JS interop means that the user sent invalid data, a well-behaved // client won't do this. Log.EndInvokeDispatchException(_logger, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Invalid interop arguments.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); } } // ReceiveByteArray is used in a fire-and-forget context, so it's responsible for its own // error handling. internal async Task ReceiveByteArray(int id, byte[] data) { AssertInitialized(); AssertNotDisposed(); try { await Renderer.Dispatcher.InvokeAsync(() => { Log.ReceiveByteArraySuccess(_logger, id); DotNetDispatcher.ReceiveByteArray(JSRuntime, id, data); }); } catch (Exception ex) { // An error completing JS interop means that the user sent invalid data, a well-behaved // client won't do this. Log.ReceiveByteArrayException(_logger, id, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Invalid byte array.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); } } // ReceiveJSDataChunk is used in a fire-and-forget context, so it's responsible for its own // error handling. internal async Task<bool> ReceiveJSDataChunk(long streamId, long chunkId, byte[] chunk, string error) { AssertInitialized(); AssertNotDisposed(); try { return await Renderer.Dispatcher.InvokeAsync(() => { return RemoteJSDataStream.ReceiveData(JSRuntime, streamId, chunkId, chunk, error); }); } catch (Exception ex) { // An error completing JS interop means that the user sent invalid data, a well-behaved // client won't do this. Log.ReceiveJSDataChunkException(_logger, streamId, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Invalid chunk supplied to stream.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); return false; } } public async Task<int> SendDotNetStreamAsync(DotNetStreamReference dotNetStreamReference, long streamId, byte[] buffer) { AssertInitialized(); AssertNotDisposed(); try { return await Renderer.Dispatcher.InvokeAsync<int>(async () => await dotNetStreamReference.Stream.ReadAsync(buffer)); } catch (Exception ex) { // An error completing stream interop means that the user sent invalid data, a well-behaved // client won't do this. Log.SendDotNetStreamException(_logger, streamId, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Unable to send .NET stream.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); return 0; } } public async Task<DotNetStreamReference> TryClaimPendingStream(long streamId) { AssertInitialized(); AssertNotDisposed(); DotNetStreamReference dotNetStreamReference = null; try { return await Renderer.Dispatcher.InvokeAsync<DotNetStreamReference>(() => { if (!JSRuntime.TryClaimPendingStreamForSending(streamId, out dotNetStreamReference)) { throw new InvalidOperationException($"The stream with ID {streamId} is not available. It may have timed out."); } return dotNetStreamReference; }); } catch (Exception ex) { // An error completing stream interop means that the user sent invalid data, a well-behaved // client won't do this. Log.SendDotNetStreamException(_logger, streamId, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Unable to locate .NET stream.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); return default; } } // OnLocationChangedAsync is used in a fire-and-forget context, so it's responsible for its own // error handling. public async Task OnLocationChangedAsync(string uri, bool intercepted) { AssertInitialized(); AssertNotDisposed(); try { await Renderer.Dispatcher.InvokeAsync(() => { Log.LocationChange(_logger, uri, CircuitId); var navigationManager = (RemoteNavigationManager)Services.GetRequiredService<NavigationManager>(); navigationManager.NotifyLocationChanged(uri, intercepted); Log.LocationChangeSucceeded(_logger, uri, CircuitId); }); } // It's up to the NavigationManager implementation to validate the URI. // // Note that it's also possible that setting the URI could cause a failure in code that listens // to NavigationManager.LocationChanged. // // In either case, a well-behaved client will not send invalid URIs, and we don't really // want to continue processing with the circuit if setting the URI failed inside application // code. The safest thing to do is consider it a critical failure since URI is global state, // and a failure means that an update to global state was partially applied. catch (LocationChangeException nex) { // LocationChangeException means that it failed in user-code. Treat this like an unhandled // exception in user-code. Log.LocationChangeFailedInCircuit(_logger, uri, CircuitId, nex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(nex, "Location change failed.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(nex, isTerminating: false)); } catch (Exception ex) { // Any other exception means that it failed validation, or inside the NavigationManager. Treat // this like bad data. Log.LocationChangeFailed(_logger, uri, CircuitId, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, $"Location change to '{uri}' failed.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); } } public void SetCircuitUser(ClaimsPrincipal user) { // This can be called before the circuit is initialized. AssertNotDisposed(); var authenticationStateProvider = Services.GetService<AuthenticationStateProvider>() as IHostEnvironmentAuthenticationStateProvider; if (authenticationStateProvider != null) { var authenticationState = new AuthenticationState(user); authenticationStateProvider.SetAuthenticationState(Task.FromResult(authenticationState)); } } public void SendPendingBatches() { AssertInitialized(); AssertNotDisposed(); // Dispatch any buffered renders we accumulated during a disconnect. // Note that while the rendering is async, we cannot await it here. The Task returned by ProcessBufferedRenderBatches relies on // OnRenderCompletedAsync to be invoked to complete, and SignalR does not allow concurrent hub method invocations. _ = Renderer.Dispatcher.InvokeAsync(() => Renderer.ProcessBufferedRenderBatches()); } private void AssertInitialized() { if (!_initialized) { throw new InvalidOperationException("Circuit is being invoked prior to initialization."); } } private void AssertNotDisposed() { if (_disposed) { throw new ObjectDisposedException(objectName: null); } } // We want to notify the client if it's still connected, and then tear-down the circuit. private async void ReportAndInvoke_UnhandledException(object sender, Exception e) { await ReportUnhandledException(e); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(e, isTerminating: false)); } // An unhandled exception from the renderer is always fatal because it came from user code. // We want to notify the client if it's still connected, and then tear-down the circuit. private async void SynchronizationContext_UnhandledException(object sender, UnhandledExceptionEventArgs e) { await ReportUnhandledException((Exception)e.ExceptionObject); UnhandledException?.Invoke(this, e); } private async Task ReportUnhandledException(Exception exception) { Log.CircuitUnhandledException(_logger, CircuitId, exception); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(exception), exception); } private string GetClientErrorMessage(Exception exception, string additionalInformation = null) { if (_options.DetailedErrors) { return exception.ToString(); } else { return $"There was an unhandled exception on the current circuit, so this circuit will be terminated. For more details turn on " + $"detailed exceptions by setting 'DetailedErrors: true' in 'appSettings.Development.json' or set '{typeof(CircuitOptions).Name}.{nameof(CircuitOptions.DetailedErrors)}'. {additionalInformation}"; } } // exception is only populated when either the renderer or the synchronization context signal exceptions. // In other cases it is null and should never be sent to the client. // error contains the information to send to the client. private async Task TryNotifyClientErrorAsync(IClientProxy client, string error, Exception exception = null) { if (!Client.Connected) { Log.UnhandledExceptionClientDisconnected( _logger, CircuitId, exception); return; } try { Log.CircuitTransmittingClientError(_logger, CircuitId); await client.SendAsync("JS.Error", error); Log.CircuitTransmittedClientErrorSuccess(_logger, CircuitId); } catch (Exception ex) { Log.CircuitTransmitErrorFailed(_logger, CircuitId, ex); } } private static partial class Log { // 100s used for lifecycle stuff // 200s used for interactive stuff [LoggerMessage(100, LogLevel.Debug, "Circuit initialization started.", EventName = "InitializationStarted")] public static partial void InitializationStarted(ILogger logger); [LoggerMessage(101, LogLevel.Debug, "Circuit initialization succeeded.", EventName = "InitializationSucceeded")] public static partial void InitializationSucceeded(ILogger logger); [LoggerMessage(102, LogLevel.Debug, "Circuit initialization failed.", EventName = "InitializationFailed")] public static partial void InitializationFailed(ILogger logger, Exception exception); [LoggerMessage(103, LogLevel.Debug, "Disposing circuit '{CircuitId}' started.", EventName = "DisposeStarted")] public static partial void DisposeStarted(ILogger logger, CircuitId circuitId); [LoggerMessage(104, LogLevel.Debug, "Disposing circuit '{CircuitId}' succeeded.", EventName = "DisposeSucceeded")] public static partial void DisposeSucceeded(ILogger logger, CircuitId circuitId); [LoggerMessage(105, LogLevel.Debug, "Disposing circuit '{CircuitId}' failed.", EventName = "DisposeFailed")] public static partial void DisposeFailed(ILogger logger, CircuitId circuitId, Exception exception); [LoggerMessage(106, LogLevel.Debug, "Opening circuit with id '{CircuitId}'.", EventName = "OnCircuitOpened")] public static partial void CircuitOpened(ILogger logger, CircuitId circuitId); [LoggerMessage(107, LogLevel.Debug, "Circuit id '{CircuitId}' connected using connection '{ConnectionId}'.", EventName = "OnConnectionUp")] public static partial void ConnectionUp(ILogger logger, CircuitId circuitId, string connectionId); [LoggerMessage(108, LogLevel.Debug, "Circuit id '{CircuitId}' disconnected from connection '{ConnectionId}'.", EventName = "OnConnectionDown")] public static partial void ConnectionDown(ILogger logger, CircuitId circuitId, string connectionId); [LoggerMessage(109, LogLevel.Debug, "Closing circuit with id '{CircuitId}'.", EventName = "OnCircuitClosed")] public static partial void CircuitClosed(ILogger logger, CircuitId circuitId); [LoggerMessage(110, LogLevel.Error, "Unhandled error invoking circuit handler type {handlerType}.{handlerMethod}: {Message}", EventName = "CircuitHandlerFailed")] private static partial void CircuitHandlerFailed(ILogger logger, Type handlerType, string handlerMethod, string message, Exception exception); public static void CircuitHandlerFailed(ILogger logger, CircuitHandler handler, string handlerMethod, Exception exception) { CircuitHandlerFailed( logger, handler.GetType(), handlerMethod, exception.Message, exception); } [LoggerMessage(111, LogLevel.Error, "Unhandled exception in circuit '{CircuitId}'.", EventName = "CircuitUnhandledException")] public static partial void CircuitUnhandledException(ILogger logger, CircuitId circuitId, Exception exception); [LoggerMessage(112, LogLevel.Debug, "About to notify client of an error in circuit '{CircuitId}'.", EventName = "CircuitTransmittingClientError")] public static partial void CircuitTransmittingClientError(ILogger logger, CircuitId circuitId); [LoggerMessage(113, LogLevel.Debug, "Successfully transmitted error to client in circuit '{CircuitId}'.", EventName = "CircuitTransmittedClientErrorSuccess")] public static partial void CircuitTransmittedClientErrorSuccess(ILogger logger, CircuitId circuitId); [LoggerMessage(114, LogLevel.Debug, "Failed to transmit exception to client in circuit '{CircuitId}'.", EventName = "CircuitTransmitErrorFailed")] public static partial void CircuitTransmitErrorFailed(ILogger logger, CircuitId circuitId, Exception exception); [LoggerMessage(115, LogLevel.Debug, "An exception occurred on the circuit host '{CircuitId}' while the client is disconnected.", EventName = "UnhandledExceptionClientDisconnected")] public static partial void UnhandledExceptionClientDisconnected(ILogger logger, CircuitId circuitId, Exception exception); [LoggerMessage(200, LogLevel.Debug, "Failed to parse the event data when trying to dispatch an event.", EventName = "DispatchEventFailedToParseEventData")] public static partial void DispatchEventFailedToParseEventData(ILogger logger, Exception ex); [LoggerMessage(201, LogLevel.Debug, "There was an error dispatching the event '{EventHandlerId}' to the application.", EventName = "DispatchEventFailedToDispatchEvent")] public static partial void DispatchEventFailedToDispatchEvent(ILogger logger, string eventHandlerId, Exception ex); [LoggerMessage(202, LogLevel.Debug, "Invoking instance method '{MethodIdentifier}' on instance '{DotNetObjectId}' with callback id '{CallId}'.", EventName = "BeginInvokeDotNet")] private static partial void BeginInvokeDotNet(ILogger logger, string methodIdentifier, long dotNetObjectId, string callId); [LoggerMessage(203, LogLevel.Debug, "Failed to invoke instance method '{MethodIdentifier}' on instance '{DotNetObjectId}' with callback id '{CallId}'.", EventName = "BeginInvokeDotNetFailed")] private static partial void BeginInvokeDotNetFailed(ILogger logger, string methodIdentifier, long dotNetObjectId, string callId, Exception exception); [LoggerMessage(204, LogLevel.Debug, "There was an error invoking 'Microsoft.JSInterop.DotNetDispatcher.EndInvoke'.", EventName = "EndInvokeDispatchException")] public static partial void EndInvokeDispatchException(ILogger logger, Exception ex); [LoggerMessage(205, LogLevel.Debug, "The JS interop call with callback id '{AsyncCall}' with arguments {Arguments}.", EventName = "EndInvokeJSFailed")] public static partial void EndInvokeJSFailed(ILogger logger, long asyncCall, string arguments); [LoggerMessage(206, LogLevel.Debug, "The JS interop call with callback id '{AsyncCall}' succeeded.", EventName = "EndInvokeJSSucceeded")] public static partial void EndInvokeJSSucceeded(ILogger logger, long asyncCall); [LoggerMessage(208, LogLevel.Debug, "Location changing to {URI} in circuit '{CircuitId}'.", EventName = "LocationChange")] public static partial void LocationChange(ILogger logger, string uri, CircuitId circuitId); [LoggerMessage(209, LogLevel.Debug, "Location change to '{URI}' in circuit '{CircuitId}' succeeded.", EventName = "LocationChangeSucceeded")] public static partial void LocationChangeSucceeded(ILogger logger, string uri, CircuitId circuitId); [LoggerMessage(210, LogLevel.Debug, "Location change to '{URI}' in circuit '{CircuitId}' failed.", EventName = "LocationChangeFailed")] public static partial void LocationChangeFailed(ILogger logger, string uri, CircuitId circuitId, Exception exception); [LoggerMessage(212, LogLevel.Debug, "Failed to complete render batch '{RenderId}' in circuit host '{CircuitId}'.", EventName = "OnRenderCompletedFailed")] public static partial void OnRenderCompletedFailed(ILogger logger, long renderId, CircuitId circuitId, Exception e); [LoggerMessage(213, LogLevel.Debug, "The ReceiveByteArray call with id '{id}' succeeded.", EventName = "ReceiveByteArraySucceeded")] public static partial void ReceiveByteArraySuccess(ILogger logger, long id); [LoggerMessage(214, LogLevel.Debug, "The ReceiveByteArray call with id '{id}' failed.", EventName = "ReceiveByteArrayException")] public static partial void ReceiveByteArrayException(ILogger logger, long id, Exception ex); [LoggerMessage(215, LogLevel.Debug, "The ReceiveJSDataChunk call with stream id '{streamId}' failed.", EventName = "ReceiveJSDataChunkException")] public static partial void ReceiveJSDataChunkException(ILogger logger, long streamId, Exception ex); [LoggerMessage(216, LogLevel.Debug, "The SendDotNetStreamAsync call with id '{id}' failed.", EventName = "SendDotNetStreamException")] public static partial void SendDotNetStreamException(ILogger logger, long id, Exception ex); [LoggerMessage(217, LogLevel.Debug, "Invoking static method with identifier '{MethodIdentifier}' on assembly '{Assembly}' with callback id '{CallId}'.", EventName = "BeginInvokeDotNetStatic")] private static partial void BeginInvokeDotNetStatic(ILogger logger, string methodIdentifier, string assembly, string callId); public static void BeginInvokeDotNet(ILogger logger, string callId, string assemblyName, string methodIdentifier, long dotNetObjectId) { if (assemblyName != null) { BeginInvokeDotNetStatic(logger, methodIdentifier, assemblyName, callId); } else { BeginInvokeDotNet(logger, methodIdentifier, dotNetObjectId, callId); } } [LoggerMessage(218, LogLevel.Debug, "Failed to invoke static method with identifier '{MethodIdentifier}' on assembly '{Assembly}' with callback id '{CallId}'.", EventName = "BeginInvokeDotNetFailed")] private static partial void BeginInvokeDotNetStaticFailed(ILogger logger, string methodIdentifier, string assembly, string callId, Exception exception); public static void BeginInvokeDotNetFailed(ILogger logger, string callId, string assemblyName, string methodIdentifier, long dotNetObjectId, Exception exception) { if (assemblyName != null) { BeginInvokeDotNetStaticFailed(logger, methodIdentifier, assemblyName, callId, exception); } else { BeginInvokeDotNetFailed(logger, methodIdentifier, dotNetObjectId, callId, exception); } } [LoggerMessage(219, LogLevel.Error, "Location change to '{URI}' in circuit '{CircuitId}' failed.", EventName = "LocationChangeFailed")] public static partial void LocationChangeFailedInCircuit(ILogger logger, string uri, CircuitId circuitId, Exception exception); } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities { using System.Activities.Debugger; using System.Activities.Validation; using System.Activities.XamlIntegration; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime; using System.Windows.Markup; using System.Xaml; [ContentProperty("Implementation")] public sealed class ActivityBuilder : IDebuggableWorkflowTree { // define attached properties that will identify PropertyReferenceExtension-based // object properties static AttachableMemberIdentifier propertyReferencePropertyID = new AttachableMemberIdentifier(typeof(ActivityBuilder), "PropertyReference"); static AttachableMemberIdentifier propertyReferencesPropertyID = new AttachableMemberIdentifier(typeof(ActivityBuilder), "PropertyReferences"); KeyedCollection<string, DynamicActivityProperty> properties; Collection<Constraint> constraints; Collection<Attribute> attributes; public ActivityBuilder() { } public string Name { get; set; } [DependsOn("Name")] public Collection<Attribute> Attributes { get { if (this.attributes == null) { this.attributes = new Collection<Attribute>(); } return this.attributes; } } [Browsable(false)] [DependsOn("Attributes")] public KeyedCollection<string, DynamicActivityProperty> Properties { get { if (this.properties == null) { this.properties = new ActivityPropertyCollection(); } return this.properties; } } [DependsOn("Properties")] [Browsable(false)] public Collection<Constraint> Constraints { get { if (this.constraints == null) { this.constraints = new Collection<Constraint>(); } return this.constraints; } } [TypeConverter(typeof(ImplementationVersionConverter))] [DefaultValue(null)] [DependsOn("Name")] public Version ImplementationVersion { get; set; } [DefaultValue(null)] [Browsable(false)] [DependsOn("Constraints")] public Activity Implementation { get; set; } // Back-compat workaround: PropertyReference shipped in 4.0. PropertyReferences is new in 4.5. // // Requirements: // - Runtime compat: Get/SetPropertyReference needs to continue to work, both when set programatically // and when loading a doc which contains only one PropertyReference on an object. // - Serialization compat: If only one PropertyReference was set, we shouldn't serialize PropertyReferences. // (Only affects when ActivityBuilder is used directly with XamlServices, since ActivityXamlServices // will convert ActivityPropertyReference to PropertyReferenceExtension.) // - Usability: To avoid the designer needing to support two separate access methods, we want // the value from SetPropertyReference to also appear in the PropertyReferences collection. // <ActivityBuilder.PropertyReference>activity property name</ActivityBuilder.PropertyReference> public static ActivityPropertyReference GetPropertyReference(object target) { return GetPropertyReferenceCollection(target).SingleItem; } // <ActivityBuilder.PropertyReference>activity property name</ActivityBuilder.PropertyReference> public static void SetPropertyReference(object target, ActivityPropertyReference value) { GetPropertyReferenceCollection(target).SingleItem = value; } public static IList<ActivityPropertyReference> GetPropertyReferences(object target) { return GetPropertyReferenceCollection(target); } public static bool ShouldSerializePropertyReference(object target) { PropertyReferenceCollection propertyReferences = GetPropertyReferenceCollection(target); return propertyReferences.Count == 1 && propertyReferences.SingleItem != null; } public static bool ShouldSerializePropertyReferences(object target) { PropertyReferenceCollection propertyReferences = GetPropertyReferenceCollection(target); return propertyReferences.Count > 1 || propertyReferences.SingleItem == null; } internal static bool HasPropertyReferences(object target) { PropertyReferenceCollection propertyReferences; if (AttachablePropertyServices.TryGetProperty(target, propertyReferencesPropertyID, out propertyReferences)) { return propertyReferences.Count > 0; } return false; } static PropertyReferenceCollection GetPropertyReferenceCollection(object target) { PropertyReferenceCollection propertyReferences; if (!AttachablePropertyServices.TryGetProperty(target, propertyReferencesPropertyID, out propertyReferences)) { propertyReferences = new PropertyReferenceCollection(target); AttachablePropertyServices.SetProperty(target, propertyReferencesPropertyID, propertyReferences); } return propertyReferences; } Activity IDebuggableWorkflowTree.GetWorkflowRoot() { return this.Implementation; } internal static KeyedCollection<string, DynamicActivityProperty> CreateActivityPropertyCollection() { return new ActivityPropertyCollection(); } class ActivityPropertyCollection : KeyedCollection<string, DynamicActivityProperty> { protected override string GetKeyForItem(DynamicActivityProperty item) { return item.Name; } } // See back-compat requirements in comment above. Design is: // - First value added to collection when it is empty becomes the single PropertyReference value // - If the single value is removed, then PropertyReference AP is removed // - If PropertyReference AP is set to null, we remove the single value. // - If PropertyReference is set to non-null, we replace the existing single value if there // is one, or else add the new value to the collection. class PropertyReferenceCollection : Collection<ActivityPropertyReference> { WeakReference targetObject; int singleItemIndex = -1; public PropertyReferenceCollection(object target) { this.targetObject = new WeakReference(target); } public ActivityPropertyReference SingleItem { get { return this.singleItemIndex >= 0 ? this[this.singleItemIndex] : null; } set { if (this.singleItemIndex >= 0) { if (value != null) { SetItem(this.singleItemIndex, value); } else { RemoveItem(this.singleItemIndex); } } else if (value != null) { Add(value); if (Count > 1) { this.singleItemIndex = Count - 1; UpdateAttachedProperty(); } } } } protected override void ClearItems() { this.singleItemIndex = -1; UpdateAttachedProperty(); } protected override void InsertItem(int index, ActivityPropertyReference item) { base.InsertItem(index, item); if (index <= this.singleItemIndex) { this.singleItemIndex++; } else if (Count == 1) { Fx.Assert(this.singleItemIndex < 0, "How did we have an index if we were empty?"); this.singleItemIndex = 0; UpdateAttachedProperty(); } } protected override void RemoveItem(int index) { base.RemoveItem(index); if (index < this.singleItemIndex) { this.singleItemIndex--; } else if (index == this.singleItemIndex) { this.singleItemIndex = -1; UpdateAttachedProperty(); } } protected override void SetItem(int index, ActivityPropertyReference item) { base.SetItem(index, item); if (index == this.singleItemIndex) { UpdateAttachedProperty(); } } void UpdateAttachedProperty() { object target = this.targetObject.Target; if (target != null) { if (this.singleItemIndex >= 0) { AttachablePropertyServices.SetProperty(target, propertyReferencePropertyID, this[this.singleItemIndex]); } else { AttachablePropertyServices.RemoveProperty(target, propertyReferencePropertyID); } } } } } [ContentProperty("Implementation")] public sealed class ActivityBuilder<TResult> : IDebuggableWorkflowTree { KeyedCollection<string, DynamicActivityProperty> properties; Collection<Constraint> constraints; Collection<Attribute> attributes; public ActivityBuilder() { } public string Name { get; set; } [DependsOn("Name")] public Collection<Attribute> Attributes { get { if (this.attributes == null) { this.attributes = new Collection<Attribute>(); } return this.attributes; } } [Browsable(false)] [DependsOn("Attributes")] public KeyedCollection<string, DynamicActivityProperty> Properties { get { if (this.properties == null) { this.properties = ActivityBuilder.CreateActivityPropertyCollection(); } return this.properties; } } [DependsOn("Properties")] [Browsable(false)] public Collection<Constraint> Constraints { get { if (this.constraints == null) { this.constraints = new Collection<Constraint>(); } return this.constraints; } } [TypeConverter(typeof(ImplementationVersionConverter))] [DefaultValue(null)] [DependsOn("Name")] public Version ImplementationVersion { get; set; } [DefaultValue(null)] [Browsable(false)] [DependsOn("Constraints")] public Activity Implementation { get; set; } Activity IDebuggableWorkflowTree.GetWorkflowRoot() { return this.Implementation; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.Build.UnitTests { public sealed class MSBuildTask_Tests : IDisposable { private readonly ITestOutputHelper _testOutput; public MSBuildTask_Tests(ITestOutputHelper testOutput) { _testOutput = testOutput; ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); } public void Dispose() { ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); } /// <summary> /// If we pass in an item spec that is over the max path but it can be normalized down to something under the max path, we should still work and not /// throw a path too long exception /// </summary> [Fact] [ActiveIssue("https://github.com/Microsoft/msbuild/issues/4247")] public void ProjectItemSpecTooLong() { string currentDirectory = Directory.GetCurrentDirectory(); try { Directory.SetCurrentDirectory(Path.GetTempPath()); string tempPath = Path.GetTempPath(); string tempProject = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetA; TargetB; TargetC` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`TargetA` Outputs=`a1.dll`/> <Target Name=`TargetB` Outputs=`b1.dll; b2.dll`/> <Target Name=`TargetC` Outputs=`@(C_Outputs)`> <CreateItem Include=`c1.dll` AdditionalMetadata=`MSBuildSourceProjectFile=birch; MSBuildSourceTargetName=oak`> <Output ItemName=`C_Outputs` TaskParameter=`Include`/> </CreateItem> </Target> </Project> "); string fileName = Path.GetFileName(tempProject); string projectFile1 = null; for (int i = 0; i < 250; i++) { projectFile1 += "..\\"; } int rootLength = Path.GetPathRoot(tempPath).Length; string tempPathNoRoot = tempPath.Substring(rootLength); projectFile1 += Path.Combine(tempPathNoRoot, fileName); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`Build`> <MSBuild Projects=`" + projectFile1 + @"` /> </Target> </Project>"; try { Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); bool success = p.Build(); Assert.True(success); // "Build failed. See 'Standard Out' tab for details." } finally { File.Delete(tempProject); } } finally { Directory.SetCurrentDirectory(currentDirectory); } } /// <summary> /// Ensure that the MSBuild task tags any output items with two pieces of metadata -- MSBuildSourceProjectFile and /// MSBuildSourceTargetName -- that give an indication of where the items came from. /// </summary> [Fact] public void OutputItemsAreTaggedWithProjectFileAndTargetName() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetA; TargetB; TargetC` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`TargetA` Outputs=`a1.dll`/> <Target Name=`TargetB` Outputs=`b1.dll; b2.dll`/> <Target Name=`TargetC` Outputs=`@(C_Outputs)`> <CreateItem Include=`c1.dll`> <Output ItemName=`C_Outputs` TaskParameter=`Include`/> </CreateItem> </Target> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetG; TargetH` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`TargetG` Outputs=`g1.dll; g2.dll`/> <Target Name=`TargetH` Outputs=`h1.dll`/> </Project> "); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + projectFile1 + @"` /> <Projects Include=`" + projectFile2 + @"` /> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; try { Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); ProjectInstance pi = p.CreateProjectInstance(); IDictionary<string, TargetResult> targetOutputs; bool success = pi.Build(null, null, null, out targetOutputs); Assert.True(success); // "Build failed. See 'Standard Out' tab for details." string expectedItemOutputs = string.Format(@" a1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetA b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB b2.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB c1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetC g1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetG g2.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetG h1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetH ", projectFile1, projectFile2); Assert.True(targetOutputs.ContainsKey("Build")); Assert.Equal(7, targetOutputs["Build"].Items.Length); ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */); } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } /// <summary> /// Ensures that it is possible to call the MSBuild task with an empty Projects parameter, and it /// shouldn't error, and it shouldn't try to build itself. /// </summary> [Fact] public void EmptyProjectsParameterResultsInNoop() { string projectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`t` > <MSBuild Projects=` @(empty) ` /> </Target> </Project> "; MockLogger logger = new MockLogger(); Project project = ObjectModelHelpers.CreateInMemoryProject(projectContents, logger); bool success = project.Build(); Assert.True(success); // "Build failed. See test output (Attachments in Azure Pipelines) for details" } /// <summary> /// Verifies that nonexistent projects aren't normally skipped /// </summary> [Fact] public void NormallyDoNotSkipNonexistentProjects() { ObjectModelHelpers.DeleteTempProjectDirectory(); ObjectModelHelpers.CreateFileInTempProjectDirectory( "SkipNonexistentProjectsMain.csproj", @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`t` > <MSBuild Projects=`this_project_does_not_exist.csproj` /> </Target> </Project> "); MockLogger logger = new MockLogger(_testOutput); ObjectModelHelpers.BuildTempProjectFileExpectFailure(@"SkipNonexistentProjectsMain.csproj", logger); string error = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFound"), "this_project_does_not_exist.csproj"); Assert.Contains(error, logger.FullLog); } /// <summary> /// Verifies that nonexistent projects aren't normally skipped /// </summary> [Fact] public void NormallyDoNotSkipNonexistentProjectsBuildInParallel() { ObjectModelHelpers.DeleteTempProjectDirectory(); ObjectModelHelpers.CreateFileInTempProjectDirectory( "SkipNonexistentProjectsMain.csproj", @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`t` > <MSBuild Projects=`this_project_does_not_exist.csproj` BuildInParallel=`true`/> </Target> </Project> "); MockLogger logger = new MockLogger(_testOutput); ObjectModelHelpers.BuildTempProjectFileExpectFailure(@"SkipNonexistentProjectsMain.csproj", logger); string error = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFound"), "this_project_does_not_exist.csproj"); Assert.Equal(0, logger.WarningCount); Assert.Equal(1, logger.ErrorCount); Assert.Contains(error, logger.FullLog); } /// <summary> /// Verifies that nonexistent projects are skipped when requested /// </summary> [Fact] public void SkipNonexistentProjects() { ObjectModelHelpers.DeleteTempProjectDirectory(); ObjectModelHelpers.CreateFileInTempProjectDirectory( "SkipNonexistentProjectsMain.csproj", @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`t` > <MSBuild Projects=`this_project_does_not_exist.csproj;foo.csproj` SkipNonexistentProjects=`true` /> </Target> </Project> "); ObjectModelHelpers.CreateFileInTempProjectDirectory( "foo.csproj", @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`t` > <Message Text=`Hello from foo.csproj`/> </Target> </Project> "); MockLogger logger = new MockLogger(_testOutput); ObjectModelHelpers.BuildTempProjectFileExpectSuccess(@"SkipNonexistentProjectsMain.csproj", logger); logger.AssertLogContains("Hello from foo.csproj"); string message = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFoundMessage"), "this_project_does_not_exist.csproj"); string error = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFound"), "this_project_does_not_exist.csproj"); Assert.Equal(0, logger.WarningCount); Assert.Equal(0, logger.ErrorCount); Assert.Contains(message, logger.FullLog); // for the missing project Assert.DoesNotContain(error, logger.FullLog); } /// <summary> /// Verifies that nonexistent projects are skipped when requested when building in parallel. /// DDB # 125831 /// </summary> [Fact] public void SkipNonexistentProjectsBuildingInParallel() { ObjectModelHelpers.DeleteTempProjectDirectory(); ObjectModelHelpers.CreateFileInTempProjectDirectory( "SkipNonexistentProjectsMain.csproj", @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`t` > <MSBuild Projects=`this_project_does_not_exist.csproj;foo.csproj` SkipNonexistentProjects=`true` BuildInParallel=`true` /> </Target> </Project> "); ObjectModelHelpers.CreateFileInTempProjectDirectory( "foo.csproj", @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`t` > <Message Text=`Hello from foo.csproj`/> </Target> </Project> "); MockLogger logger = new MockLogger(_testOutput); ObjectModelHelpers.BuildTempProjectFileExpectSuccess(@"SkipNonexistentProjectsMain.csproj", logger); logger.AssertLogContains("Hello from foo.csproj"); string message = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFoundMessage"), "this_project_does_not_exist.csproj"); string error = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFound"), "this_project_does_not_exist.csproj"); Assert.Equal(0, logger.WarningCount); Assert.Equal(0, logger.ErrorCount); Assert.Contains(message, logger.FullLog); // for the missing project Assert.DoesNotContain(error, logger.FullLog); } [Fact] public void LogErrorWhenBuildingVCProj() { ObjectModelHelpers.DeleteTempProjectDirectory(); ObjectModelHelpers.CreateFileInTempProjectDirectory( "BuildingVCProjMain.csproj", @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`t` > <MSBuild Projects=`blah.vcproj;foo.csproj` StopOnFirstFailure=`false` /> </Target> </Project> "); ObjectModelHelpers.CreateFileInTempProjectDirectory( "foo.csproj", @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`t` > <Message Text=`Hello from foo.csproj`/> </Target> </Project> "); ObjectModelHelpers.CreateFileInTempProjectDirectory( "blah.vcproj", @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <NotWellFormedMSBuildFormatTag /> <Target Name=`t` > <Message Text=`Hello from blah.vcproj`/> </Target> </Project> "); MockLogger logger = new MockLogger(_testOutput); ObjectModelHelpers.BuildTempProjectFileExpectFailure(@"BuildingVCProjMain.csproj", logger); logger.AssertLogContains("Hello from foo.csproj"); string error = String.Format(AssemblyResources.GetString("MSBuild.ProjectUpgradeNeededToVcxProj"), "blah.vcproj"); Assert.Equal(0, logger.WarningCount); Assert.Equal(1, logger.ErrorCount); Assert.Contains(error, logger.FullLog); } #if FEATURE_COMPILE_IN_TESTS /// <summary> /// Regression test for bug 533369. Calling the MSBuild task, passing in a property /// in the Properties parameter that has a special character in its value, such as semicolon. /// However, it's a situation where the project author doesn't have control over the /// property value and so he can't escape it himself. /// </summary> [Fact] public void PropertyOverridesContainSemicolon() { ObjectModelHelpers.DeleteTempProjectDirectory(); // ------------------------------------------------------- // ConsoleApplication1.csproj // ------------------------------------------------------- // Just a normal console application project. ObjectModelHelpers.CreateFileInTempProjectDirectory( @"bug'533'369\Sub;Dir\ConsoleApplication1\ConsoleApplication1.csproj", @" <Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <PropertyGroup> <Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration> <Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform> <OutputType>Exe</OutputType> <AssemblyName>ConsoleApplication1</AssemblyName> </PropertyGroup> <PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> </PropertyGroup> <PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Release|AnyCPU' `> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> </PropertyGroup> <ItemGroup> <Reference Include=`System` /> <Reference Include=`System.Data` /> <Reference Include=`System.Xml` /> </ItemGroup> <ItemGroup> <Compile Include=`Program.cs` /> </ItemGroup> <Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` /> </Project> "); // ------------------------------------------------------- // Program.cs // ------------------------------------------------------- // Just a normal console application project. ObjectModelHelpers.CreateFileInTempProjectDirectory( @"bug'533'369\Sub;Dir\ConsoleApplication1\Program.cs", @" using System; namespace ConsoleApplication32 { class Program { static void Main(string[] args) { Console.WriteLine(`Hello world`); } } } "); // ------------------------------------------------------- // TeamBuild.proj // ------------------------------------------------------- // Attempts to build the above ConsoleApplication1.csproj by calling the MSBuild task, // and overriding the OutDir property. However, the value being passed into OutDir // is coming from another property which is produced by CreateProperty and has // some special characters in it. ObjectModelHelpers.CreateFileInTempProjectDirectory( @"bug'533'369\Sub;Dir\TeamBuild.proj", @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`Build`> <CreateProperty Value=`$(MSBuildProjectDirectory)\binaries\`> <Output PropertyName=`MasterOutDir` TaskParameter=`Value`/> </CreateProperty> <MSBuild Projects=`ConsoleApplication1\ConsoleApplication1.csproj` Properties=`OutDir=$(MasterOutDir)` Targets=`Rebuild`/> </Target> </Project> "); MockLogger logger = new MockLogger(_testOutput); ObjectModelHelpers.BuildTempProjectFileExpectSuccess(@"bug'533'369\Sub;Dir\TeamBuild.proj", logger); ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bug'533'369\Sub;Dir\binaries\ConsoleApplication1.exe"); } #endif /// <summary> /// Check if passing different global properties via metadata works /// </summary> [Fact] public void DifferentGlobalPropertiesWithDefault() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyProp)'=='0'`/> <Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyProp)'=='1'`/> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyProp)'=='0'` /> <Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyProp)'=='1'` /> </Project> "); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + projectFile1 + @"` /> <Projects Include=`" + projectFile1 + @"`> <Properties>MyProp=1</Properties> </Projects> <Projects Include=`" + projectFile2 + @"` /> <Projects Include=`" + projectFile2 + @"`> <Properties>MyProp=1</Properties> </Projects> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)` Properties=`MyProp=0`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; try { Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); ProjectInstance pi = p.CreateProjectInstance(); IDictionary<string, TargetResult> targetOutputs; bool success = pi.Build(null, null, null, out targetOutputs); Assert.True(success); // "Build failed. See 'Standard Out' tab for details." string expectedItemOutputs = string.Format(@" a1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetA b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB g1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetG h1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetH ", projectFile1, projectFile2); Assert.True(targetOutputs.ContainsKey("Build")); Assert.Equal(4, targetOutputs["Build"].Items.Length); ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */); } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } /// <summary> /// Check if passing different global properties via metadata works /// </summary> [Fact] public void DifferentGlobalPropertiesWithoutDefault() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyProp)'=='0'`/> <Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyProp)'=='1'`/> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyProp)'=='0'` /> <Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyProp)'=='1'` /> </Project> "); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + projectFile1 + @"` /> <Projects Include=`" + projectFile1 + @"`> <Properties>MyProp=1</Properties> </Projects> <Projects Include=`" + projectFile2 + @"` /> <Projects Include=`" + projectFile2 + @"`> <Properties>MyProp=1</Properties> </Projects> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; try { Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); ProjectInstance pi = p.CreateProjectInstance(); IDictionary<string, TargetResult> targetOutputs; bool success = pi.Build(null, null, null, out targetOutputs); Assert.True(success); // "Build failed. See 'Standard Out' tab for details." string expectedItemOutputs = string.Format(@" b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB h1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetH ", projectFile1, projectFile2); Assert.True(targetOutputs.ContainsKey("Build")); Assert.Equal(2, targetOutputs["Build"].Items.Length); ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */); } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } /// <summary> /// Check trailing semicolons are ignored /// </summary> [Fact] public void VariousPropertiesToMSBuildTask() { string projectFile = null; try { projectFile = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <PR Include='$(MSBuildProjectFullPath)'> <Properties>a=a;b=b;</Properties> <AdditionalProperties>e=e;g=1;f=f;</AdditionalProperties> <UndefineProperties>g;h;</UndefineProperties> </PR> </ItemGroup> <Target Name='a'> <MSBuild Projects='@(PR)' Properties='c=c;d=d;' RemoveProperties='i;c;' Targets='b'/> </Target> <Target Name='b'> <Message Text='a=[$(a)]' Importance='High' /> <Message Text='b=[$(b)]' Importance='High' /> <Message Text='c=[$(c)]' Importance='High' /> <Message Text='d=[$(d)]' Importance='High' /> <Message Text='e=[$(e)]' Importance='High' /> <Message Text='f=[$(f)]' Importance='High' /> <Message Text='g=[$(g)]' Importance='High' /> </Target> </Project> "); MockLogger logger = new MockLogger(_testOutput); ObjectModelHelpers.BuildTempProjectFileExpectSuccess(projectFile, logger); Console.WriteLine(logger.FullLog); logger.AssertLogContains("a=[a]"); logger.AssertLogContains("b=[b]"); logger.AssertLogContains("c=[]"); logger.AssertLogContains("d=[]"); logger.AssertLogContains("e=[e]"); logger.AssertLogContains("f=[f]"); logger.AssertLogContains("g=[]"); } finally { File.Delete(projectFile); } } /// <summary> /// Check if passing different global properties via metadata works /// </summary> [Fact] public void DifferentGlobalPropertiesWithBlanks() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyProp)'=='0'`/> <Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyProp)'=='1'`/> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyProp)'=='0'` /> <Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyProp)'=='1'` /> </Project> "); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + projectFile1 + @"` /> <Projects Include=`" + projectFile1 + @"`> <Properties></Properties> </Projects> <Projects Include=`" + projectFile2 + @"` /> <Projects Include=`" + projectFile2 + @"`> <Properties>MyProp=1</Properties> </Projects> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; try { Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); ProjectInstance pi = p.CreateProjectInstance(); IDictionary<string, TargetResult> targetOutputs; bool success = pi.Build(null, null, null, out targetOutputs); Assert.True(success); // "Build failed. See 'Standard Out' tab for details." string expectedItemOutputs = string.Format(@" h1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetH ", projectFile2); Assert.True(targetOutputs.ContainsKey("Build")); Assert.Single(targetOutputs["Build"].Items); ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */); } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } /// <summary> /// Check if passing different global properties via metadata works /// </summary> [Fact] public void DifferentGlobalPropertiesInvalid() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyProp)'=='0'`/> <Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyProp)'=='1'`/> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyProp)'=='0'` /> <Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyProp)'=='1'` /> </Project> "); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + projectFile1 + @"` /> <Projects Include=`" + projectFile1 + @"`> <Properties>=1</Properties> </Projects> <Projects Include=`" + projectFile2 + @"` /> <Projects Include=`" + projectFile2 + @"`> <Properties>=;1</Properties> </Projects> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; try { Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); bool success = p.Build(); Assert.False(success); // "Build succeeded. See 'Standard Out' tab for details." } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } /// <summary> /// Check if passing additional global properties via metadata works /// </summary> [Fact] public void DifferentAdditionalPropertiesWithDefault() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyPropG)'=='1'`/> <Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyPropA)'=='1'`/> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyPropG)'=='1'` /> <Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyPropA)'=='1'` /> </Project> "); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + projectFile1 + @"`> <AdditionalProperties>MyPropA=1</AdditionalProperties> </Projects> <Projects Include=`" + projectFile2 + @"`> <AdditionalProperties>MyPropA=0</AdditionalProperties> </Projects> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)` Properties=`MyPropG=1`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; try { Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); ProjectInstance pi = p.CreateProjectInstance(); IDictionary<string, TargetResult> targetOutputs; bool success = pi.Build(null, null, null, out targetOutputs); Assert.True(success); // "Build failed. See 'Standard Out' tab for details." string expectedItemOutputs = string.Format(@" a1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetA b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB g1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetG ", projectFile1, projectFile2); Assert.True(targetOutputs.ContainsKey("Build")); Assert.Equal(3, targetOutputs["Build"].Items.Length); ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */); } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } /// <summary> /// Check if passing additional global properties via metadata works /// </summary> [Fact] public void DifferentAdditionalPropertiesWithGlobalProperties() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyPropG)'=='0'`/> <Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyPropA)'=='1'`/> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyPropG)'=='0'` /> <Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyPropA)'=='1'` /> </Project> "); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + projectFile1 + @"`> <Properties>MyPropG=1</Properties> <AdditionalProperties>MyPropA=1</AdditionalProperties> </Projects> <Projects Include=`" + projectFile2 + @"`> <Properties>MyPropG=0</Properties> <AdditionalProperties>MyPropA=1</AdditionalProperties> </Projects> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)` Properties=`MyPropG=1`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; try { Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); ProjectInstance pi = p.CreateProjectInstance(); IDictionary<string, TargetResult> targetOutputs; bool success = pi.Build(null, null, null, out targetOutputs); Assert.True(success); // "Build failed. See 'Standard Out' tab for details." string expectedItemOutputs = string.Format(@" b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB g1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetG h1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetH ", projectFile1, projectFile2); Assert.True(targetOutputs.ContainsKey("Build")); Assert.Equal(3, targetOutputs["Build"].Items.Length); ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */); } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } /// <summary> /// Check if passing additional global properties via metadata works /// </summary> [Fact] public void DifferentAdditionalPropertiesWithoutDefault() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyPropG)'=='1'`/> <Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyPropA)'=='1'`/> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyPropG)'=='1'` /> <Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyPropA)'=='1'` /> </Project> "); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + projectFile1 + @"`> <AdditionalProperties>MyPropA=1</AdditionalProperties> </Projects> <Projects Include=`" + projectFile2 + @"`> <AdditionalProperties>MyPropA=1</AdditionalProperties> </Projects> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; try { Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); ProjectInstance pi = p.CreateProjectInstance(); IDictionary<string, TargetResult> targetOutputs; bool success = pi.Build(null, null, null, out targetOutputs); Assert.True(success); // "Build failed. See 'Standard Out' tab for details." string expectedItemOutputs = string.Format(@" b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB h1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetH ", projectFile1, projectFile2); Assert.True(targetOutputs.ContainsKey("Build")); Assert.Equal(2, targetOutputs["Build"].Items.Length); ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */); } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } /// <summary> /// Properties and Targets that use non-standard separation chars /// </summary> [Fact] public void TargetsWithSeparationChars() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`Build` xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <Target Name=`Clean` /> <Target Name=`Build` /> <Target Name=`BuildAgain` /> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`Build` xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <PropertyGroup> <Targets>Clean%3BBuild%3CBuildAgain</Targets> </PropertyGroup> <ItemGroup> <ProjectFile Include=`" + projectFile1 + @"` /> </ItemGroup> <Target Name=`Build` Outputs=`$(SomeOutputs)`> <MSBuild Projects=`@(ProjectFile)` Targets=`$(Targets)` TargetAndPropertyListSeparators=`%3B;%3C` /> </Target> </Project> "); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + projectFile2 + @"` /> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; try { Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); bool success = p.Build(); Assert.True(success); // "Build failed. See 'Standard Out' tab for details." } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } /// <summary> /// Verify stopOnFirstFailure with BuildInParallel override message are correctly logged /// Also verify stop on first failure will not build the second project if the first one failed /// The Aardvark tests which also test StopOnFirstFailure are at: /// qa\md\wd\DTP\MSBuild\ShippingExtensions\ShippingTasks\MSBuild\_Tst\MSBuild.StopOnFirstFailure /// </summary> [Fact] public void StopOnFirstFailureandBuildInParallelSingleNode() { string project1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='msbuild'> <Error Text='Error'/> </Target> </Project> "); string project2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='msbuild'> <Message Text='SecondProject'/> </Target> </Project> "); try { ITaskItem[] projects = new ITaskItem[] { new TaskItem(project1), new TaskItem(project2) }; // Test the various combinations of BuildInParallel and StopOnFirstFailure when the msbuild task is told there are not multiple nodes // running in the system for (int i = 0; i < 4; i++) { bool buildInParallel = false; bool stopOnFirstFailure = false; // first set up the project being built. switch (i) { case 0: buildInParallel = true; stopOnFirstFailure = true; break; case 1: buildInParallel = true; stopOnFirstFailure = false; break; case 2: buildInParallel = false; stopOnFirstFailure = true; break; case 3: buildInParallel = false; stopOnFirstFailure = false; break; } string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + project1 + @"` /> <Projects Include=`" + project2 + @"` /> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)` Targets=`msbuild` BuildInParallel=`" + buildInParallel.ToString() + @"` StopOnFirstFailure=`" + stopOnFirstFailure.ToString() + @"`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; MockLogger logger = new MockLogger(); Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents, logger); bool success = p.Build(logger); switch (i) { case 0: // Verify setting BuildInParallel and StopOnFirstFailure to // true will cause the msbuild task to set BuildInParallel to false during the execute // Verify build did not build second project which has the message SecondProject logger.AssertLogDoesntContain("SecondProject"); // Verify the correct msbuild task messages are in the log logger.AssertLogContains(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure")); logger.AssertLogContains(AssemblyResources.GetString("MSBuild.NotBuildingInParallel")); break; case 1: // Verify setting BuildInParallel to true and StopOnFirstFailure to // false will cause no change in BuildInParallel // Verify build did build second project which has the message SecondProject logger.AssertLogContains("SecondProject"); // Verify the correct msbuild task messages are in the log logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel")); break; case 2: // Verify build did not build second project which has the message SecondProject logger.AssertLogDoesntContain("SecondProject"); // Verify the correct msbuild task messages are in the log logger.AssertLogContains(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel")); break; case 3: // Verify setting BuildInParallel to false and StopOnFirstFailure to // false will cause no change in BuildInParallel // Verify build did build second project which has the message SecondProject logger.AssertLogContains("SecondProject"); // Verify the correct msbuild task messages are in the log logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel")); break; } // The build should fail as the first project has an error Assert.False(success, "Iteration of i " + i + " Build Succeeded. See 'Standard Out' tab for details."); } } finally { File.Delete(project1); File.Delete(project2); } } #if FEATURE_APPDOMAIN /// <summary> /// Verify stopOnFirstFailure with BuildInParallel override message are correctly logged when there are multiple nodes /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void StopOnFirstFailureandBuildInParallelMultipleNode() { string project1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='msbuild'> <Error Text='Error'/> </Target> </Project> "); string project2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='msbuild'> <Message Text='SecondProject'/> </Target> </Project> "); try { // Test the various combinations of BuildInParallel and StopOnFirstFailure when the msbuild task is told there are multiple nodes // running in the system for (int i = 0; i < 4; i++) { bool buildInParallel = false; bool stopOnFirstFailure = false; // first set up the project being built. switch (i) { case 0: buildInParallel = true; stopOnFirstFailure = true; break; case 1: buildInParallel = true; stopOnFirstFailure = false; break; case 2: buildInParallel = false; stopOnFirstFailure = true; break; case 3: buildInParallel = false; stopOnFirstFailure = false; break; } string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + project1 + @"` /> <Projects Include=`" + project2 + @"` /> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)` Targets=`msbuild` BuildInParallel=`" + buildInParallel.ToString() + @"` StopOnFirstFailure=`" + stopOnFirstFailure.ToString() + @"`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; MockLogger logger = new MockLogger(); ProjectCollection pc = new ProjectCollection(null, new List<ILogger> { logger }, null, ToolsetDefinitionLocations.Default, 2, false); Project p = ObjectModelHelpers.CreateInMemoryProject(pc, parentProjectContents, logger); bool success = p.Build(); switch (i) { case 0: // Verify build did build second project which has the message SecondProject logger.AssertLogContains("SecondProject"); // Verify the correct msbuild task messages are in the log logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects")); logger.AssertLogContains(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel")); break; case 1: // Verify setting BuildInParallel to true and StopOnFirstFailure to // false will cause no change in BuildInParallel // Verify build did build second project which has the message SecondProject logger.AssertLogContains("SecondProject"); // Verify the correct msbuild task messages are in the log logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel")); break; case 2: // Verify setting BuildInParallel to false and StopOnFirstFailure to // true will cause no change in BuildInParallel // Verify build did not build second project which has the message SecondProject logger.AssertLogDoesntContain("SecondProject"); // Verify the correct msbuild task messages are in the log logger.AssertLogContains(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel")); break; case 3: // Verify setting BuildInParallel to false and StopOnFirstFailure to // false will cause no change in BuildInParallel // Verify build did build second project which has the message SecondProject logger.AssertLogContains("SecondProject"); // Verify the correct msbuild task messages are in the log logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure")); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel")); break; } // The build should fail as the first project has an error Assert.False(success, "Iteration of i " + i + " Build Succeeded. See 'Standard Out' tab for details."); } } finally { File.Delete(project1); File.Delete(project2); } } #endif /// <summary> /// Test the skipping of the remaining projects. Verify the skip message is only displayed when there are projects to skip. /// </summary> [Fact] public void SkipRemainingProjects() { string project1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='msbuild'> <Error Text='Error'/> </Target> </Project> "); string project2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='msbuild'> <Message Text='SecondProject'/> </Target> </Project> "); try { string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + project1 + @"` /> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)` Targets=`msbuild` BuildInParallel=`false` StopOnFirstFailure=`true`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; MockLogger logger = new MockLogger(); ProjectCollection pc = new ProjectCollection(null, new List<ILogger> { logger }, null, ToolsetDefinitionLocations.Default, 2, false); Project p = ObjectModelHelpers.CreateInMemoryProject(pc, parentProjectContents, logger); bool success = p.Build(); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects")); Assert.False(success); // "Build Succeeded. See 'Standard Out' tab for details." parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + project2 + @"` /> <Projects Include=`" + project1 + @"` /> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)` Targets=`msbuild` BuildInParallel=`false` StopOnFirstFailure=`true`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; MockLogger logger2 = new MockLogger(); Project p2 = ObjectModelHelpers.CreateInMemoryProject(pc, parentProjectContents, logger2); bool success2 = p2.Build(); logger2.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects")); Assert.False(success2); // "Build Succeeded. See 'Standard Out' tab for details." } finally { File.Delete(project1); File.Delete(project2); } } /// <summary> /// Verify the behavior of Target execution with StopOnFirstFailure /// </summary> [Fact] public void TargetStopOnFirstFailureBuildInParallel() { string project1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='T1'> <Message Text='Proj2 T1 message'/> </Target> <Target Name='T2'> <Message Text='Proj2 T2 message'/> </Target> <Target Name='T3'> <Error Text='Error'/> </Target> </Project> "); try { ITaskItem[] projects = new ITaskItem[] { new TaskItem(project1) }; for (int i = 0; i < 6; i++) { bool stopOnFirstFailure = false; bool runEachTargetSeparately = false; string target1 = String.Empty; string target2 = String.Empty; string target3 = String.Empty; switch (i) { case 0: stopOnFirstFailure = true; runEachTargetSeparately = true; target1 = "T1"; target2 = "T2"; target3 = "T3"; break; case 1: stopOnFirstFailure = true; runEachTargetSeparately = true; target1 = "T1"; target2 = "T3"; target3 = "T2"; break; case 2: stopOnFirstFailure = false; runEachTargetSeparately = true; target1 = "T1"; target2 = "T3"; target3 = "T2"; break; case 3: stopOnFirstFailure = true; target1 = "T1"; target2 = "T2"; target3 = "T3"; break; case 4: stopOnFirstFailure = true; target1 = "T1"; target2 = "T3"; target3 = "T2"; break; case 5: stopOnFirstFailure = false; target1 = "T1"; target2 = "T3"; target3 = "T2"; break; } string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + project1 + @"` /> </ItemGroup> <ItemGroup> <Targets Include=`" + target1 + @"` /> <Targets Include=`" + target2 + @"` /> <Targets Include=`" + target3 + @"` /> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)` Targets=`@(Targets)` StopOnFirstFailure=`" + stopOnFirstFailure.ToString() + @"` RunEachTargetSeparately=`" + runEachTargetSeparately.ToString() + @"`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; MockLogger logger = new MockLogger(); Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents, logger); bool success = p.Build(); switch (i) { case 0: // Test the case where the error is in the last project and RunEachTargetSeparately = true logger.AssertLogContains("Proj2 T1 message"); logger.AssertLogContains("Proj2 T2 message"); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets")); break; case 1: // Test the case where the error is in the second target out of 3. logger.AssertLogContains("Proj2 T1 message"); logger.AssertLogContains(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets")); logger.AssertLogDoesntContain("Proj2 T2 message"); // The build should fail as the first project has an error break; case 2: // Test case where error is in second last target but stopOnFirstFailure is false logger.AssertLogContains("Proj2 T1 message"); logger.AssertLogContains("Proj2 T2 message"); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets")); break; // Test the cases where RunEachTargetSeparately is false. In these cases all of the targets should be submitted at once case 3: // Test the case where the error is in the last project and RunEachTargetSeparately = true logger.AssertLogContains("Proj2 T1 message"); logger.AssertLogContains("Proj2 T2 message"); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets")); // The build should fail as the first project has an error break; case 4: // Test the case where the error is in the second target out of 3. logger.AssertLogContains("Proj2 T1 message"); logger.AssertLogDoesntContain("Proj2 T2 message"); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets")); // The build should fail as the first project has an error break; case 5: // Test case where error is in second last target but stopOnFirstFailure is false logger.AssertLogContains("Proj2 T1 message"); logger.AssertLogDoesntContain("Proj2 T2 message"); logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets")); break; } // The build should fail as the first project has an error Assert.False(success, "Iteration of i:" + i + "Build Succeeded. See 'Standard Out' tab for details."); } } finally { File.Delete(project1); } } /// <summary> /// Properties and Targets that use non-standard separation chars /// </summary> [Fact] public void PropertiesWithSeparationChars() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`Build` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`Build` Outputs=`|$(a)|$(b)|$(C)|$(D)|` /> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`Build` xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <PropertyGroup> <AValues>a%3BA</AValues> <BValues>b;B</BValues> <CValues>c;C</CValues> <DValues>d%3BD</DValues> </PropertyGroup> <ItemGroup> <ProjectFile Include=`" + projectFile1 + @"`> <AdditionalProperties>C=$(CValues)%3BD=$(DValues)</AdditionalProperties> </ProjectFile> </ItemGroup> <Target Name=`Build` Outputs=`$(SomeOutputs)`> <MSBuild Projects=`@(ProjectFile)` Targets=`Build` Properties=`a=$(AValues)%3Bb=$(BValues)` TargetAndPropertyListSeparators=`%3B`> <Output TaskParameter=`TargetOutputs` PropertyName=`SomeOutputs`/> </MSBuild> </Target> </Project> "); string parentProjectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Projects Include=`" + projectFile2 + @"` /> </ItemGroup> <Target Name=`Build` Returns=`@(Outputs)`> <MSBuild Projects=`@(Projects)`> <Output TaskParameter=`TargetOutputs` ItemName=`Outputs` /> </MSBuild> </Target> </Project>"; try { ITaskItem[] projects = new ITaskItem[] { new TaskItem(projectFile2) }; Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents); ProjectInstance pi = p.CreateProjectInstance(); IDictionary<string, TargetResult> targetOutputs; bool success = pi.Build(null, null, null, out targetOutputs); Assert.True(success); // "Build failed. See 'Standard Out' tab for details." Assert.True(targetOutputs.ContainsKey("Build")); Assert.Equal(5, targetOutputs["Build"].Items.Length); Assert.Equal("|a", targetOutputs["Build"].Items[0].ItemSpec); Assert.Equal("A|b", targetOutputs["Build"].Items[1].ItemSpec); Assert.Equal("B|c", targetOutputs["Build"].Items[2].ItemSpec); Assert.Equal("C|d", targetOutputs["Build"].Items[3].ItemSpec); Assert.Equal("D|", targetOutputs["Build"].Items[4].ItemSpec); } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } /// <summary> /// Orcas had a bug that if the target casing specified was not correct, we would still build it, /// but not return any target outputs! /// </summary> [Fact] public void TargetNameIsCaseInsensitive() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`Build` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'> <Target Name=`bUiLd` Outputs=`foo.out` /> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project DefaultTargets=`t` xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <Target Name=`t`> <MSBuild Projects=`" + projectFile1 + @"` Targets=`BUILD`> <Output TaskParameter=`TargetOutputs` ItemName=`out`/> </MSBuild> <Message Text=`[@(out)]`/> </Target> </Project> "); try { Project project = new Project(projectFile2); MockLogger logger = new MockLogger(); Assert.True(project.Build(logger)); logger.AssertLogContains("[foo.out]"); } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } [Fact] public void ProjectFileWithoutNamespaceBuilds() { string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project> <Target Name=`Build` Outputs=`foo.out` /> </Project> "); string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project> <Target Name=`t`> <MSBuild Projects=`" + projectFile1 + @"` Targets=`Build`> <Output TaskParameter=`TargetOutputs` ItemName=`out`/> </MSBuild> <Message Text=`[@(out)]`/> </Target> </Project> "); try { Project project = new Project(projectFile2); MockLogger logger = new MockLogger(); Assert.True(project.Build(logger)); logger.AssertLogContains("[foo.out]"); } finally { File.Delete(projectFile1); File.Delete(projectFile2); } } } }
#region Copyright notice and license // Copyright 2015 gRPC 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.Threading; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// Options for calls made by client. /// </summary> public struct CallOptions { Metadata headers; DateTime? deadline; CancellationToken cancellationToken; WriteOptions writeOptions; ContextPropagationToken propagationToken; CallCredentials credentials; CallFlags flags; /// <summary> /// Creates a new instance of <c>CallOptions</c> struct. /// </summary> /// <param name="headers">Headers to be sent with the call.</param> /// <param name="deadline">Deadline for the call to finish. null means no deadline.</param> /// <param name="cancellationToken">Can be used to request cancellation of the call.</param> /// <param name="writeOptions">Write options that will be used for this call.</param> /// <param name="propagationToken">Context propagation token obtained from <see cref="ServerCallContext"/>.</param> /// <param name="credentials">Credentials to use for this call.</param> public CallOptions(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken), WriteOptions writeOptions = null, ContextPropagationToken propagationToken = null, CallCredentials credentials = null) { this.headers = headers; this.deadline = deadline; this.cancellationToken = cancellationToken; this.writeOptions = writeOptions; this.propagationToken = propagationToken; this.credentials = credentials; this.flags = default(CallFlags); } /// <summary> /// Headers to send at the beginning of the call. /// </summary> public Metadata Headers { get { return headers; } } /// <summary> /// Call deadline. /// </summary> public DateTime? Deadline { get { return deadline; } } /// <summary> /// Token that can be used for cancelling the call on the client side. /// Cancelling the token will request cancellation /// of the remote call. Best effort will be made to deliver the cancellation /// notification to the server and interaction of the call with the server side /// will be terminated. Unless the call finishes before the cancellation could /// happen (there is an inherent race), /// the call will finish with <c>StatusCode.Cancelled</c> status. /// </summary> public CancellationToken CancellationToken { get { return cancellationToken; } } /// <summary> /// Write options that will be used for this call. /// </summary> public WriteOptions WriteOptions { get { return this.writeOptions; } } /// <summary> /// Token for propagating parent call context. /// </summary> public ContextPropagationToken PropagationToken { get { return this.propagationToken; } } /// <summary> /// Credentials to use for this call. /// </summary> public CallCredentials Credentials { get { return this.credentials; } } /// <summary> /// If <c>true</c> and and channel is in <c>ChannelState.TransientFailure</c>, the call will attempt waiting for the channel to recover /// instead of failing immediately (which is the default "FailFast" semantics). /// Note: experimental API that can change or be removed without any prior notice. /// </summary> public bool IsWaitForReady { get { return (this.flags & CallFlags.WaitForReady) == CallFlags.WaitForReady; } } /// <summary> /// Flags to use for this call. /// </summary> internal CallFlags Flags { get { return this.flags; } } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Headers</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="headers">The headers.</param> public CallOptions WithHeaders(Metadata headers) { var newOptions = this; newOptions.headers = headers; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Deadline</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="deadline">The deadline.</param> public CallOptions WithDeadline(DateTime deadline) { var newOptions = this; newOptions.deadline = deadline; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>CancellationToken</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> public CallOptions WithCancellationToken(CancellationToken cancellationToken) { var newOptions = this; newOptions.cancellationToken = cancellationToken; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>WriteOptions</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="writeOptions">The write options.</param> public CallOptions WithWriteOptions(WriteOptions writeOptions) { var newOptions = this; newOptions.writeOptions = writeOptions; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>PropagationToken</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="propagationToken">The context propagation token.</param> public CallOptions WithPropagationToken(ContextPropagationToken propagationToken) { var newOptions = this; newOptions.propagationToken = propagationToken; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Credentials</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="credentials">The call credentials.</param> public CallOptions WithCredentials(CallCredentials credentials) { var newOptions = this; newOptions.credentials = credentials; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with "WaitForReady" semantics enabled/disabled. /// <see cref="IsWaitForReady"/>. /// Note: experimental API that can change or be removed without any prior notice. /// </summary> public CallOptions WithWaitForReady(bool waitForReady = true) { if (waitForReady) { return WithFlags(this.flags | CallFlags.WaitForReady); } return WithFlags(this.flags & ~CallFlags.WaitForReady); } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Flags</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="flags">The call flags.</param> internal CallOptions WithFlags(CallFlags flags) { var newOptions = this; newOptions.flags = flags; return newOptions; } /// <summary> /// Returns a new instance of <see cref="CallOptions"/> with /// all previously unset values set to their defaults and deadline and cancellation /// token propagated when appropriate. /// </summary> internal CallOptions Normalize() { var newOptions = this; // silently ignore the context propagation token if it wasn't produced by "us" var propagationTokenImpl = propagationToken.AsImplOrNull(); if (propagationTokenImpl != null) { if (propagationTokenImpl.Options.IsPropagateDeadline) { GrpcPreconditions.CheckArgument(!newOptions.deadline.HasValue, "Cannot propagate deadline from parent call. The deadline has already been set explicitly."); newOptions.deadline = propagationTokenImpl.ParentDeadline; } if (propagationTokenImpl.Options.IsPropagateCancellation) { GrpcPreconditions.CheckArgument(!newOptions.cancellationToken.CanBeCanceled, "Cannot propagate cancellation token from parent call. The cancellation token has already been set to a non-default value."); newOptions.cancellationToken = propagationTokenImpl.ParentCancellationToken; } } newOptions.headers = newOptions.headers ?? Metadata.Empty; newOptions.deadline = newOptions.deadline ?? DateTime.MaxValue; return newOptions; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using error = Microsoft.Build.Shared.ErrorUtilities; namespace Microsoft.Build.Conversion { /// <summary> /// This class implements a custom text reader for the old VS7/Everett /// project file format. The old format allowed certain XML special /// characters to be present within an XML attribute value. For example, /// /// &lt;MyElement MyAttribute="My --> Value" /&gt; /// /// However, the System.Xml classes are more strict, and do not allow /// the &lt; or &gt; characters to exist within an attribute value. But /// the conversion utility still needs to be able to convert all old /// project files. So the OldVSProjectFileReader class implements /// the TextReader interface, thereby effectively intercepting all of /// the calls which are used by the XmlTextReader to actually read the /// raw text out of the file. As we are reading the text out of the /// file, we replace all &gt; (less-than) characters inside attribute values with "&gt;", /// etc. The XmlTextReader has no idea that this is going on, but /// no longer complains about invalid characters. /// </summary> /// <owner>rgoel</owner> internal sealed class OldVSProjectFileReader : TextReader { // This is the underlying text file where we will be reading the raw text // from. private StreamReader oldVSProjectFile; // We will be reading one line at a time out of the text file, and caching // it here. private StringBuilder singleLine; // The "TextReader" interface that we are implementing only allows // forward access through the file. You cannot seek to a random location // or read backwards. This variable is the index into the "singleLine" // string above, which indicates how far the caller has read. Once we // reach the end of "singleLine", we'll go read a new line from the file. private int currentReadPositionWithinSingleLine; /// <summary> /// Constructor, initialized using the filename of an existing old format /// project file on disk. /// </summary> /// <owner>rgoel</owner> /// <param name="filename"></param> internal OldVSProjectFileReader ( string filename ) { this.oldVSProjectFile = new StreamReader(filename, Encoding.Default); // HIGHCHAR: Default means ANSI, ANSI is what VS .NET 2003 wrote. Without this, the project would be read as ASCII. this.singleLine = new StringBuilder(); this.currentReadPositionWithinSingleLine = 0; } /// <summary> /// Releases all locks and closes all handles on the underlying file. /// </summary> /// <owner>rgoel</owner> public override void Close ( ) { oldVSProjectFile.Close(); } /// <summary> /// Returns the next character in the file, without actually advancing /// the read pointer. Returns -1 if we're already at the end of the file. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> public override int Peek ( ) { // If necessary, read a new line of text into our internal buffer // (this.singleLine). if (!this.ReadLineIntoInternalBuffer()) { // If we've reached the end of the file, return -1. return -1; } // Return the next character, but don't advance the current position. return this.singleLine[this.currentReadPositionWithinSingleLine]; } /// <summary> /// Returns the next character in the file, and advances the read pointer. /// Returns -1 if we're already at the end of the file. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> public override int Read ( ) { // Use our "Peek" functionality above. int returnCharacter = this.Peek(); // If there's a character there, advance the read pointer by one. if (returnCharacter != -1) { this.currentReadPositionWithinSingleLine++; } return returnCharacter; } /// <summary> /// Reads the specified number of characters into the caller's buffer, /// starting at the specified index into the caller's buffer. Returns /// the number of characters read, or 0 if we're already at the end of /// the file. /// </summary> /// <param name="bufferToReadInto"></param> /// <param name="startIndexIntoBuffer"></param> /// <param name="charactersToRead"></param> /// <returns></returns> /// <owner>rgoel</owner> public override int Read ( char[] bufferToReadInto, // The buffer to read the data into. int startIndexIntoBuffer, // The index into "bufferToReadInto" int charactersToRead // The number of characters to read. ) { // Make sure there's enough room in the caller's buffer for what he's // asking us to do. if ((startIndexIntoBuffer + charactersToRead) > bufferToReadInto.Length) { // End-user should never see this message, so it doesn't need to be localized. throw new ArgumentException("Cannot write past end of user's buffer.", nameof(charactersToRead)); } int charactersCopied = 0; // Keep looping until we've read in the number of characters requested. // If we reach the end of file, we'll break out early. while (0 < charactersToRead) { // Read more data from the underlying file if necessary. if (!this.ReadLineIntoInternalBuffer()) { // If we've reached the end of the underlying file, exit the // loop. break; } // We're going to copy characters from our cached singleLine to the caller's // buffer. The number of characters to copy is the lesser of (the remaining // characters in our cached singleLine) and (the number of characters remaining // before we've fulfilled the caller's request). int charactersToCopy = (this.singleLine.Length - currentReadPositionWithinSingleLine); if (charactersToCopy > charactersToRead) { charactersToCopy = charactersToRead; } // Copy characters from our cached "singleLine" to the caller's buffer. this.singleLine.ToString().CopyTo(this.currentReadPositionWithinSingleLine, bufferToReadInto, startIndexIntoBuffer, charactersToCopy); // Update all counts and indices. startIndexIntoBuffer += charactersToCopy; this.currentReadPositionWithinSingleLine += charactersToCopy; charactersCopied += charactersToCopy; charactersToRead -= charactersToCopy; } return charactersCopied; } /// <summary> /// Not implemented. Our class only supports reading from a file, which /// can't change beneath the covers while we're reading from it. Therefore, /// a blocking read doesn't make sense for our scenario. (A blocking read /// is where you wait until the requested number of characters actually /// become available ... which is never going to happen if you've already /// reached the end of a file.) /// </summary> /// <param name="bufferToReadInto"></param> /// <param name="startIndexIntoBuffer"></param> /// <param name="charactersToRead"></param> /// <returns></returns> /// <owner>rgoel</owner> public override int ReadBlock ( char[] bufferToReadInto, int startIndexIntoBuffer, int charactersToRead ) { throw new NotImplementedException(); } /// <summary> /// Reads a single line of text, and returns it as a string, not including the /// terminating line-ending characters. If we were at the end of the file, /// return null. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> public override string ReadLine ( ) { // Read a new line from the underlying file if necessary (that is, only // if our currently cached singleLine has already been used up). if (!this.ReadLineIntoInternalBuffer()) { // If we reached the end of the underlying file, return null. return null; } // We now have a single line of text cached in our "singleLine" variable. // Just return that, or the portion of that which hasn't been already read // by the caller). string result = this.singleLine.ToString(this.currentReadPositionWithinSingleLine, this.singleLine.Length - this.currentReadPositionWithinSingleLine); // The caller has read the entirety of our cached "singleLine", so update // our read pointer accordingly. this.currentReadPositionWithinSingleLine = this.singleLine.Length; // Strip off the line endings before returning to caller. char[] lineEndingCharacters = new char[] {'\r', '\n'}; return result.Trim(lineEndingCharacters); } /// <summary> /// Reads the remainder of the file, and returns it as a string. Returns /// an empty string if we've already reached the end of the file. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> public override string ReadToEnd ( ) { // This is what we're going to return to the caller. StringBuilder result = new StringBuilder(); // Keep reading lines of text out of the underlying file, one line at // a time. while (true) { if (!this.ReadLineIntoInternalBuffer()) { // Exit the loop when we've reached the end of the underlying // file. break; } // Append the line of text to the resulting output. result.Append(this.singleLine.ToString(this.currentReadPositionWithinSingleLine, this.singleLine.Length - this.currentReadPositionWithinSingleLine)); this.currentReadPositionWithinSingleLine = this.singleLine.Length; } return result.ToString(); } /// <summary> /// And this is where the real magic happens. If our currently cached /// "singleLine" has been used up, we read a new line of text from the /// underlying text file. But as we read the line of text from the file, /// we immediately replace all instances of special characters that occur /// within double-quotes with the corresponding XML-friendly equivalents. /// For example, if the underlying text file contained this: /// /// &lt;MyElement MyAttribute="My --&gt; Value" /&gt; /// /// then we would read it in and immediately convert it to this: /// /// &lt;MyElement MyAttribute="My --&gt; Value" /&gt; /// /// and we would store it this way in our "singleLine", so that the callers /// never know the difference. /// /// This method returns true on success, and false if we were unable to /// read a new line (due to end of file). /// </summary> /// <returns></returns> /// <owner>rgoel</owner> private bool ReadLineIntoInternalBuffer ( ) { // Only do the work if we've already used up the data in the currently // cached "singleLine". if (this.currentReadPositionWithinSingleLine >= this.singleLine.Length) { // Read a line of text from the underlying file. string lineFromProjectFile = this.oldVSProjectFile.ReadLine(); if (lineFromProjectFile == null) { // If we've reached the end of the file, return false. return false; } // Take the line of text just read, and replace all special characters // with the escaped XML-friendly string equivalents. this.singleLine = new StringBuilder(this.ReplaceSpecialCharacters(lineFromProjectFile)); // The underlying StreamReader.ReadLine method doesn't give us the // trailing line endings, so add them back ourselves. this.singleLine.Append(Environment.NewLine); // So now we have a new cached "singleLine". Reset the read pointer // to the beginning of the new line just read. this.currentReadPositionWithinSingleLine = 0; } return true; } /// <summary> /// This method uses a regular expression to search for the stuff in /// between double-quotes. We obviously don't want to touch the stuff /// OUTSIDE of double-quotes, because then we would be mucking with the /// real angle-brackets that delimit the XML element names, etc. /// </summary> /// <param name="originalLine"></param> /// <returns></returns> /// <owner>rgoel</owner> private string ReplaceSpecialCharacters ( string originalLine ) { // Find the stuff within double-quotes, and send it off to the // "ReplaceSpecialCharactersInXmlAttribute" for proper replacement of // the special characters. Regex attributeValueInsideDoubleQuotesPattern = new Regex("= *\"[^\"]*\""); string replacedStuffInsideDoubleQuotes = attributeValueInsideDoubleQuotesPattern.Replace(originalLine, new MatchEvaluator(this.ReplaceSpecialCharactersInXmlAttribute)); // Find the stuff within single-quotes, and send it off to the // "ReplaceSpecialCharactersInXmlAttribute" for proper replacement of // the special characters. Regex attributeValueInsideSingleQuotesPattern = new Regex("= *'[^']*'"); string replacedStuffInsideSingleQuotes = attributeValueInsideSingleQuotesPattern.Replace(replacedStuffInsideDoubleQuotes, new MatchEvaluator(this.ReplaceSpecialCharactersInXmlAttribute)); return replacedStuffInsideSingleQuotes; } /// <summary> /// This method is used as the delegate that is passed into Regex.Replace. /// It a regular expression to search for the stuff in /// between double-quotes. We obviously don't want to touch the stuff /// OUTSIDE of double-quotes, because then we would be mucking with the /// real angle-brackets that delimit the XML element names, etc. /// </summary> /// <param name="xmlAttribute"></param> /// <returns></returns> /// <owner>RGoel</owner> private string ReplaceSpecialCharactersInXmlAttribute ( Match xmlAttribute ) { // We've been given the string for the attribute value (i.e., all the stuff // within double-quotes, including the double-quotes). Replace all the special characters // within it, and return the new string. return ReplaceSpecialCharactersInXmlAttributeString(xmlAttribute.Value); } /// <summary> /// This method actually does the replacement of special characters within the /// text of the XML attribute. /// </summary> /// <param name="xmlAttributeText">Input string</param> /// <returns>New string with all the replacements (e.g. "&amp;" becomes "&amp;amp;", etc.)</returns> /// <owner>RGoel</owner> internal static string ReplaceSpecialCharactersInXmlAttributeString ( string xmlAttributeText ) { // Replace the special characters with their XML-friendly escaped equivalents. The // "<" and ">" signs are easy, because if they exist at all within the value of an // XML attribute, we know that they need to be replaced with "&lt;" and "&gt;" // respectively. xmlAttributeText = xmlAttributeText.Replace("<", "&lt;"); xmlAttributeText = xmlAttributeText.Replace(">", "&gt;"); xmlAttributeText = ReplaceNonEscapingAmpersands(xmlAttributeText); return xmlAttributeText; } // Note -- the comment below is rendered a little confusing by escaping for XML doc compiler. Read "&amp;" as "&" // and "&amp;amp;" as "&amp;". Or just look at the intellisense tooltip. /// <summary> /// This method scans the strings for "&amp;" characters, and based on what follows /// the "&amp;" character, it determines whether the "&amp;" character needs to be replaced /// with "&amp;amp;". The old XML parser used in the VS.NET 2002/2003 project system /// was quite inconsistent in its treatment of escaped characters in XML, so here /// we're having to make up for those bugs. The new XML parser (System.Xml) /// is much more strict in enforcing proper XML syntax, and therefore doesn't /// tolerate "&amp;" characters in the XML attribute value, unless the "&amp;" is being /// used to escape some special character. /// </summary> /// <param name="xmlAttributeText">Input string</param> /// <returns>New string with all the replacements (e.g. "&amp;" becomes "&amp;amp;", etc.)</returns> /// <owner>RGoel</owner> private static string ReplaceNonEscapingAmpersands ( string xmlAttributeText ) { // Ampersands are a little trickier, because some instances of "&" we need to leave // untouched, and some we need to replace with "&amp;". For example, // aaa&bbb should be replaced with aaa&amp;bbb // But: // aaa&lt;bbb should not be touched. // Loop through each instance of "&" int indexOfAmpersand = xmlAttributeText.IndexOf('&'); while (indexOfAmpersand != -1) { // If an "&" was found, search for the next ";" following the "&". int indexOfNextSemicolon = xmlAttributeText.IndexOf(';', indexOfAmpersand); if (indexOfNextSemicolon == -1) { // No semicolon means that the ampersand was really intended to be a literal // ampersand and therefore we need to replace it with "&amp;". For example, // // aaa&bbb should get replaced with aaa&amp;bbb xmlAttributeText = ReplaceAmpersandWithLiteral(xmlAttributeText, indexOfAmpersand); } else { // We found the semicolon. Capture the characters between (but not // including) the "&" and ";". string entityName = xmlAttributeText.Substring(indexOfAmpersand + 1, indexOfNextSemicolon - indexOfAmpersand - 1); // Perf note: Here we are walking through the entire list of entities, and // doing a string comparison for each. This is expensive, but this code // should only get executed in fairly rare circumstances. It's not very // common for people to have these embedded into their project files. bool foundEntity = false; for (int i = 0 ; i < entities.Length ; i++) { // Case-sensitive comparison to see if the entity name matches any of // the well-known ones that were emitted by the XML writer in the VS.NET // 2002/2003 project system. if (String.Equals(entityName, entities[i], StringComparison.Ordinal)) { foundEntity = true; break; } } // If it didn't match a well-known entity name, then the next thing to // check is if it represents an ASCII code. For example, in an XML // attribute, if I wanted to represent the "+" sign, I could do this: // // &#43; // if (!foundEntity && (entityName.Length > 0) && (entityName[0] == '#')) { // At this point, we know entityName is something like "#1234" or "#x1234abcd" bool isNumber = false; // A lower-case "x" in the second position indicates a hexadecimal value. if ((entityName.Length > 2) && (entityName[1] == 'x')) { isNumber = true; // It's a hexadecimal number. Make sure every character of the entity // is in fact a valid hexadecimal character. for (int i = 2; i < entityName.Length; i++) { if (!Uri.IsHexDigit(entityName[i])) { isNumber = false; break; } } } else if (entityName.Length > 1) { // Otherwise it's a decimal value. isNumber = true; // ake sure every character of the entity is in fact a valid decimal number. for (int i = 1; i < entityName.Length; i++) { if (!Char.IsNumber(entityName[i])) { isNumber = false; break; } } } if (isNumber) { foundEntity = true; } } // If the ampersand did not precede an actual well-known entity, then we DO want to // replace the "&" with a "&amp;". Otherwise we don't. if (!foundEntity) { xmlAttributeText = ReplaceAmpersandWithLiteral(xmlAttributeText, indexOfAmpersand); } } // We're done process that particular "&". Now find the next one. indexOfAmpersand = xmlAttributeText.IndexOf('&', indexOfAmpersand + 1); } return xmlAttributeText; } // Note -- the comment below is rendered a little confusing by escaping for XML doc compiler. Read "&amp;" as "&" // and "&amp;amp;" as "&amp;". Or just look at the intellisense tooltip. /// <summary> /// Replaces a single instance of an "&amp;" character in a string with "&amp;amp;" and returns the new string. /// </summary> /// <param name="originalString">Original string where we should find an "&amp;" character.</param> /// <param name="indexOfAmpersand">The index of the "&amp;" which we want to replace.</param> /// <returns>The new string with the "&amp;" replaced with "&amp;amp;".</returns> /// <owner>RGoel</owner> internal static string ReplaceAmpersandWithLiteral ( string originalString, int indexOfAmpersand ) { error.VerifyThrow(originalString[indexOfAmpersand] == '&', "Caller passed in a string that doesn't have an '&' character in the specified location."); StringBuilder replacedString = new StringBuilder(); replacedString.Append(originalString, 0, indexOfAmpersand); replacedString.Append("&amp;"); replacedString.Append(originalString, indexOfAmpersand + 1, originalString.Length - indexOfAmpersand + 1); return replacedString.ToString(); } // This is the complete list of well-known entity names that were written out // by the XML writer in the VS.NET 2002/2003 project system. This list was // taken directly from the source code. private static readonly string[] entities = { "quot", // "amp", // & - ampersand "apos", // ' - apostrophe //// not part of HTML! "lt", // < less than "gt", // > greater than "nbsp", // Non breaking space "iexcl", // "cent", // cent "pound", // pound "curren", // currency "yen", // yen "brvbar", // vertical bar "sect", // section "uml", // "copy", // Copyright "ordf", // "laquo", // "not", // "shy", // "reg", // Registered TradeMark "macr", // "deg", // "plusmn", // "sup2", // "sup3", // "acute", // "micro", // "para", // "middot", // "cedil", // "sup1", // "ordm", // "raquo", // "frac14", // 1/4 "frac12", // 1/2 "frac34", // 3/4 "iquest", // Inverse question mark "Agrave", // Capital A grave accent "Aacute", // Capital A acute accent "Acirc", // Capital A circumflex accent "Atilde", // Capital A tilde "Auml", // Capital A dieresis or umlaut mark "Aring", // Capital A ring "AElig", // Capital AE dipthong (ligature) "Ccedil", // Capital C cedilla "Egrave", // Capital E grave accent "Eacute", // Capital E acute accent "Ecirc", // Capital E circumflex accent "Euml", // Capital E dieresis or umlaut mark "Igrave", // Capital I grave accent "Iacute", // Capital I acute accent "Icirc", // Capital I circumflex accent "Iuml", // Capital I dieresis or umlaut mark "ETH", // Capital Eth Icelandic "Ntilde", // Capital N tilde "Ograve", // Capital O grave accent "Oacute", // Capital O acute accent "Ocirc", // Capital O circumflex accent "Otilde", // Capital O tilde "Ouml", // Capital O dieresis or umlaut mark "times", // multiply or times "Oslash", // Capital O slash "Ugrave", // Capital U grave accent "Uacute", // Capital U acute accent "Ucirc", // Capital U circumflex accent "Uuml", // Capital U dieresis or umlaut mark; "Yacute", // Capital Y acute accent "THORN", // Capital THORN Icelandic "szlig", // Small sharp s German (sz ligature) "agrave", // Small a grave accent "aacute", // Small a acute accent "acirc", // Small a circumflex accent "atilde", // Small a tilde "auml", // Small a dieresis or umlaut mark "aring", // Small a ring "aelig", // Small ae dipthong (ligature) "ccedil", // Small c cedilla "egrave", // Small e grave accent "eacute", // Small e acute accent "ecirc", // Small e circumflex accent "euml", // Small e dieresis or umlaut mark "igrave", // Small i grave accent "iacute", // Small i acute accent "icirc", // Small i circumflex accent "iuml", // Small i dieresis or umlaut mark "eth", // Small eth Icelandic "ntilde", // Small n tilde "ograve", // Small o grave accent "oacute", // Small o acute accent "ocirc", // Small o circumflex accent "otilde", // Small o tilde "ouml", // Small o dieresis or umlaut mark "divide", // divide "oslash", // Small o slash "ugrave", // Small u grave accent "uacute", // Small u acute accent "ucirc", // Small u circumflex accent "uuml", // Small u dieresis or umlaut mark "yacute", // Small y acute accent "thorn", // Small thorn Icelandic "yuml", // Small y dieresis or umlaut mark "OElig", // latin capital ligature oe, U0152 ISOlat2 "oelig", // latin small ligature oe, U0153 ISOlat2 "Scaron", // latin capital letter s with caron, U0160 ISOlat2 "scaron", // latin small letter s with caron, U0161 ISOlat2 "Yuml", // latin capital letter y with diaeresis, U0178 ISOlat2 "fnof", // latin small f with hook, =function, =florin, U0192 ISOtech "circ", // modifier letter circumflex accent, U02C6 ISOpub "tilde", // small tilde, U02DC ISOdia "Alpha", // greek capital letter alpha "Beta", // greek capital letter beta "Gamma", // greek capital letter gamma "Delta", // greek capital letter delta "Epsilon", // greek capital letter epsilon "Zeta", // greek capital letter zeta "Eta", // greek capital letter eta "Theta", // greek capital letter theta "Iota", // greek capital letter iota "Kappa", // greek capital letter kappa "Lambda", // greek capital letter lambda "Mu", // greek capital letter mu "Nu", // greek capital letter nu "Xi", // greek capital letter xi "Omicron", // greek capital letter omicron "Pi", // greek capital letter pi "Rho", // greek capital letter rho "Sigma", // greek capital letter sigma "Tau", // greek capital letter tau "Upsilon", // greek capital letter upsilon "Phi", // greek capital letter phi "Chi", // greek capital letter chi "Psi", // greek capital letter psi "Omega", // greek capital letter omega "alpha", // greek small letter alpha "beta", // greek small letter beta "gamma", // greek small letter gamma "delta", // greek small letter delta "epsilon", // greek small letter epsilon "zeta", // greek small letter zeta "eta", // greek small letter eta "theta", // greek small letter theta "iota", // greek small letter iota "kappa", // greek small letter kappa "lambda", // greek small letter lambda "mu", // greek small letter mu "nu", // greek small letter nu "xi", // greek small letter xi "omicron", // greek small letter omicron "pi", // greek small letter pi "rho", // greek small letter rho "sigmaf", // greek small final sigma "sigma", // greek small letter sigma "tau", // greek small letter tau "upsilon", // greek small letter upsilon "phi", // greek small letter phi "chi", // greek small letter chi "psi", // greek small letter psi "omega", // greek small letter omega "thetasym", // greek small letter theta symbol, U03D1 NEW "upsih", // greek upsilon with hook symbol "piv", // greek pi symbol "ensp", // en space, U2002 ISOpub "emsp", // em space, U2003 ISOpub "thinsp", // thin space, U2009 ISOpub "zwnj", // zero width non-joiner, U200C NEW RFC 2070 "zwj", // zero width joiner, U200D NEW RFC 2070 "lrm", // left-to-right mark, U200E NEW RFC 2070 "rlm", // right-to-left mark, U200F NEW RFC 2070 "ndash", // en dash, U2013 ISOpub "mdash", // em dash, U2014 ISOpub "lsquo", // left single quotation mark, U2018 ISOnum "rsquo", // right single quotation mark, U2019 ISOnum "sbquo", // single low-9 quotation mark, U201A NEW "ldquo", // left double quotation mark, U201C ISOnum "rdquo", // right double quotation mark, U201D ISOnum "bdquo", // double low-9 quotation mark, U201E NEW "dagger", // dagger, U2020 ISOpub "Dagger", // double dagger, U2021 ISOpub "bull", // bullet, =black small circle, U2022 ISOpub "hellip", // horizontal ellipsis, =three dot leader, U2026 ISOpub "permil", // per mille sign, U2030 ISOtech "prime", // prime, =minutes, =feet, U2032 ISOtech "Prime", // double prime, =seconds, =inches, U2033 ISOtech "lsaquo", // single left-pointing angle quotation mark, U2039 ISO proposed "rsaquo", // single right-pointing angle quotation mark, U203A ISO proposed "oline", // overline, spacing overscore "frasl", // fraction slash "image", // blackletter capital I, =imaginary part, U2111 ISOamso "weierp", // script capital P, =power set, =Weierstrass p, U2118 ISOamso "real", // blackletter capital R, =real part symbol, U211C ISOamso "trade", // trade mark sign, U2122 ISOnum "alefsym", // alef symbol, =first transfinite cardinal, U2135 NEW "larr", // leftwards arrow, U2190 ISOnum "uarr", // upwards arrow, U2191 ISOnum "rarr", // rightwards arrow, U2192 ISOnum "darr", // downwards arrow, U2193 ISOnum "harr", // left right arrow, U2194 ISOamsa "crarr", // downwards arrow with corner leftwards, =carriage return, U21B5 NEW "lArr", // leftwards double arrow, U21D0 ISOtech "uArr", // upwards double arrow, U21D1 ISOamsa "rArr", // rightwards double arrow, U21D2 ISOtech "dArr", // downwards double arrow, U21D3 ISOamsa "hArr", // left right double arrow, U21D4 ISOamsa "forall", // for all, U2200 ISOtech "part", // partial differential, U2202 ISOtech "exist", // there exists, U2203 ISOtech "empty", // empty set, =null set, =diameter, U2205 ISOamso "nabla", // nabla, =backward difference, U2207 ISOtech "isin", // element of, U2208 ISOtech "notin", // not an element of, U2209 ISOtech "ni", // contains as member, U220B ISOtech "prod", // n-ary product, =product sign, U220F ISOamsb "sum", // n-ary sumation, U2211 ISOamsb "minus", // minus sign, U2212 ISOtech "lowast", // asterisk operator, U2217 ISOtech "radic", // square root, =radical sign, U221A ISOtech "prop", // proportional to, U221D ISOtech "infin", // infinity, U221E ISOtech "ang", // angle, U2220 ISOamso "and", // logical and, =wedge, U2227 ISOtech "or", // logical or, =vee, U2228 ISOtech "cap", // intersection, =cap, U2229 ISOtech "cup", // union, =cup, U222A ISOtech "int", // integral, U222B ISOtech "there4", // therefore, U2234 ISOtech "sim", // tilde operator, =varies with, =similar to, U223C ISOtech "cong", // approximately equal to, U2245 ISOtech "asymp", // almost equal to, =asymptotic to, U2248 ISOamsr "ne", // not equal to, U2260 ISOtech "equiv", // identical to, U2261 ISOtech "le", // less-than or equal to, U2264 ISOtech "ge", // greater-than or equal to, U2265 ISOtech "sub", // subset of, U2282 ISOtech "sup", // superset of, U2283 ISOtech "nsub", // not a subset of, U2284 ISOamsn "sube", // subset of or equal to, U2286 ISOtech "supe", // superset of or equal to, U2287 ISOtech "oplus", // circled plus, =direct sum, U2295 ISOamsb "otimes", // circled times, =vector product, U2297 ISOamsb "perp", // up tack, =orthogonal to, =perpendicular, U22A5 ISOtech "sdot", // dot operator, U22C5 ISOamsb "lceil", // left ceiling, =apl upstile, U2308, ISOamsc "rceil", // right ceiling, U2309, ISOamsc "lfloor", // left floor, =apl downstile, U230A, ISOamsc "rfloor", // right floor, U230B, ISOamsc "lang", // left-pointing angle bracket, =bra, U2329 ISOtech "rang", // right-pointing angle bracket, =ket, U232A ISOtech "loz", // lozenge, U25CA ISOpub "spades", // black spade suit, U2660 ISOpub "clubs", // black club suit, =shamrock, U2663 ISOpub "hearts", // black heart suit, =valentine, U2665 ISOpub "diams" // black diamond suit, U2666 ISOpub }; } }
// 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; namespace System.Xml.Xsl.Qil { /// <summary> /// Factory methods for constructing QilExpression nodes. /// </summary> /// <remarks> /// See <see cref="http://dynamo/qil/qil.xml">the QIL functional specification</see> for documentation. /// </remarks> internal sealed class QilFactory { private QilTypeChecker _typeCheck; public QilFactory() { _typeCheck = new QilTypeChecker(); } public QilTypeChecker TypeChecker { get { return _typeCheck; } } //----------------------------------------------- // Convenience methods //----------------------------------------------- public QilExpression QilExpression(QilNode root, QilFactory factory) { QilExpression n = new QilExpression(QilNodeType.QilExpression, root, factory); n.XmlType = _typeCheck.CheckQilExpression(n); TraceNode(n); return n; } public QilList FunctionList(IList<QilNode> values) { QilList seq = FunctionList(); seq.Add(values); return seq; } public QilList GlobalVariableList(IList<QilNode> values) { QilList seq = GlobalVariableList(); seq.Add(values); return seq; } public QilList GlobalParameterList(IList<QilNode> values) { QilList seq = GlobalParameterList(); seq.Add(values); return seq; } public QilList ActualParameterList(IList<QilNode> values) { QilList seq = ActualParameterList(); seq.Add(values); return seq; } public QilList FormalParameterList(IList<QilNode> values) { QilList seq = FormalParameterList(); seq.Add(values); return seq; } public QilList SortKeyList(IList<QilNode> values) { QilList seq = SortKeyList(); seq.Add(values); return seq; } public QilList BranchList(IList<QilNode> values) { QilList seq = BranchList(); seq.Add(values); return seq; } public QilList Sequence(IList<QilNode> values) { QilList seq = Sequence(); seq.Add(values); return seq; } public QilParameter Parameter(XmlQueryType xmlType) { return Parameter(null, null, xmlType); } public QilStrConcat StrConcat(QilNode values) { return StrConcat(LiteralString(""), values); } public QilName LiteralQName(string local) { return LiteralQName(local, string.Empty, string.Empty); } public QilTargetType TypeAssert(QilNode expr, XmlQueryType xmlType) { return TypeAssert(expr, (QilNode)LiteralType(xmlType)); } public QilTargetType IsType(QilNode expr, XmlQueryType xmlType) { return IsType(expr, (QilNode)LiteralType(xmlType)); } public QilTargetType XsltConvert(QilNode expr, XmlQueryType xmlType) { return XsltConvert(expr, (QilNode)LiteralType(xmlType)); } public QilFunction Function(QilNode arguments, QilNode sideEffects, XmlQueryType xmlType) { return Function(arguments, Unknown(xmlType), sideEffects, xmlType); } #region AUTOGENERATED #region meta //----------------------------------------------- // meta //----------------------------------------------- public QilExpression QilExpression(QilNode root) { QilExpression n = new QilExpression(QilNodeType.QilExpression, root); n.XmlType = _typeCheck.CheckQilExpression(n); TraceNode(n); return n; } public QilList FunctionList() { QilList n = new QilList(QilNodeType.FunctionList); n.XmlType = _typeCheck.CheckFunctionList(n); TraceNode(n); return n; } public QilList GlobalVariableList() { QilList n = new QilList(QilNodeType.GlobalVariableList); n.XmlType = _typeCheck.CheckGlobalVariableList(n); TraceNode(n); return n; } public QilList GlobalParameterList() { QilList n = new QilList(QilNodeType.GlobalParameterList); n.XmlType = _typeCheck.CheckGlobalParameterList(n); TraceNode(n); return n; } public QilList ActualParameterList() { QilList n = new QilList(QilNodeType.ActualParameterList); n.XmlType = _typeCheck.CheckActualParameterList(n); TraceNode(n); return n; } public QilList FormalParameterList() { QilList n = new QilList(QilNodeType.FormalParameterList); n.XmlType = _typeCheck.CheckFormalParameterList(n); TraceNode(n); return n; } public QilList SortKeyList() { QilList n = new QilList(QilNodeType.SortKeyList); n.XmlType = _typeCheck.CheckSortKeyList(n); TraceNode(n); return n; } public QilList BranchList() { QilList n = new QilList(QilNodeType.BranchList); n.XmlType = _typeCheck.CheckBranchList(n); TraceNode(n); return n; } public QilUnary OptimizeBarrier(QilNode child) { QilUnary n = new QilUnary(QilNodeType.OptimizeBarrier, child); n.XmlType = _typeCheck.CheckOptimizeBarrier(n); TraceNode(n); return n; } public QilNode Unknown(XmlQueryType xmlType) { QilNode n = new QilNode(QilNodeType.Unknown, xmlType); n.XmlType = _typeCheck.CheckUnknown(n); TraceNode(n); return n; } #endregion // meta #region specials //----------------------------------------------- // specials //----------------------------------------------- public QilDataSource DataSource(QilNode name, QilNode baseUri) { QilDataSource n = new QilDataSource(QilNodeType.DataSource, name, baseUri); n.XmlType = _typeCheck.CheckDataSource(n); TraceNode(n); return n; } public QilUnary Nop(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Nop, child); n.XmlType = _typeCheck.CheckNop(n); TraceNode(n); return n; } public QilUnary Error(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Error, child); n.XmlType = _typeCheck.CheckError(n); TraceNode(n); return n; } public QilUnary Warning(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Warning, child); n.XmlType = _typeCheck.CheckWarning(n); TraceNode(n); return n; } #endregion // specials #region variables //----------------------------------------------- // variables //----------------------------------------------- public QilIterator For(QilNode binding) { QilIterator n = new QilIterator(QilNodeType.For, binding); n.XmlType = _typeCheck.CheckFor(n); TraceNode(n); return n; } public QilIterator Let(QilNode binding) { QilIterator n = new QilIterator(QilNodeType.Let, binding); n.XmlType = _typeCheck.CheckLet(n); TraceNode(n); return n; } public QilParameter Parameter(QilNode defaultValue, QilNode name, XmlQueryType xmlType) { QilParameter n = new QilParameter(QilNodeType.Parameter, defaultValue, name, xmlType); n.XmlType = _typeCheck.CheckParameter(n); TraceNode(n); return n; } public QilUnary PositionOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.PositionOf, child); n.XmlType = _typeCheck.CheckPositionOf(n); TraceNode(n); return n; } #endregion // variables #region literals //----------------------------------------------- // literals //----------------------------------------------- public QilNode True() { QilNode n = new QilNode(QilNodeType.True); n.XmlType = _typeCheck.CheckTrue(n); TraceNode(n); return n; } public QilNode False() { QilNode n = new QilNode(QilNodeType.False); n.XmlType = _typeCheck.CheckFalse(n); TraceNode(n); return n; } public QilLiteral LiteralString(string value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralString, value); n.XmlType = _typeCheck.CheckLiteralString(n); TraceNode(n); return n; } public QilLiteral LiteralInt32(int value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralInt32, value); n.XmlType = _typeCheck.CheckLiteralInt32(n); TraceNode(n); return n; } public QilLiteral LiteralInt64(long value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralInt64, value); n.XmlType = _typeCheck.CheckLiteralInt64(n); TraceNode(n); return n; } public QilLiteral LiteralDouble(double value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralDouble, value); n.XmlType = _typeCheck.CheckLiteralDouble(n); TraceNode(n); return n; } public QilLiteral LiteralDecimal(decimal value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralDecimal, value); n.XmlType = _typeCheck.CheckLiteralDecimal(n); TraceNode(n); return n; } public QilName LiteralQName(string localName, string namespaceUri, string prefix) { QilName n = new QilName(QilNodeType.LiteralQName, localName, namespaceUri, prefix); n.XmlType = _typeCheck.CheckLiteralQName(n); TraceNode(n); return n; } public QilLiteral LiteralType(XmlQueryType value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralType, value); n.XmlType = _typeCheck.CheckLiteralType(n); TraceNode(n); return n; } public QilLiteral LiteralObject(object value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralObject, value); n.XmlType = _typeCheck.CheckLiteralObject(n); TraceNode(n); return n; } #endregion // literals #region boolean operators //----------------------------------------------- // boolean operators //----------------------------------------------- public QilBinary And(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.And, left, right); n.XmlType = _typeCheck.CheckAnd(n); TraceNode(n); return n; } public QilBinary Or(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Or, left, right); n.XmlType = _typeCheck.CheckOr(n); TraceNode(n); return n; } public QilUnary Not(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Not, child); n.XmlType = _typeCheck.CheckNot(n); TraceNode(n); return n; } #endregion // boolean operators #region choice //----------------------------------------------- // choice //----------------------------------------------- public QilTernary Conditional(QilNode left, QilNode center, QilNode right) { QilTernary n = new QilTernary(QilNodeType.Conditional, left, center, right); n.XmlType = _typeCheck.CheckConditional(n); TraceNode(n); return n; } public QilChoice Choice(QilNode expression, QilNode branches) { QilChoice n = new QilChoice(QilNodeType.Choice, expression, branches); n.XmlType = _typeCheck.CheckChoice(n); TraceNode(n); return n; } #endregion // choice #region collection operators //----------------------------------------------- // collection operators //----------------------------------------------- public QilUnary Length(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Length, child); n.XmlType = _typeCheck.CheckLength(n); TraceNode(n); return n; } public QilList Sequence() { QilList n = new QilList(QilNodeType.Sequence); n.XmlType = _typeCheck.CheckSequence(n); TraceNode(n); return n; } public QilBinary Union(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Union, left, right); n.XmlType = _typeCheck.CheckUnion(n); TraceNode(n); return n; } public QilBinary Intersection(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Intersection, left, right); n.XmlType = _typeCheck.CheckIntersection(n); TraceNode(n); return n; } public QilBinary Difference(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Difference, left, right); n.XmlType = _typeCheck.CheckDifference(n); TraceNode(n); return n; } public QilUnary Average(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Average, child); n.XmlType = _typeCheck.CheckAverage(n); TraceNode(n); return n; } public QilUnary Sum(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Sum, child); n.XmlType = _typeCheck.CheckSum(n); TraceNode(n); return n; } public QilUnary Minimum(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Minimum, child); n.XmlType = _typeCheck.CheckMinimum(n); TraceNode(n); return n; } public QilUnary Maximum(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Maximum, child); n.XmlType = _typeCheck.CheckMaximum(n); TraceNode(n); return n; } #endregion // collection operators #region arithmetic operators //----------------------------------------------- // arithmetic operators //----------------------------------------------- public QilUnary Negate(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Negate, child); n.XmlType = _typeCheck.CheckNegate(n); TraceNode(n); return n; } public QilBinary Add(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Add, left, right); n.XmlType = _typeCheck.CheckAdd(n); TraceNode(n); return n; } public QilBinary Subtract(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Subtract, left, right); n.XmlType = _typeCheck.CheckSubtract(n); TraceNode(n); return n; } public QilBinary Multiply(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Multiply, left, right); n.XmlType = _typeCheck.CheckMultiply(n); TraceNode(n); return n; } public QilBinary Divide(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Divide, left, right); n.XmlType = _typeCheck.CheckDivide(n); TraceNode(n); return n; } public QilBinary Modulo(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Modulo, left, right); n.XmlType = _typeCheck.CheckModulo(n); TraceNode(n); return n; } #endregion // arithmetic operators #region string operators //----------------------------------------------- // string operators //----------------------------------------------- public QilUnary StrLength(QilNode child) { QilUnary n = new QilUnary(QilNodeType.StrLength, child); n.XmlType = _typeCheck.CheckStrLength(n); TraceNode(n); return n; } public QilStrConcat StrConcat(QilNode delimiter, QilNode values) { QilStrConcat n = new QilStrConcat(QilNodeType.StrConcat, delimiter, values); n.XmlType = _typeCheck.CheckStrConcat(n); TraceNode(n); return n; } public QilBinary StrParseQName(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.StrParseQName, left, right); n.XmlType = _typeCheck.CheckStrParseQName(n); TraceNode(n); return n; } #endregion // string operators #region value comparison operators //----------------------------------------------- // value comparison operators //----------------------------------------------- public QilBinary Ne(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Ne, left, right); n.XmlType = _typeCheck.CheckNe(n); TraceNode(n); return n; } public QilBinary Eq(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Eq, left, right); n.XmlType = _typeCheck.CheckEq(n); TraceNode(n); return n; } public QilBinary Gt(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Gt, left, right); n.XmlType = _typeCheck.CheckGt(n); TraceNode(n); return n; } public QilBinary Ge(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Ge, left, right); n.XmlType = _typeCheck.CheckGe(n); TraceNode(n); return n; } public QilBinary Lt(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Lt, left, right); n.XmlType = _typeCheck.CheckLt(n); TraceNode(n); return n; } public QilBinary Le(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Le, left, right); n.XmlType = _typeCheck.CheckLe(n); TraceNode(n); return n; } #endregion // value comparison operators #region node comparison operators //----------------------------------------------- // node comparison operators //----------------------------------------------- public QilBinary Is(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Is, left, right); n.XmlType = _typeCheck.CheckIs(n); TraceNode(n); return n; } public QilBinary After(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.After, left, right); n.XmlType = _typeCheck.CheckAfter(n); TraceNode(n); return n; } public QilBinary Before(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Before, left, right); n.XmlType = _typeCheck.CheckBefore(n); TraceNode(n); return n; } #endregion // node comparison operators #region loops //----------------------------------------------- // loops //----------------------------------------------- public QilLoop Loop(QilNode variable, QilNode body) { QilLoop n = new QilLoop(QilNodeType.Loop, variable, body); n.XmlType = _typeCheck.CheckLoop(n); TraceNode(n); return n; } public QilLoop Filter(QilNode variable, QilNode body) { QilLoop n = new QilLoop(QilNodeType.Filter, variable, body); n.XmlType = _typeCheck.CheckFilter(n); TraceNode(n); return n; } #endregion // loops #region sorting //----------------------------------------------- // sorting //----------------------------------------------- public QilLoop Sort(QilNode variable, QilNode body) { QilLoop n = new QilLoop(QilNodeType.Sort, variable, body); n.XmlType = _typeCheck.CheckSort(n); TraceNode(n); return n; } public QilSortKey SortKey(QilNode key, QilNode collation) { QilSortKey n = new QilSortKey(QilNodeType.SortKey, key, collation); n.XmlType = _typeCheck.CheckSortKey(n); TraceNode(n); return n; } public QilUnary DocOrderDistinct(QilNode child) { QilUnary n = new QilUnary(QilNodeType.DocOrderDistinct, child); n.XmlType = _typeCheck.CheckDocOrderDistinct(n); TraceNode(n); return n; } #endregion // sorting #region function definition and invocation //----------------------------------------------- // function definition and invocation //----------------------------------------------- public QilFunction Function(QilNode arguments, QilNode definition, QilNode sideEffects, XmlQueryType xmlType) { QilFunction n = new QilFunction(QilNodeType.Function, arguments, definition, sideEffects, xmlType); n.XmlType = _typeCheck.CheckFunction(n); TraceNode(n); return n; } public QilInvoke Invoke(QilNode function, QilNode arguments) { QilInvoke n = new QilInvoke(QilNodeType.Invoke, function, arguments); n.XmlType = _typeCheck.CheckInvoke(n); TraceNode(n); return n; } #endregion // function definition and invocation #region XML navigation //----------------------------------------------- // XML navigation //----------------------------------------------- public QilUnary Content(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Content, child); n.XmlType = _typeCheck.CheckContent(n); TraceNode(n); return n; } public QilBinary Attribute(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Attribute, left, right); n.XmlType = _typeCheck.CheckAttribute(n); TraceNode(n); return n; } public QilUnary Parent(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Parent, child); n.XmlType = _typeCheck.CheckParent(n); TraceNode(n); return n; } public QilUnary Root(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Root, child); n.XmlType = _typeCheck.CheckRoot(n); TraceNode(n); return n; } public QilNode XmlContext() { QilNode n = new QilNode(QilNodeType.XmlContext); n.XmlType = _typeCheck.CheckXmlContext(n); TraceNode(n); return n; } public QilUnary Descendant(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Descendant, child); n.XmlType = _typeCheck.CheckDescendant(n); TraceNode(n); return n; } public QilUnary DescendantOrSelf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.DescendantOrSelf, child); n.XmlType = _typeCheck.CheckDescendantOrSelf(n); TraceNode(n); return n; } public QilUnary Ancestor(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Ancestor, child); n.XmlType = _typeCheck.CheckAncestor(n); TraceNode(n); return n; } public QilUnary AncestorOrSelf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.AncestorOrSelf, child); n.XmlType = _typeCheck.CheckAncestorOrSelf(n); TraceNode(n); return n; } public QilUnary Preceding(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Preceding, child); n.XmlType = _typeCheck.CheckPreceding(n); TraceNode(n); return n; } public QilUnary FollowingSibling(QilNode child) { QilUnary n = new QilUnary(QilNodeType.FollowingSibling, child); n.XmlType = _typeCheck.CheckFollowingSibling(n); TraceNode(n); return n; } public QilUnary PrecedingSibling(QilNode child) { QilUnary n = new QilUnary(QilNodeType.PrecedingSibling, child); n.XmlType = _typeCheck.CheckPrecedingSibling(n); TraceNode(n); return n; } public QilBinary NodeRange(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.NodeRange, left, right); n.XmlType = _typeCheck.CheckNodeRange(n); TraceNode(n); return n; } public QilBinary Deref(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Deref, left, right); n.XmlType = _typeCheck.CheckDeref(n); TraceNode(n); return n; } #endregion // XML navigation #region XML construction //----------------------------------------------- // XML construction //----------------------------------------------- public QilBinary ElementCtor(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.ElementCtor, left, right); n.XmlType = _typeCheck.CheckElementCtor(n); TraceNode(n); return n; } public QilBinary AttributeCtor(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.AttributeCtor, left, right); n.XmlType = _typeCheck.CheckAttributeCtor(n); TraceNode(n); return n; } public QilUnary CommentCtor(QilNode child) { QilUnary n = new QilUnary(QilNodeType.CommentCtor, child); n.XmlType = _typeCheck.CheckCommentCtor(n); TraceNode(n); return n; } public QilBinary PICtor(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.PICtor, left, right); n.XmlType = _typeCheck.CheckPICtor(n); TraceNode(n); return n; } public QilUnary TextCtor(QilNode child) { QilUnary n = new QilUnary(QilNodeType.TextCtor, child); n.XmlType = _typeCheck.CheckTextCtor(n); TraceNode(n); return n; } public QilUnary RawTextCtor(QilNode child) { QilUnary n = new QilUnary(QilNodeType.RawTextCtor, child); n.XmlType = _typeCheck.CheckRawTextCtor(n); TraceNode(n); return n; } public QilUnary DocumentCtor(QilNode child) { QilUnary n = new QilUnary(QilNodeType.DocumentCtor, child); n.XmlType = _typeCheck.CheckDocumentCtor(n); TraceNode(n); return n; } public QilBinary NamespaceDecl(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.NamespaceDecl, left, right); n.XmlType = _typeCheck.CheckNamespaceDecl(n); TraceNode(n); return n; } public QilBinary RtfCtor(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.RtfCtor, left, right); n.XmlType = _typeCheck.CheckRtfCtor(n); TraceNode(n); return n; } #endregion // XML construction #region Node properties //----------------------------------------------- // Node properties //----------------------------------------------- public QilUnary NameOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.NameOf, child); n.XmlType = _typeCheck.CheckNameOf(n); TraceNode(n); return n; } public QilUnary LocalNameOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.LocalNameOf, child); n.XmlType = _typeCheck.CheckLocalNameOf(n); TraceNode(n); return n; } public QilUnary NamespaceUriOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.NamespaceUriOf, child); n.XmlType = _typeCheck.CheckNamespaceUriOf(n); TraceNode(n); return n; } public QilUnary PrefixOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.PrefixOf, child); n.XmlType = _typeCheck.CheckPrefixOf(n); TraceNode(n); return n; } #endregion // Node properties #region Type operators //----------------------------------------------- // Type operators //----------------------------------------------- public QilTargetType TypeAssert(QilNode source, QilNode targetType) { QilTargetType n = new QilTargetType(QilNodeType.TypeAssert, source, targetType); n.XmlType = _typeCheck.CheckTypeAssert(n); TraceNode(n); return n; } public QilTargetType IsType(QilNode source, QilNode targetType) { QilTargetType n = new QilTargetType(QilNodeType.IsType, source, targetType); n.XmlType = _typeCheck.CheckIsType(n); TraceNode(n); return n; } public QilUnary IsEmpty(QilNode child) { QilUnary n = new QilUnary(QilNodeType.IsEmpty, child); n.XmlType = _typeCheck.CheckIsEmpty(n); TraceNode(n); return n; } #endregion // Type operators #region XPath operators //----------------------------------------------- // XPath operators //----------------------------------------------- public QilUnary XPathNodeValue(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XPathNodeValue, child); n.XmlType = _typeCheck.CheckXPathNodeValue(n); TraceNode(n); return n; } public QilUnary XPathFollowing(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XPathFollowing, child); n.XmlType = _typeCheck.CheckXPathFollowing(n); TraceNode(n); return n; } public QilUnary XPathPreceding(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XPathPreceding, child); n.XmlType = _typeCheck.CheckXPathPreceding(n); TraceNode(n); return n; } public QilUnary XPathNamespace(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XPathNamespace, child); n.XmlType = _typeCheck.CheckXPathNamespace(n); TraceNode(n); return n; } #endregion // XPath operators #region XSLT //----------------------------------------------- // XSLT //----------------------------------------------- public QilUnary XsltGenerateId(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XsltGenerateId, child); n.XmlType = _typeCheck.CheckXsltGenerateId(n); TraceNode(n); return n; } public QilInvokeLateBound XsltInvokeLateBound(QilNode name, QilNode arguments) { QilInvokeLateBound n = new QilInvokeLateBound(QilNodeType.XsltInvokeLateBound, name, arguments); n.XmlType = _typeCheck.CheckXsltInvokeLateBound(n); TraceNode(n); return n; } public QilInvokeEarlyBound XsltInvokeEarlyBound(QilNode name, QilNode clrMethod, QilNode arguments, XmlQueryType xmlType) { QilInvokeEarlyBound n = new QilInvokeEarlyBound(QilNodeType.XsltInvokeEarlyBound, name, clrMethod, arguments, xmlType); n.XmlType = _typeCheck.CheckXsltInvokeEarlyBound(n); TraceNode(n); return n; } public QilBinary XsltCopy(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.XsltCopy, left, right); n.XmlType = _typeCheck.CheckXsltCopy(n); TraceNode(n); return n; } public QilUnary XsltCopyOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XsltCopyOf, child); n.XmlType = _typeCheck.CheckXsltCopyOf(n); TraceNode(n); return n; } public QilTargetType XsltConvert(QilNode source, QilNode targetType) { QilTargetType n = new QilTargetType(QilNodeType.XsltConvert, source, targetType); n.XmlType = _typeCheck.CheckXsltConvert(n); TraceNode(n); return n; } #endregion // XSLT #endregion #region Diagnostic Support #if QIL_TRACE_NODE_CREATION internal sealed class Diagnostics { private int nodecnt = 0; private ArrayList nodelist = new ArrayList(); public ArrayList NodeTable { get { return nodelist; } } public void AddNode(QilNode n) { nodelist.Add(n); n.NodeId = nodecnt++; StackTrace st = new StackTrace(true); for (int i = 1; i < st.FrameCount; i++) { StackFrame sf = st.GetFrame(i); Type mt = sf.GetMethod().DeclaringType; if (mt != typeof(QilFactory) && mt != typeof(QilPatternFactory)) { n.NodeLocation = mt.FullName + "." + sf.GetMethod().Name + " (" + sf.GetFileName() + ": " + sf.GetFileLineNumber() + "," + sf.GetFileColumnNumber() + ")"; break; } } } } private Diagnostics diag = new Diagnostics(); public Diagnostics DebugInfo { get { return diag; } set { diag = value; } } #endif [System.Diagnostics.Conditional("QIL_TRACE_NODE_CREATION")] public void TraceNode(QilNode n) { #if QIL_TRACE_NODE_CREATION this.diag.AddNode(n); #endif } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Lists; using osu.Framework.Logging; using osu.Framework.Threading; using osu.Framework.Utils; using osu.Game.Configuration; using osu.Game.Database; using osu.Game.Rulesets; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.UI; namespace osu.Game.Beatmaps { /// <summary> /// A component which performs and acts as a central cache for difficulty calculations of beatmap/ruleset/mod combinations. /// Currently not persisted between game sessions. /// </summary> public class BeatmapDifficultyCache : MemoryCachingComponent<BeatmapDifficultyCache.DifficultyCacheLookup, StarDifficulty?> { // Too many simultaneous updates can lead to stutters. One thread seems to work fine for song select display purposes. private readonly ThreadedTaskScheduler updateScheduler = new ThreadedTaskScheduler(1, nameof(BeatmapDifficultyCache)); /// <summary> /// All bindables that should be updated along with the current ruleset + mods. /// </summary> private readonly WeakList<BindableStarDifficulty> trackedBindables = new WeakList<BindableStarDifficulty>(); /// <summary> /// Cancellation sources used by tracked bindables. /// </summary> private readonly List<CancellationTokenSource> linkedCancellationSources = new List<CancellationTokenSource>(); /// <summary> /// Lock to be held when operating on <see cref="trackedBindables"/> or <see cref="linkedCancellationSources"/>. /// </summary> private readonly object bindableUpdateLock = new object(); private CancellationTokenSource trackedUpdateCancellationSource; [Resolved] private BeatmapManager beatmapManager { get; set; } [Resolved] private Bindable<RulesetInfo> currentRuleset { get; set; } [Resolved] private Bindable<IReadOnlyList<Mod>> currentMods { get; set; } private ModSettingChangeTracker modSettingChangeTracker; private ScheduledDelegate debouncedModSettingsChange; protected override void LoadComplete() { base.LoadComplete(); currentRuleset.BindValueChanged(_ => updateTrackedBindables()); currentMods.BindValueChanged(mods => { modSettingChangeTracker?.Dispose(); updateTrackedBindables(); modSettingChangeTracker = new ModSettingChangeTracker(mods.NewValue); modSettingChangeTracker.SettingChanged += _ => { debouncedModSettingsChange?.Cancel(); debouncedModSettingsChange = Scheduler.AddDelayed(updateTrackedBindables, 100); }; }, true); } /// <summary> /// Retrieves a bindable containing the star difficulty of a <see cref="BeatmapInfo"/> that follows the currently-selected ruleset and mods. /// </summary> /// <param name="beatmapInfo">The <see cref="BeatmapInfo"/> to get the difficulty of.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> which stops updating the star difficulty for the given <see cref="BeatmapInfo"/>.</param> /// <returns>A bindable that is updated to contain the star difficulty when it becomes available. Will be null while in an initial calculating state (but not during updates to ruleset and mods if a stale value is already propagated).</returns> public IBindable<StarDifficulty?> GetBindableDifficulty([NotNull] IBeatmapInfo beatmapInfo, CancellationToken cancellationToken = default) { var bindable = createBindable(beatmapInfo, currentRuleset.Value, currentMods.Value, cancellationToken); lock (bindableUpdateLock) trackedBindables.Add(bindable); return bindable; } /// <summary> /// Retrieves a bindable containing the star difficulty of a <see cref="IBeatmapInfo"/> with a given <see cref="RulesetInfo"/> and <see cref="Mod"/> combination. /// </summary> /// <remarks> /// The bindable will not update to follow the currently-selected ruleset and mods or its settings. /// </remarks> /// <param name="beatmapInfo">The <see cref="IBeatmapInfo"/> to get the difficulty of.</param> /// <param name="rulesetInfo">The <see cref="IRulesetInfo"/> to get the difficulty with. If <c>null</c>, the <paramref name="beatmapInfo"/>'s ruleset is used.</param> /// <param name="mods">The <see cref="Mod"/>s to get the difficulty with. If <c>null</c>, no mods will be assumed.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> which stops updating the star difficulty for the given <see cref="IBeatmapInfo"/>.</param> /// <returns>A bindable that is updated to contain the star difficulty when it becomes available. Will be null while in an initial calculating state.</returns> public IBindable<StarDifficulty?> GetBindableDifficulty([NotNull] IBeatmapInfo beatmapInfo, [CanBeNull] IRulesetInfo rulesetInfo, [CanBeNull] IEnumerable<Mod> mods, CancellationToken cancellationToken = default) => createBindable(beatmapInfo, rulesetInfo, mods, cancellationToken); /// <summary> /// Retrieves the difficulty of a <see cref="IBeatmapInfo"/>. /// </summary> /// <param name="beatmapInfo">The <see cref="IBeatmapInfo"/> to get the difficulty of.</param> /// <param name="rulesetInfo">The <see cref="IRulesetInfo"/> to get the difficulty with.</param> /// <param name="mods">The <see cref="Mod"/>s to get the difficulty with.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> which stops computing the star difficulty.</param> /// <returns> /// The requested <see cref="StarDifficulty"/>, if non-<see langword="null"/>. /// A <see langword="null"/> return value indicates that the difficulty process failed or was interrupted early, /// and as such there is no usable star difficulty value to be returned. /// </returns> public virtual Task<StarDifficulty?> GetDifficultyAsync([NotNull] IBeatmapInfo beatmapInfo, [CanBeNull] IRulesetInfo rulesetInfo = null, [CanBeNull] IEnumerable<Mod> mods = null, CancellationToken cancellationToken = default) { // In the case that the user hasn't given us a ruleset, use the beatmap's default ruleset. rulesetInfo ??= beatmapInfo.Ruleset; var localBeatmapInfo = beatmapInfo as BeatmapInfo; var localRulesetInfo = rulesetInfo as RulesetInfo; // Difficulty can only be computed if the beatmap and ruleset are locally available. if (localBeatmapInfo == null || localBeatmapInfo.ID == 0 || localRulesetInfo == null) { // If not, fall back to the existing star difficulty (e.g. from an online source). return Task.FromResult<StarDifficulty?>(new StarDifficulty(beatmapInfo.StarRating, (beatmapInfo as IBeatmapOnlineInfo)?.MaxCombo ?? 0)); } return GetAsync(new DifficultyCacheLookup(localBeatmapInfo, localRulesetInfo, mods), cancellationToken); } protected override Task<StarDifficulty?> ComputeValueAsync(DifficultyCacheLookup lookup, CancellationToken cancellationToken = default) { return Task.Factory.StartNew(() => { if (CheckExists(lookup, out var existing)) return existing; return computeDifficulty(lookup, cancellationToken); }, cancellationToken, TaskCreationOptions.HideScheduler | TaskCreationOptions.RunContinuationsAsynchronously, updateScheduler); } protected override bool CacheNullValues => false; public Task<List<TimedDifficultyAttributes>> GetTimedDifficultyAttributesAsync(IWorkingBeatmap beatmap, Ruleset ruleset, Mod[] mods, CancellationToken cancellationToken = default) { return Task.Factory.StartNew(() => ruleset.CreateDifficultyCalculator(beatmap).CalculateTimed(mods, cancellationToken), cancellationToken, TaskCreationOptions.HideScheduler | TaskCreationOptions.RunContinuationsAsynchronously, updateScheduler); } /// <summary> /// Retrieves the <see cref="DifficultyRating"/> that describes a star rating. /// </summary> /// <remarks> /// For more information, see: https://osu.ppy.sh/help/wiki/Difficulties /// </remarks> /// <param name="starRating">The star rating.</param> /// <returns>The <see cref="DifficultyRating"/> that best describes <paramref name="starRating"/>.</returns> public static DifficultyRating GetDifficultyRating(double starRating) { if (Precision.AlmostBigger(starRating, 6.5, 0.005)) return DifficultyRating.ExpertPlus; if (Precision.AlmostBigger(starRating, 5.3, 0.005)) return DifficultyRating.Expert; if (Precision.AlmostBigger(starRating, 4.0, 0.005)) return DifficultyRating.Insane; if (Precision.AlmostBigger(starRating, 2.7, 0.005)) return DifficultyRating.Hard; if (Precision.AlmostBigger(starRating, 2.0, 0.005)) return DifficultyRating.Normal; return DifficultyRating.Easy; } /// <summary> /// Updates all tracked <see cref="BindableStarDifficulty"/> using the current ruleset and mods. /// </summary> private void updateTrackedBindables() { lock (bindableUpdateLock) { cancelTrackedBindableUpdate(); trackedUpdateCancellationSource = new CancellationTokenSource(); foreach (var b in trackedBindables) { var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(trackedUpdateCancellationSource.Token, b.CancellationToken); linkedCancellationSources.Add(linkedSource); updateBindable(b, currentRuleset.Value, currentMods.Value, linkedSource.Token); } } } /// <summary> /// Cancels the existing update of all tracked <see cref="BindableStarDifficulty"/> via <see cref="updateTrackedBindables"/>. /// </summary> private void cancelTrackedBindableUpdate() { lock (bindableUpdateLock) { trackedUpdateCancellationSource?.Cancel(); trackedUpdateCancellationSource = null; if (linkedCancellationSources != null) { foreach (var c in linkedCancellationSources) c.Dispose(); linkedCancellationSources.Clear(); } } } /// <summary> /// Creates a new <see cref="BindableStarDifficulty"/> and triggers an initial value update. /// </summary> /// <param name="beatmapInfo">The <see cref="IBeatmapInfo"/> that star difficulty should correspond to.</param> /// <param name="initialRulesetInfo">The initial <see cref="IRulesetInfo"/> to get the difficulty with.</param> /// <param name="initialMods">The initial <see cref="Mod"/>s to get the difficulty with.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> which stops updating the star difficulty for the given <see cref="IBeatmapInfo"/>.</param> /// <returns>The <see cref="BindableStarDifficulty"/>.</returns> private BindableStarDifficulty createBindable([NotNull] IBeatmapInfo beatmapInfo, [CanBeNull] IRulesetInfo initialRulesetInfo, [CanBeNull] IEnumerable<Mod> initialMods, CancellationToken cancellationToken) { var bindable = new BindableStarDifficulty(beatmapInfo, cancellationToken); updateBindable(bindable, initialRulesetInfo, initialMods, cancellationToken); return bindable; } /// <summary> /// Updates the value of a <see cref="BindableStarDifficulty"/> with a given ruleset + mods. /// </summary> /// <param name="bindable">The <see cref="BindableStarDifficulty"/> to update.</param> /// <param name="rulesetInfo">The <see cref="IRulesetInfo"/> to update with.</param> /// <param name="mods">The <see cref="Mod"/>s to update with.</param> /// <param name="cancellationToken">A token that may be used to cancel this update.</param> private void updateBindable([NotNull] BindableStarDifficulty bindable, [CanBeNull] IRulesetInfo rulesetInfo, [CanBeNull] IEnumerable<Mod> mods, CancellationToken cancellationToken = default) { // GetDifficultyAsync will fall back to existing data from IBeatmapInfo if not locally available // (contrary to GetAsync) GetDifficultyAsync(bindable.BeatmapInfo, rulesetInfo, mods, cancellationToken) .ContinueWith(t => { // We're on a threadpool thread, but we should exit back to the update thread so consumers can safely handle value-changed events. Schedule(() => { if (!cancellationToken.IsCancellationRequested && t.Result != null) bindable.Value = t.Result; }); }, cancellationToken); } /// <summary> /// Computes the difficulty defined by a <see cref="DifficultyCacheLookup"/> key, and stores it to the timed cache. /// </summary> /// <param name="key">The <see cref="DifficultyCacheLookup"/> that defines the computation parameters.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The <see cref="StarDifficulty"/>.</returns> private StarDifficulty? computeDifficulty(in DifficultyCacheLookup key, CancellationToken cancellationToken = default) { // In the case that the user hasn't given us a ruleset, use the beatmap's default ruleset. var beatmapInfo = key.BeatmapInfo; var rulesetInfo = key.Ruleset; try { var ruleset = rulesetInfo.CreateInstance(); Debug.Assert(ruleset != null); var calculator = ruleset.CreateDifficultyCalculator(beatmapManager.GetWorkingBeatmap(key.BeatmapInfo)); var attributes = calculator.Calculate(key.OrderedMods, cancellationToken); return new StarDifficulty(attributes); } catch (OperationCanceledException) { // no need to log, cancellations are expected as part of normal operation. return null; } catch (BeatmapInvalidForRulesetException invalidForRuleset) { if (rulesetInfo.Equals(beatmapInfo.Ruleset)) Logger.Error(invalidForRuleset, $"Failed to convert {beatmapInfo.OnlineID} to the beatmap's default ruleset ({beatmapInfo.Ruleset})."); return null; } catch (Exception unknownException) { Logger.Error(unknownException, "Failed to calculate beatmap difficulty"); return null; } } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); modSettingChangeTracker?.Dispose(); cancelTrackedBindableUpdate(); updateScheduler?.Dispose(); } public readonly struct DifficultyCacheLookup : IEquatable<DifficultyCacheLookup> { public readonly BeatmapInfo BeatmapInfo; public readonly RulesetInfo Ruleset; public readonly Mod[] OrderedMods; public DifficultyCacheLookup([NotNull] BeatmapInfo beatmapInfo, [CanBeNull] RulesetInfo ruleset, IEnumerable<Mod> mods) { BeatmapInfo = beatmapInfo; // In the case that the user hasn't given us a ruleset, use the beatmap's default ruleset. Ruleset = ruleset ?? BeatmapInfo.Ruleset; OrderedMods = mods?.OrderBy(m => m.Acronym).Select(mod => mod.DeepClone()).ToArray() ?? Array.Empty<Mod>(); } public bool Equals(DifficultyCacheLookup other) => BeatmapInfo.Equals(other.BeatmapInfo) && Ruleset.Equals(other.Ruleset) && OrderedMods.SequenceEqual(other.OrderedMods); public override int GetHashCode() { var hashCode = new HashCode(); hashCode.Add(BeatmapInfo.ID); hashCode.Add(Ruleset.ShortName); foreach (var mod in OrderedMods) hashCode.Add(mod); return hashCode.ToHashCode(); } } private class BindableStarDifficulty : Bindable<StarDifficulty?> { public readonly IBeatmapInfo BeatmapInfo; public readonly CancellationToken CancellationToken; public BindableStarDifficulty(IBeatmapInfo beatmapInfo, CancellationToken cancellationToken) { BeatmapInfo = beatmapInfo; CancellationToken = cancellationToken; } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.IO; using System.IO.Compression; using System.Runtime.CompilerServices; using System.Text; using NLog.Common; using NLog.Layouts; using NLog.Targets; using Xunit; #if !NETSTANDARD using Ionic.Zip; #endif public abstract class NLogTestBase { protected NLogTestBase() { //reset before every test LogManager.ThrowExceptions = false; // Ignore any errors triggered by closing existing config LogManager.Configuration = null; // Will close any existing config LogManager.LogFactory.ResetCandidateConfigFilePath(); InternalLogger.Reset(); InternalLogger.LogLevel = LogLevel.Off; LogManager.ThrowExceptions = true; // Ensure exceptions are thrown by default during unit-testing LogManager.ThrowConfigExceptions = null; System.Diagnostics.Trace.Listeners.Clear(); #if !NETSTANDARD System.Diagnostics.Debug.Listeners.Clear(); #endif } protected void AssertDebugCounter(string targetName, int val) { Assert.Equal(val, GetDebugTarget(targetName).Counter); } protected void AssertDebugLastMessage(string targetName, string msg) { Assert.Equal(msg, GetDebugLastMessage(targetName)); } protected void AssertDebugLastMessage(string targetName, string msg, LogFactory logFactory) { Assert.Equal(msg, GetDebugLastMessage(targetName, logFactory)); } protected void AssertDebugLastMessageContains(string targetName, string msg) { string debugLastMessage = GetDebugLastMessage(targetName); Assert.True(debugLastMessage.Contains(msg), $"Expected to find '{msg}' in last message value on '{targetName}', but found '{debugLastMessage}'"); } protected string GetDebugLastMessage(string targetName) { return GetDebugLastMessage(targetName, LogManager.LogFactory); } protected string GetDebugLastMessage(string targetName, LogFactory logFactory) { return GetDebugTarget(targetName, logFactory).LastMessage; } public DebugTarget GetDebugTarget(string targetName) { return GetDebugTarget(targetName, LogManager.LogFactory); } protected DebugTarget GetDebugTarget(string targetName, LogFactory logFactory) { return LogFactoryTestExtensions.GetDebugTarget(targetName, logFactory.Configuration); } protected void AssertFileContentsStartsWith(string fileName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); byte[] buf = File.ReadAllBytes(fileName); Assert.True(encodedBuf.Length <= buf.Length, $"File:{fileName} encodedBytes:{encodedBuf.Length} does not match file.content:{buf.Length}, file.length = {fi.Length}"); for (int i = 0; i < encodedBuf.Length; ++i) { if (encodedBuf[i] != buf[i]) Assert.True(encodedBuf[i] == buf[i], $"File:{fileName} content mismatch {(int)encodedBuf[i]} <> {(int)buf[i]} at index {i}"); } } protected void AssertFileContentsEndsWith(string fileName, string contents, Encoding encoding) { if (!File.Exists(fileName)) Assert.True(false, "File '" + fileName + "' doesn't exist."); string fileText = File.ReadAllText(fileName, encoding); Assert.True(fileText.Length >= contents.Length); Assert.Equal(contents, fileText.Substring(fileText.Length - contents.Length)); } protected class CustomFileCompressor : IArchiveFileCompressor { public void CompressFile(string fileName, string archiveFileName) { string entryName = Path.GetFileNameWithoutExtension(archiveFileName) + Path.GetExtension(fileName); CompressFile(fileName, archiveFileName, entryName); } public void CompressFile(string fileName, string archiveFileName, string entryName) { #if !NETSTANDARD using (var zip = new Ionic.Zip.ZipFile()) { ZipEntry entry = zip.AddFile(fileName); entry.FileName = entryName; zip.Save(archiveFileName); } #endif } } #if NET35 || NET40 protected void AssertZipFileContents(string fileName, string expectedEntryName, string contents, Encoding encoding) { if (!File.Exists(fileName)) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); using (var zip = new Ionic.Zip.ZipFile(fileName)) { Assert.Equal(1, zip.Count); Assert.Equal(encodedBuf.Length, zip[0].UncompressedSize); byte[] buf = new byte[zip[0].UncompressedSize]; using (var fs = zip[0].OpenReader()) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } } #else protected void AssertZipFileContents(string fileName, string expectedEntryName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var zip = new ZipArchive(stream, ZipArchiveMode.Read)) { Assert.Single(zip.Entries); Assert.Equal(expectedEntryName, zip.Entries[0].Name); Assert.Equal(encodedBuf.Length, zip.Entries[0].Length); byte[] buf = new byte[(int)zip.Entries[0].Length]; using (var fs = zip.Entries[0].Open()) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } } #endif protected void AssertFileContents(string fileName, string expectedEntryName, string contents, Encoding encoding) { AssertFileContents(fileName, contents, encoding, false); } protected void AssertFileContents(string fileName, string contents, Encoding encoding) { AssertFileContents(fileName, contents, encoding, false); } protected void AssertFileContents(string fileName, string contents, Encoding encoding, bool addBom) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); //add bom if needed if (addBom) { var preamble = encoding.GetPreamble(); if (preamble.Length > 0) { //insert before encodedBuf = preamble.Concat(encodedBuf).ToArray(); } } byte[] buf; using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { int index = 0; int count = (int)fs.Length; buf = new byte[count]; while (count > 0) { int n = fs.Read(buf, index, count); if (n == 0) break; index += n; count -= n; } } Assert.True(encodedBuf.Length == buf.Length, $"File:{fileName} encodedBytes:{encodedBuf.Length} does not match file.content:{buf.Length}, file.length = {fi.Length}"); for (int i = 0; i < buf.Length; ++i) { if (encodedBuf[i] != buf[i]) Assert.True(encodedBuf[i] == buf[i], $"File:{fileName} content mismatch {(int)encodedBuf[i]} <> {(int)buf[i]} at index {i}"); } } protected void AssertFileContains(string fileName, string contentToCheck, Encoding encoding) { if (contentToCheck.Contains(Environment.NewLine)) Assert.True(false, "Please use only single line string to check."); FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); using (TextReader fs = new StreamReader(fileName, encoding)) { string line; while ((line = fs.ReadLine()) != null) { if (line.Contains(contentToCheck)) return; } } Assert.True(false, "File doesn't contains '" + contentToCheck + "'"); } protected void AssertFileNotContains(string fileName, string contentToCheck, Encoding encoding) { if (contentToCheck.Contains(Environment.NewLine)) Assert.True(false, "Please use only single line string to check."); FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); using (TextReader fs = new StreamReader(fileName, encoding)) { string line; while ((line = fs.ReadLine()) != null) { if (line.Contains(contentToCheck)) Assert.False(true, "File contains '" + contentToCheck + "'"); } } } protected string StringRepeat(int times, string s) { StringBuilder sb = new StringBuilder(s.Length * times); for (int i = 0; i < times; ++i) sb.Append(s); return sb.ToString(); } /// <summary> /// Render layout <paramref name="layout"/> with dummy <see cref="LogEventInfo" />and compare result with <paramref name="expected"/>. /// </summary> protected static void AssertLayoutRendererOutput(Layout layout, string expected) { var logEventInfo = LogEventInfo.Create(LogLevel.Info, "loggername", "message"); AssertLayoutRendererOutput(layout, logEventInfo, expected); } /// <summary> /// Render layout <paramref name="layout"/> with <paramref name="logEventInfo"/> and compare result with <paramref name="expected"/>. /// </summary> protected static void AssertLayoutRendererOutput(Layout layout, LogEventInfo logEventInfo, string expected) { layout.Initialize(null); string actual = layout.Render(logEventInfo); layout.Close(); Assert.Equal(expected, actual); } #if !NET35 && !NET40 /// <summary> /// Get line number of previous line. /// </summary> protected int GetPrevLineNumber([CallerLineNumber] int callingFileLineNumber = 0) { return callingFileLineNumber - 1; } #else /// <summary> /// Get line number of previous line. /// </summary> protected int GetPrevLineNumber() { //fixed value set with #line 100000 return 100001; } #endif protected string RunAndCaptureInternalLog(SyncAction action, LogLevel internalLogLevel) { var stringWriter = new Logger(); var orgWriter = InternalLogger.LogWriter; var orgTimestamp = InternalLogger.IncludeTimestamp; var orgLevel = InternalLogger.LogLevel; try { InternalLogger.LogWriter = stringWriter; InternalLogger.IncludeTimestamp = false; InternalLogger.LogLevel = internalLogLevel; action(); } finally { InternalLogger.LogWriter = orgWriter; InternalLogger.IncludeTimestamp = orgTimestamp; InternalLogger.LogLevel = orgLevel; } return stringWriter.ToString(); } /// <summary> /// To handle unstable integration tests, retry if failed /// </summary> /// <param name="tries"></param> /// <param name="action"></param> protected void RetryingIntegrationTest(int tries, Action action) { int tried = 0; while (tried < tries) { try { tried++; action(); return; //success } catch (Exception) { if (tried >= tries) { throw; } } } } /// <summary> /// This class has to be used when outputting from the InternalLogger.LogWriter. /// Just creating a string writer will cause issues, since string writer is not thread safe. /// This can cause issues when calling the ToString() on the text writer, since the underlying stringbuilder /// of the textwriter, has char arrays that gets fucked up by the multiple threads. /// this is a simple wrapper that just locks access to the writer so only one thread can access /// it at a time. /// </summary> private class Logger : TextWriter { private readonly StringWriter writer = new StringWriter(); public override Encoding Encoding => writer.Encoding; #if NETSTANDARD1_5 public override void Write(char value) { lock (this.writer) { this.writer.Write(value); } } #endif public override void Write(string value) { lock (writer) { writer.Write(value); } } public override void WriteLine(string value) { lock (writer) { writer.WriteLine(value); } } public override string ToString() { lock (writer) { return writer.ToString(); } } } /// <summary> /// Creates <see cref="CultureInfo"/> instance for test purposes /// </summary> /// <param name="cultureName">Culture name to create</param> /// <remarks> /// Creates <see cref="CultureInfo"/> instance with non-userOverride /// flag to provide expected results when running tests in different /// system cultures(with overriden culture options) /// </remarks> protected static CultureInfo GetCultureInfo(string cultureName) { return new CultureInfo(cultureName, false); } /// <summary> /// Are we running on Linux environment or Windows environemtn ? /// </summary> /// <returns>true when something else than Windows</returns> protected static bool IsLinux() { return !NLog.Internal.PlatformDetector.IsWin32; } /// <summary> /// Are we running on AppVeyor? /// </summary> /// <returns></returns> protected static bool IsAppVeyor() { var val = Environment.GetEnvironmentVariable("APPVEYOR"); return val != null && val.Equals("true", StringComparison.OrdinalIgnoreCase); } public delegate void SyncAction(); public class NoThrowNLogExceptions : IDisposable { private readonly bool throwExceptions; public NoThrowNLogExceptions() { throwExceptions = LogManager.ThrowExceptions; LogManager.ThrowExceptions = false; } public void Dispose() { LogManager.ThrowExceptions = throwExceptions; } } public class InternalLoggerScope : IDisposable { private readonly TextWriter oldConsoleOutputWriter; public StringWriter ConsoleOutputWriter { get; private set; } private readonly TextWriter oldConsoleErrorWriter; public StringWriter ConsoleErrorWriter { get; private set; } private readonly LogLevel globalThreshold; private readonly bool throwExceptions; private readonly bool? throwConfigExceptions; public InternalLoggerScope(bool redirectConsole = false) { InternalLogger.LogLevel = LogLevel.Info; if (redirectConsole) { ConsoleOutputWriter = new StringWriter() { NewLine = "\n" }; ConsoleErrorWriter = new StringWriter() { NewLine = "\n" }; oldConsoleOutputWriter = Console.Out; oldConsoleErrorWriter = Console.Error; Console.SetOut(ConsoleOutputWriter); Console.SetError(ConsoleErrorWriter); } globalThreshold = LogManager.GlobalThreshold; throwExceptions = LogManager.ThrowExceptions; throwConfigExceptions = LogManager.ThrowConfigExceptions; } public void SetConsoleError(StringWriter consoleErrorWriter) { if (ConsoleOutputWriter is null || consoleErrorWriter is null) throw new InvalidOperationException("Initialize with redirectConsole=true"); ConsoleErrorWriter = consoleErrorWriter; Console.SetError(consoleErrorWriter); } public void SetConsoleOutput(StringWriter consoleOutputWriter) { if (ConsoleOutputWriter is null || consoleOutputWriter is null) throw new InvalidOperationException("Initialize with redirectConsole=true"); ConsoleOutputWriter = consoleOutputWriter; Console.SetOut(consoleOutputWriter); } public void Dispose() { var logFile = InternalLogger.LogFile; InternalLogger.Reset(); LogManager.GlobalThreshold = globalThreshold; LogManager.ThrowExceptions = throwExceptions; LogManager.ThrowConfigExceptions = throwConfigExceptions; if (ConsoleOutputWriter != null) Console.SetOut(oldConsoleOutputWriter); if (ConsoleErrorWriter != null) Console.SetError(oldConsoleErrorWriter); if (!string.IsNullOrEmpty(InternalLogger.LogFile)) { if (File.Exists(InternalLogger.LogFile)) File.Delete(InternalLogger.LogFile); } if (!string.IsNullOrEmpty(logFile) && logFile != InternalLogger.LogFile) { if (File.Exists(logFile)) File.Delete(logFile); } } } protected static void AssertContainsInDictionary<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { Assert.Contains(key, dictionary); Assert.Equal(value, dictionary[key]); } } }
using GitVersion.BuildAgents; using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; using GitVersion.Model; using GitVersion.OutputVariables; namespace GitVersion; public class ArgumentParser : IArgumentParser { private readonly IEnvironment environment; private readonly ICurrentBuildAgent buildAgent; private readonly IConsole console; private readonly IGlobbingResolver globbingResolver; private const string defaultOutputFileName = "GitVersion.json"; public ArgumentParser(IEnvironment environment, ICurrentBuildAgent buildAgent, IConsole console, IGlobbingResolver globbingResolver) { this.environment = environment.NotNull(); this.console = console.NotNull(); this.globbingResolver = globbingResolver.NotNull(); this.buildAgent = buildAgent.NotNull(); } public Arguments ParseArguments(string commandLineArguments) { var arguments = QuotedStringHelpers.SplitUnquoted(commandLineArguments, ' '); return ParseArguments(arguments); } public Arguments ParseArguments(string[] commandLineArguments) { if (commandLineArguments.Length == 0) { var args = new Arguments { TargetPath = System.Environment.CurrentDirectory }; args.Output.Add(OutputType.Json); AddAuthentication(args); args.NoFetch = this.buildAgent.PreventFetch(); return args; } var firstArgument = commandLineArguments.First(); if (firstArgument.IsInit()) { return new Arguments { TargetPath = System.Environment.CurrentDirectory, Init = true }; } if (firstArgument.IsHelp()) { return new Arguments { IsHelp = true }; } if (firstArgument.IsSwitch("version")) { return new Arguments { IsVersion = true }; } var arguments = new Arguments(); AddAuthentication(arguments); var switchesAndValues = CollectSwitchesAndValuesFromArguments(commandLineArguments, out var firstArgumentIsSwitch); for (var i = 0; i < switchesAndValues.AllKeys.Length; i++) { ParseSwitchArguments(arguments, switchesAndValues, i); } if (arguments.Output.Count == 0) { arguments.Output.Add(OutputType.Json); } if (arguments.Output.Contains(OutputType.File) && arguments.OutputFile == null) { arguments.OutputFile = defaultOutputFileName; } // If the first argument is a switch, it should already have been consumed in the above loop, // or else a WarningException should have been thrown and we wouldn't end up here. arguments.TargetPath ??= firstArgumentIsSwitch ? System.Environment.CurrentDirectory : firstArgument; arguments.TargetPath = arguments.TargetPath.TrimEnd('/', '\\'); if (!arguments.EnsureAssemblyInfo) arguments.UpdateAssemblyInfoFileName = ResolveFiles(arguments.TargetPath, arguments.UpdateAssemblyInfoFileName).ToHashSet(); arguments.NoFetch = arguments.NoFetch || this.buildAgent.PreventFetch(); return arguments; } private void ParseSwitchArguments(Arguments arguments, NameValueCollection switchesAndValues, int i) { var name = switchesAndValues.AllKeys[i]; var values = switchesAndValues.GetValues(name); var value = values?.FirstOrDefault(); if (ParseSwitches(arguments, name, values, value)) return; ParseTargetPath(arguments, name, values, value, i == 0); } private void AddAuthentication(Arguments arguments) { var username = this.environment.GetEnvironmentVariable("GITVERSION_REMOTE_USERNAME"); if (!username.IsNullOrWhiteSpace()) { arguments.Authentication.Username = username; } var password = this.environment.GetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD"); if (!password.IsNullOrWhiteSpace()) { arguments.Authentication.Password = password; } } private IEnumerable<string> ResolveFiles(string workingDirectory, ISet<string>? assemblyInfoFiles) { if (assemblyInfoFiles == null) yield break; foreach (var file in assemblyInfoFiles) { var paths = this.globbingResolver.Resolve(workingDirectory, file); foreach (var path in paths) { yield return Path.GetFullPath(PathHelper.Combine(workingDirectory, path)); } } } private void ParseTargetPath(Arguments arguments, string? name, IReadOnlyList<string>? values, string? value, bool parseEnded) { if (name.IsSwitch("targetpath")) { EnsureArgumentValueCount(values); arguments.TargetPath = value; if (!Directory.Exists(value)) { this.console.WriteLine($"The working directory '{value}' does not exist."); } return; } var couldNotParseMessage = $"Could not parse command line parameter '{name}'."; // If we've reached through all argument switches without a match, we can relatively safely assume that the first argument isn't a switch, but the target path. if (parseEnded) { if (name != null && name.StartsWith("/")) { if (Path.DirectorySeparatorChar == '/' && name.IsValidPath()) { arguments.TargetPath = name; return; } } else if (!name.IsSwitchArgument()) { arguments.TargetPath = name; return; } couldNotParseMessage += " If it is the target path, make sure it exists."; } throw new WarningException(couldNotParseMessage); } private static bool ParseSwitches(Arguments arguments, string? name, IReadOnlyList<string>? values, string? value) { if (name.IsSwitch("l")) { EnsureArgumentValueCount(values); arguments.LogFilePath = value; return true; } if (ParseConfigArguments(arguments, name, values, value)) return true; if (ParseRemoteArguments(arguments, name, values, value)) return true; if (name.IsSwitch("diag")) { if (value == null || value.IsTrue()) { arguments.Diag = true; } return true; } if (name.IsSwitch("updateprojectfiles")) { ParseUpdateProjectInfo(arguments, value, values); return true; } if (name.IsSwitch("updateAssemblyInfo")) { ParseUpdateAssemblyInfo(arguments, value, values); return true; } if (name.IsSwitch("ensureassemblyinfo")) { ParseEnsureAssemblyInfo(arguments, value); return true; } if (name.IsSwitch("v") || name.IsSwitch("showvariable")) { ParseShowVariable(arguments, value, name); return true; } if (name.IsSwitch("output")) { ParseOutput(arguments, values); return true; } if (name.IsSwitch("outputfile")) { EnsureArgumentValueCount(values); arguments.OutputFile = value; return true; } if (name.IsSwitch("nofetch")) { arguments.NoFetch = true; return true; } if (name.IsSwitch("nonormalize")) { arguments.NoNormalize = true; return true; } if (name.IsSwitch("nocache")) { arguments.NoCache = true; return true; } if (name.IsSwitch("verbosity")) { ParseVerbosity(arguments, value); return true; } if (name.IsSwitch("updatewixversionfile")) { arguments.UpdateWixVersionFile = true; return true; } return false; } private static bool ParseConfigArguments(Arguments arguments, string? name, IReadOnlyList<string>? values, string? value) { if (name.IsSwitch("config")) { EnsureArgumentValueCount(values); arguments.ConfigFile = value; return true; } if (name.IsSwitch("overrideconfig")) { ParseOverrideConfig(arguments, values); return true; } if (!name.IsSwitch("showConfig")) return false; arguments.ShowConfig = value.IsTrue() || !value.IsFalse(); return true; } private static bool ParseRemoteArguments(Arguments arguments, string? name, IReadOnlyList<string>? values, string? value) { if (name.IsSwitch("dynamicRepoLocation")) { EnsureArgumentValueCount(values); arguments.DynamicRepositoryClonePath = value; return true; } if (name.IsSwitch("url")) { EnsureArgumentValueCount(values); arguments.TargetUrl = value; return true; } if (name.IsSwitch("u")) { EnsureArgumentValueCount(values); arguments.Authentication.Username = value; return true; } if (name.IsSwitch("p")) { EnsureArgumentValueCount(values); arguments.Authentication.Password = value; return true; } if (name.IsSwitch("c")) { EnsureArgumentValueCount(values); arguments.CommitId = value; return true; } if (name.IsSwitch("b")) { EnsureArgumentValueCount(values); arguments.TargetBranch = value; return true; } return false; } private static void ParseShowVariable(Arguments arguments, string? value, string? name) { string? versionVariable = null; if (!value.IsNullOrWhiteSpace()) { versionVariable = VersionVariables.AvailableVariables.SingleOrDefault(av => av.Equals(value.Replace("'", ""), StringComparison.CurrentCultureIgnoreCase)); } if (versionVariable == null) { var message = $"{name} requires a valid version variable. Available variables are:{System.Environment.NewLine}" + string.Join(", ", VersionVariables.AvailableVariables.Select(x => string.Concat("'", x, "'"))); throw new WarningException(message); } arguments.ShowVariable = versionVariable; } private static void ParseEnsureAssemblyInfo(Arguments arguments, string? value) { arguments.EnsureAssemblyInfo = true; if (value.IsFalse()) { arguments.EnsureAssemblyInfo = false; } if (arguments.UpdateProjectFiles) { throw new WarningException("Cannot specify -ensureassemblyinfo with updateprojectfiles: please ensure your project file exists before attempting to update it"); } if (arguments.UpdateAssemblyInfoFileName.Count > 1 && arguments.EnsureAssemblyInfo) { throw new WarningException("Can't specify multiple assembly info files when using /ensureassemblyinfo switch, either use a single assembly info file or do not specify /ensureassemblyinfo and create assembly info files manually"); } } private static void ParseOutput(Arguments arguments, IEnumerable<string>? values) { if (values == null) return; foreach (var v in values) { if (!Enum.TryParse(v, true, out OutputType outputType)) { throw new WarningException($"Value '{v}' cannot be parsed as output type, please use 'json', 'file' or 'buildserver'"); } arguments.Output.Add(outputType); } } private static void ParseVerbosity(Arguments arguments, string? value) { // first try the old version, this check will be removed in version 6.0.0, making it a breaking change if (Enum.TryParse(value, true, out LogLevel logLevel)) { arguments.Verbosity = LogExtensions.GetVerbosityForLevel(logLevel); } else if (!Enum.TryParse(value, true, out arguments.Verbosity)) { throw new WarningException($"Could not parse Verbosity value '{value}'"); } } private static void ParseOverrideConfig(Arguments arguments, IReadOnlyCollection<string>? values) { if (values == null || values.Count == 0) return; var parser = new OverrideConfigOptionParser(); // key=value foreach (var keyValueOption in values) { var keyAndValue = QuotedStringHelpers.SplitUnquoted(keyValueOption, '='); if (keyAndValue.Length != 2) { throw new WarningException($"Could not parse /overrideconfig option: {keyValueOption}. Ensure it is in format 'key=value'."); } var optionKey = keyAndValue[0].ToLowerInvariant(); if (!OverrideConfigOptionParser.SupportedProperties.Contains(optionKey)) { throw new WarningException($"Could not parse /overrideconfig option: {keyValueOption}. Unsupported 'key'."); } parser.SetValue(optionKey, keyAndValue[1]); } arguments.OverrideConfig = parser.GetConfig(); } private static void ParseUpdateAssemblyInfo(Arguments arguments, string? value, IReadOnlyCollection<string>? values) { if (value.IsTrue()) { arguments.UpdateAssemblyInfo = true; } else if (value.IsFalse()) { arguments.UpdateAssemblyInfo = false; } else if (values is { Count: > 1 }) { arguments.UpdateAssemblyInfo = true; foreach (var v in values) { arguments.UpdateAssemblyInfoFileName.Add(v); } } else if (!value.IsSwitchArgument()) { arguments.UpdateAssemblyInfo = true; if (value != null) { arguments.UpdateAssemblyInfoFileName.Add(value); } } else { arguments.UpdateAssemblyInfo = true; } if (arguments.UpdateProjectFiles) { throw new WarningException("Cannot specify both updateprojectfiles and updateassemblyinfo in the same run. Please rerun GitVersion with only one parameter"); } if (arguments.UpdateAssemblyInfoFileName.Count > 1 && arguments.EnsureAssemblyInfo) { throw new WarningException("Can't specify multiple assembly info files when using -ensureassemblyinfo switch, either use a single assembly info file or do not specify -ensureassemblyinfo and create assembly info files manually"); } } private static void ParseUpdateProjectInfo(Arguments arguments, string? value, IReadOnlyCollection<string>? values) { if (value.IsTrue()) { arguments.UpdateProjectFiles = true; } else if (value.IsFalse()) { arguments.UpdateProjectFiles = false; } else if (values is { Count: > 1 }) { arguments.UpdateProjectFiles = true; foreach (var v in values) { arguments.UpdateAssemblyInfoFileName.Add(v); } } else if (!value.IsSwitchArgument()) { arguments.UpdateProjectFiles = true; if (value != null) { arguments.UpdateAssemblyInfoFileName.Add(value); } } else { arguments.UpdateProjectFiles = true; } if (arguments.UpdateAssemblyInfo) { throw new WarningException("Cannot specify both updateassemblyinfo and updateprojectfiles in the same run. Please rerun GitVersion with only one parameter"); } if (arguments.EnsureAssemblyInfo) { throw new WarningException("Cannot specify -ensureassemblyinfo with updateprojectfiles: please ensure your project file exists before attempting to update it"); } } private static void EnsureArgumentValueCount(IReadOnlyList<string>? values) { if (values is { Count: > 1 }) { throw new WarningException($"Could not parse command line parameter '{values[1]}'."); } } private static NameValueCollection CollectSwitchesAndValuesFromArguments(IList<string> namedArguments, out bool firstArgumentIsSwitch) { firstArgumentIsSwitch = true; var switchesAndValues = new NameValueCollection(); string? currentKey = null; var argumentRequiresValue = false; for (var i = 0; i < namedArguments.Count; i += 1) { var arg = namedArguments[i]; // If the current (previous) argument doesn't require a value parameter and this is a switch, create new name/value entry for it, with a null value. if (!argumentRequiresValue && arg.IsSwitchArgument()) { currentKey = arg; argumentRequiresValue = arg.ArgumentRequiresValue(i); switchesAndValues.Add(currentKey, null); } // If this is a value (not a switch) else if (currentKey != null) { // And if the current switch does not have a value yet and the value is not itself a switch, set its value to this argument. if (switchesAndValues[currentKey].IsNullOrEmpty()) { switchesAndValues[currentKey] = arg; } // Otherwise add the value under the same switch. else { switchesAndValues.Add(currentKey, arg); } // Reset the boolean argument flag so the next argument won't be ignored. argumentRequiresValue = false; } else if (i == 0) { firstArgumentIsSwitch = false; } } return switchesAndValues; } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; namespace DotSpatial.Data { /// <summary> /// This handles the methodology of progress messaging in one place to make it easier to update. /// </summary> public class ProgressMeter { #region Fields private double _endValue; private int _oldProg = -1; // the previous progress level private int _prog; // the current progress level private double _startValue; private int _stepPercent = 1; private double _value; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ProgressMeter"/> class, but doesn't support the IProgressHandler unless one is specified. /// </summary> public ProgressMeter() : this(null, "Calculating values.", 100) { } /// <summary> /// Initializes a new instance of the <see cref="ProgressMeter"/> class. /// A progress meter can't actually do anything without a progressHandler, which actually displays the status. /// </summary> /// <param name="progressHandler">An IProgressHandler that will actually handle the status messages sent by this meter.</param> public ProgressMeter(IProgressHandler progressHandler) : this(progressHandler, "Calculating values.", 100) { } /// <summary> /// Initializes a new instance of the <see cref="ProgressMeter"/> class that simply keeps track of progress and is capable of sending progress messages. /// This assumes a MaxValue of 100 unless it is changed later. /// </summary> /// <param name="progressHandler">Any valid IProgressHandler that will display progress messages.</param> /// <param name="baseMessage">A base message to use as the basic status for this progress handler.</param> public ProgressMeter(IProgressHandler progressHandler, string baseMessage) : this(progressHandler, baseMessage, 100) { } /// <summary> /// Initializes a new instance of the <see cref="ProgressMeter"/> class that simply keeps track of progress and is capable of sending progress messages. /// </summary> /// <param name="progressHandler">Any valid implementation if IProgressHandler that will handle the progress function.</param> /// <param name="baseMessage">The message without any progress information.</param> /// <param name="endValue">Percent should show a range between the MinValue and MaxValue. MinValue is assumed to be 0.</param> public ProgressMeter(IProgressHandler progressHandler, string baseMessage, object endValue) { _endValue = Convert.ToDouble(endValue); ProgressHandler = progressHandler; Reset(); BaseMessage = baseMessage; } #endregion #region Properties /// <summary> /// Gets or sets the string message (without the progress element). /// </summary> public string BaseMessage { get; set; } /// <summary> /// Gets or sets the current integer progress level from 0 to 100. If a new update is less than or equal to the previous /// value, then no progress will be displayed by the ProgressMeter. Values less than 0 are set to 0. Values greater than /// 100 are set to 100. /// </summary> public int CurrentPercent { get { return _prog; } set { int val = value; if (val < 0) val = 0; if (val > 100) { val = 100; } _prog = val; if (_prog >= _oldProg + _stepPercent) { SendProgress(); _oldProg = _prog; } } } /// <summary> /// Gets or sets the current value relative to the specified MaxValue in order to update the progress. /// Setting this will also update OldProgress if there is an integer change in the percentage, and send /// a progress message to the IProgressHandler interface. /// </summary> public object CurrentValue { get { return _value; } set { _value = Convert.ToDouble(value); if (_startValue < _endValue) { CurrentPercent = Convert.ToInt32(Math.Round(100 * (_value - _startValue) / (_endValue - _startValue))); } else { CurrentPercent = _startValue == _endValue ? 100 : Convert.ToInt32(Math.Round(100 * (_startValue - _value) / (_startValue - _endValue))); } } } /// <summary> /// Gets or sets the value that defines when the meter should show as 100% complete. /// EndValue can be less than StartValue, but values closer to EndValue /// will show as being closer to 100%. /// </summary> public object EndValue { get { return _endValue; } set { _endValue = Convert.ToDouble(value); } } /// <summary> /// Gets or sets the string that does not include any mention of progress percentage, but specifies what is occurring. /// </summary> public string Key { get { return BaseMessage; } set { BaseMessage = value; } } /// <summary> /// Gets or sets the previous integer progress level from 0 to 100. If a new update is less than or equal to the previous /// value, then no progress will be displayed by the ProgressMeter. Values less than 0 are set to 0. Values greater than /// 100 are set to 100. /// </summary> public int PreviousPercent { get { return _oldProg; } set { int val = value; if (val < 0) val = 0; if (val > 100) val = 100; _oldProg = val; } } /// <summary> /// Gets or sets the progress handler for this meter. /// </summary> public IProgressHandler ProgressHandler { get; set; } /// <summary> /// Gets or sets a value indicating whether the progress meter should send messages to the IProgressHandler. /// By default Silent is false, but setting this to true will disable the messaging portion. /// </summary> public bool Silent { get; set; } /// <summary> /// Gets or sets the minimum value the meter should show as 0% complete. /// </summary> public object StartValue { get { return _startValue; } set { _startValue = Convert.ToDouble(value); } } /// <summary> /// Gets or sets a value that is 1 by default. Ordinarily this will send a progress message only when the integer progress /// has changed by 1 percentage point. For example, if StepPercent were set to 5, then a progress update would only /// be sent out at 5%, 10% and so on. This helps reduce overhead in cases where showing status messages is actually /// the majority of the processing time for the function. /// </summary> public int StepPercent { get { return _stepPercent; } set { _stepPercent = value; if (_stepPercent < 1) _stepPercent = 1; if (_stepPercent > 100) _stepPercent = 100; } } #endregion #region Methods /// <summary> /// This always increments the CurrentValue by one. /// </summary> public void Next() { CurrentValue = _value + 1; } /// <summary> /// Resets the progress meter to the 0 value. This sets the status message to "Ready.". /// </summary> public void Reset() { _prog = 0; _oldProg = 0; BaseMessage = "Ready."; if (Silent) return; ProgressHandler?.Progress(_prog, BaseMessage); } /// <summary> /// Sends a progress message to the IProgressHandler interface with the current message and progress. /// </summary> public void SendProgress() { if (Silent) return; ProgressHandler?.Progress(_prog, BaseMessage + ", " + _prog + "% Complete."); } #endregion } }
using System; using System.Linq; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Extensions.DependencyInjection; namespace OptionsWebSite.Models { public static class SeedData { public static async void Initialize(IServiceProvider serviceProvider) { var context = serviceProvider.GetService<DiplomaOptionsContext>(); var identityContext = serviceProvider.GetService<ApplicationDbContext>(); var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>(); var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); if (context.Database == null || identityContext.Database == null) { throw new Exception("DB is null"); } if (!identityContext.Users.Any()){ if (!(await roleManager.RoleExistsAsync("Admin"))) await roleManager.CreateAsync(new IdentityRole("Admin")); if (!(await roleManager.RoleExistsAsync("Student"))) await roleManager.CreateAsync(new IdentityRole("Student")); string[] emails = { "a@a.a", "s@s.s" }; string[] studentIds = { "A00111111", "A00222222" }; if ( (await userManager.FindByEmailAsync(emails[0])) == null) { var user = new ApplicationUser { Email = emails[0], UserName = studentIds[0], }; var result = await userManager.CreateAsync(user, "P@$$w0rd"); if (result.Succeeded){ await userManager.AddToRoleAsync( (await userManager.FindByEmailAsync(user.Email)) , "Admin"); var addedUser = await userManager.FindByNameAsync(studentIds[0]); await userManager.SetLockoutEnabledAsync(addedUser, false); } } if ( (await userManager.FindByEmailAsync(emails[1])) == null) { var user = new ApplicationUser { Email = emails[1], UserName = studentIds[1], }; var result = await userManager.CreateAsync(user, "P@$$w0rd"); if (result.Succeeded){ await userManager.AddToRoleAsync( (await userManager.FindByEmailAsync(user.Email) ), "Student"); var addedUser = await userManager.FindByNameAsync(studentIds[1]); await userManager.SetLockoutEnabledAsync(addedUser, false); } } } if (!context.YearTerms.Any()) { // Seed YearTerms context.YearTerms.AddRange( new YearTerm { Year = 2015, Term = 10, IsDefault = false }, new YearTerm { Year = 2015, Term = 20, IsDefault = false }, new YearTerm { Year = 2015, Term = 30, IsDefault = false }, new YearTerm { Year = 2016, Term = 10, IsDefault = true }); context.SaveChanges(); } if (!context.Options.Any()) { // Seed Options context.Options.AddRange( new Option { Title = "Data Communications", IsActive = true }, new Option { Title = "Client Server", IsActive = true }, new Option { Title = "Digital Processing", IsActive = true }, new Option { Title = "Information Systems", IsActive = true }, new Option { Title = "Database", IsActive = false }, new Option { Title = "Web & Mobile", IsActive = true }, new Option { Title = "Tech Pro", IsActive = false }); context.SaveChanges(); } if (!context.Choices.Any()) { // Seed Choices context.Choices.AddRange( // Seed 10 choices for 2015-30 CreateChoice(context, "A00333333", "Bob", "White", 2015, 30), CreateChoice(context, "A00444444", "James", "Smith", 2015, 30), CreateChoice(context, "A00555555", "John", "Doe", 2015, 30), CreateChoice(context, "A00666666", "Jack", "Williams", 2015, 30), CreateChoice(context, "A00777777", "Gus", "Johnson", 2015, 30), CreateChoice(context, "A00888888", "Fred", "Green", 2015, 30), CreateChoice(context, "A00999999", "Jessica", "Ford", 2015, 30), CreateChoice(context, "A00121212", "Rebecca", "Scott", 2015, 30), CreateChoice(context, "A00232323", "Rachel", "Allen", 2015, 30), CreateChoice(context, "A00343434", "Tony", "Peters", 2015, 30), // Seed 10 choices for 2016-10 CreateChoice(context, "A00454545", "Tom", "Carlson", 2016, 10), CreateChoice(context, "A00565656", "Kate", "Leung", 2016, 10), CreateChoice(context, "A00676767", "Matthew", "Robinson", 2016, 10), CreateChoice(context, "A00787878", "Rob", "Lee", 2016, 10), CreateChoice(context, "A00898989", "Ryan", "Jackson", 2016, 10), CreateChoice(context, "A00111222", "Ben", "Evans", 2016, 10), CreateChoice(context, "A00222333", "Michael", "Thompson", 2016, 10), CreateChoice(context, "A00333444", "Allison", "Miller", 2016, 10), CreateChoice(context, "A00444555", "Jane", "Willis", 2016, 10), CreateChoice(context, "A00555666", "Michelle", "Ray", 2016, 10) ); context.SaveChanges(); } } // Creates choice with randomized option choices private static Choice CreateChoice(DiplomaOptionsContext context, String studentId, String firstName, String lastName, int year, int term) { Random rng = new Random(); // Used for randomizing option choices Option[] options = context.Options.Where(o => o.IsActive == true).ToArray(); for (int i = options.Length - 1; i >= 0; i--) { int k = rng.Next(i + 1); var temp = options[i]; options[i] = options[k]; options[k] = temp; } return new Choice { StudentId = studentId, StudentFirstName = firstName, StudentLastName = lastName, Option1 = options[0], Option2 = options[1], Option3 = options[2], Option4 = options[3], YearTerm = context.YearTerms.Select(y => y) .Where(y => y.Year == year) .Where(y => y.Term == term).FirstOrDefault(), SelectionDate = DateTime.Now }; } } }
// 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 Internal.Cryptography; using System.Diagnostics; using Internal.NativeCrypto; using static Interop.BCrypt; using static Interop.NCrypt; using KeyBlobMagicNumber = Interop.BCrypt.KeyBlobMagicNumber; namespace System.Security.Cryptography { #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS internal static partial class DSAImplementation { #endif public sealed partial class DSACng : DSA { // For keysizes up to and including 1024 bits, CNG's blob format is BCRYPT_DSA_KEY_BLOB. // For keysizes exceeding 1024 bits, CNG's blob format is BCRYPT_DSA_KEY_BLOB_V2. private const int MaxV1KeySize = 1024; private const int Sha1HashOutputSize = 20; private const int Sha256HashOutputSize = 32; private const int Sha512HashOutputSize = 64; public override void ImportParameters(DSAParameters parameters) { if (parameters.P == null || parameters.Q == null || parameters.G == null || parameters.Y == null) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MissingFields); // J is not required and is not even used on CNG blobs. It should however be less than P (J == (P-1) / Q). This validation check // is just to maintain parity with DSACryptoServiceProvider, which also performs this check. if (parameters.J != null && parameters.J.Length >= parameters.P.Length) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPJ); bool hasPrivateKey = parameters.X != null; int keySizeInBytes = parameters.P.Length; int keySizeInBits = keySizeInBytes * 8; if (parameters.G.Length != keySizeInBytes || parameters.Y.Length != keySizeInBytes) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY); if (hasPrivateKey && parameters.X.Length != parameters.Q.Length) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX); byte[] blob; if (keySizeInBits <= MaxV1KeySize) { GenerateV1DsaBlob(out blob, parameters, keySizeInBytes, hasPrivateKey); } else { GenerateV2DsaBlob(out blob, parameters, keySizeInBytes, hasPrivateKey); } ImportKeyBlob(blob, hasPrivateKey); } public override void ImportPkcs8PrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { CngPkcs8.Pkcs8Response response = CngPkcs8.ImportPkcs8PrivateKey(source, out int localRead); ProcessPkcs8Response(response); bytesRead = localRead; } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey( passwordBytes, source, out int localRead); ProcessPkcs8Response(response); bytesRead = localRead; } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey( password, source, out int localRead); ProcessPkcs8Response(response); bytesRead = localRead; } private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) { // Wrong algorithm? if (response.GetAlgorithmGroup() != BCryptNative.AlgorithmName.DSA) { response.FreeKey(); throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey); } AcceptImport(response); } public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, pbeParameters); } public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException(nameof(pbeParameters)); } PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return ExportEncryptedPkcs8(password, pbeParameters.IterationCount); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, password, pbeParameters); } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); return CngPkcs8.TryExportEncryptedPkcs8PrivateKey( this, passwordBytes, pbeParameters, destination, out bytesWritten); } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return TryExportEncryptedPkcs8( password, pbeParameters.IterationCount, destination, out bytesWritten); } return CngPkcs8.TryExportEncryptedPkcs8PrivateKey( this, password, pbeParameters, destination, out bytesWritten); } private static void GenerateV1DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivate) { // We need to build a key blob structured as follows: // // BCRYPT_DSA_KEY_BLOB header // byte[cbKey] P // byte[cbKey] G // byte[cbKey] Y // -- Private only -- // byte[Sha1HashOutputSize] X unsafe { int blobSize = sizeof(BCRYPT_DSA_KEY_BLOB) + cbKey + cbKey + cbKey; if (includePrivate) { blobSize += Sha1HashOutputSize; } blob = new byte[blobSize]; fixed (byte* pDsaBlob = &blob[0]) { // Build the header BCRYPT_DSA_KEY_BLOB* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB*)pDsaBlob; pBcryptBlob->Magic = includePrivate ? KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC : KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC; pBcryptBlob->cbKey = cbKey; int offset = sizeof(KeyBlobMagicNumber) + sizeof(int); // skip Magic and cbKey if (parameters.Seed != null) { // The Seed length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message. if (parameters.Seed.Length != Sha1HashOutputSize) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey); Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter); Interop.BCrypt.Emit(blob, ref offset, parameters.Seed); } else { // If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject // anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng. Interop.BCrypt.EmitByte(blob, ref offset, 0xff, Sha1HashOutputSize + sizeof(int)); } // The Q length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message. if (parameters.Q.Length != Sha1HashOutputSize) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey); Interop.BCrypt.Emit(blob, ref offset, parameters.Q); Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB)}"); Interop.BCrypt.Emit(blob, ref offset, parameters.P); Interop.BCrypt.Emit(blob, ref offset, parameters.G); Interop.BCrypt.Emit(blob, ref offset, parameters.Y); if (includePrivate) { Interop.BCrypt.Emit(blob, ref offset, parameters.X); } Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}"); } } } private static void GenerateV2DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivateParameters) { // We need to build a key blob structured as follows: // BCRYPT_DSA_KEY_BLOB_V2 header // byte[cbSeedLength] Seed // byte[cbGroupSize] Q // byte[cbKey] P // byte[cbKey] G // byte[cbKey] Y // -- Private only -- // byte[cbGroupSize] X unsafe { int blobSize = sizeof(BCRYPT_DSA_KEY_BLOB_V2) + (parameters.Seed == null ? parameters.Q.Length : parameters.Seed.Length) + // Use Q size if Seed is not present parameters.Q.Length + parameters.P.Length + parameters.G.Length + parameters.Y.Length + (includePrivateParameters ? parameters.X.Length : 0); blob = new byte[blobSize]; fixed (byte* pDsaBlob = &blob[0]) { // Build the header BCRYPT_DSA_KEY_BLOB_V2* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB_V2*)pDsaBlob; pBcryptBlob->Magic = includePrivateParameters ? KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2 : KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2; pBcryptBlob->cbKey = cbKey; // For some reason, Windows bakes the hash algorithm into the key itself. Furthermore, it demands that the Q length match the // length of the named hash algorithm's output - otherwise, the Import fails. So we have to give it the hash algorithm that matches // the Q length - and if there is no matching hash algorithm, we throw up our hands and throw a PlatformNotSupported. // // Note that this has no bearing on the hash algorithm you pass to SignData(). The class library (not Windows) hashes that according // to the hash algorithm passed to SignData() and presents the hash result to NCryptSignHash(), truncating the hash to the Q length // if necessary (and as demanded by the NIST spec.) Windows will be no wiser and we'll get the result we want. HASHALGORITHM_ENUM hashAlgorithm; switch (parameters.Q.Length) { case Sha1HashOutputSize: hashAlgorithm = HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA1; break; case Sha256HashOutputSize: hashAlgorithm = HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA256; break; case Sha512HashOutputSize: hashAlgorithm = HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA512; break; default: throw new PlatformNotSupportedException(SR.Cryptography_InvalidDsaParameters_QRestriction_LargeKey); } pBcryptBlob->hashAlgorithm = hashAlgorithm; pBcryptBlob->standardVersion = DSAFIPSVERSION_ENUM.DSA_FIPS186_3; int offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2) - 4; //skip to Count[4] if (parameters.Seed != null) { Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter); Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}"); pBcryptBlob->cbSeedLength = parameters.Seed.Length; pBcryptBlob->cbGroupSize = parameters.Q.Length; Interop.BCrypt.Emit(blob, ref offset, parameters.Seed); } else { // If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject // anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng. Interop.BCrypt.EmitByte(blob, ref offset, 0xff, sizeof(int)); Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}"); int defaultSeedLength = parameters.Q.Length; pBcryptBlob->cbSeedLength = defaultSeedLength; pBcryptBlob->cbGroupSize = parameters.Q.Length; Interop.BCrypt.EmitByte(blob, ref offset, 0xff, defaultSeedLength); } Interop.BCrypt.Emit(blob, ref offset, parameters.Q); Interop.BCrypt.Emit(blob, ref offset, parameters.P); Interop.BCrypt.Emit(blob, ref offset, parameters.G); Interop.BCrypt.Emit(blob, ref offset, parameters.Y); if (includePrivateParameters) { Interop.BCrypt.Emit(blob, ref offset, parameters.X); } Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}"); } } } public override DSAParameters ExportParameters(bool includePrivateParameters) { byte[] dsaBlob = ExportKeyBlob(includePrivateParameters); KeyBlobMagicNumber magic = (KeyBlobMagicNumber)BitConverter.ToInt32(dsaBlob, 0); // Check the magic value in the key blob header. If the blob does not have the required magic, // then throw a CryptographicException. CheckMagicValueOfKey(magic, includePrivateParameters); unsafe { DSAParameters dsaParams = new DSAParameters(); fixed (byte* pDsaBlob = dsaBlob) { int offset; if (magic == KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC || magic == KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC) { if (dsaBlob.Length < sizeof(BCRYPT_DSA_KEY_BLOB)) throw ErrorCode.E_FAIL.ToCryptographicException(); BCRYPT_DSA_KEY_BLOB* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB*)pDsaBlob; // We now have a buffer laid out as follows: // BCRYPT_DSA_KEY_BLOB header // byte[cbKey] P // byte[cbKey] G // byte[cbKey] Y // -- Private only -- // byte[Sha1HashOutputSize] X offset = sizeof(KeyBlobMagicNumber) + sizeof(int); // skip Magic and cbKey // Read out a (V1) BCRYPT_DSA_KEY_BLOB structure. dsaParams.Counter = FromBigEndian(Interop.BCrypt.Consume(dsaBlob, ref offset, 4)); dsaParams.Seed = Interop.BCrypt.Consume(dsaBlob, ref offset, Sha1HashOutputSize); dsaParams.Q = Interop.BCrypt.Consume(dsaBlob, ref offset, Sha1HashOutputSize); Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB)}"); dsaParams.P = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); dsaParams.G = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); dsaParams.Y = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); if (includePrivateParameters) { dsaParams.X = Interop.BCrypt.Consume(dsaBlob, ref offset, Sha1HashOutputSize); } } else { Debug.Assert(magic == KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2 || magic == KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2); if (dsaBlob.Length < sizeof(BCRYPT_DSA_KEY_BLOB_V2)) throw ErrorCode.E_FAIL.ToCryptographicException(); BCRYPT_DSA_KEY_BLOB_V2* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB_V2*)pDsaBlob; // We now have a buffer laid out as follows: // BCRYPT_DSA_KEY_BLOB_V2 header // byte[cbSeedLength] Seed // byte[cbGroupSize] Q // byte[cbKey] P // byte[cbKey] G // byte[cbKey] Y // -- Private only -- // byte[cbGroupSize] X offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2) - 4; //skip to Count[4] // Read out a BCRYPT_DSA_KEY_BLOB_V2 structure. dsaParams.Counter = FromBigEndian(Interop.BCrypt.Consume(dsaBlob, ref offset, 4)); Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}"); dsaParams.Seed = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbSeedLength); dsaParams.Q = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbGroupSize); dsaParams.P = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); dsaParams.G = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); dsaParams.Y = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); if (includePrivateParameters) { dsaParams.X = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbGroupSize); } } // If no counter/seed information is present, normalize Counter and Seed to 0/null to maintain parity with the CAPI version of DSA. if (dsaParams.Counter == -1) { dsaParams.Counter = 0; dsaParams.Seed = null; } Debug.Assert(offset == dsaBlob.Length, $"Expected offset = dsaBlob.Length, got {offset} != {dsaBlob.Length}"); return dsaParams; } } } private static int FromBigEndian(byte[] b) { return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]; } /// <summary> /// This function checks the magic value in the key blob header /// </summary> /// <param name="includePrivateParameters">Private blob if true else public key blob</param> private static void CheckMagicValueOfKey(KeyBlobMagicNumber magic, bool includePrivateParameters) { if (includePrivateParameters) { if (magic != KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC && magic != KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2) throw new CryptographicException(SR.Cryptography_NotValidPrivateKey); } else { if (magic != KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC && magic != KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2) throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey); } } } #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS } #endif }
using System; using System.Collections.Generic; using System.Linq; using ModestTree; using TypeExtensions = ModestTree.TypeExtensions; namespace Zenject { public abstract class ProviderBindingFinalizer : IBindingFinalizer { public ProviderBindingFinalizer(BindInfo bindInfo) { BindInfo = bindInfo; } public BindingInheritanceMethods BindingInheritanceMethod { get { return BindInfo.BindingInheritanceMethod; } } protected BindInfo BindInfo { get; private set; } protected ScopeTypes GetScope() { if (BindInfo.Scope == ScopeTypes.Unset) { // If condition is set then it's probably fine to allow the default of transient Assert.That(!BindInfo.RequireExplicitScope || BindInfo.Condition != null, "Scope must be set for the previous binding! Please either specify AsTransient, AsCached, or AsSingle. Last binding: Contract: {0}, Identifier: {1} {2}", BindInfo.ContractTypes.Select(x => x.ToString()).Join(", "), BindInfo.Identifier, BindInfo.ContextInfo != null ? "Context: '{0}'".Fmt(BindInfo.ContextInfo) : ""); return ScopeTypes.Transient; } return BindInfo.Scope; } public void FinalizeBinding(DiContainer container) { if (BindInfo.ContractTypes.Count == 0) { // We could assert her instead but it is nice when used with things like // BindInterfaces() (and there aren't any interfaces) to allow // interfaces to be added later return; } try { OnFinalizeBinding(container); } catch (Exception e) { throw Assert.CreateException( e, "Error while finalizing previous binding! Contract: {0}, Identifier: {1} {2}", BindInfo.ContractTypes.Select(x => x.ToString()).Join(", "), BindInfo.Identifier, BindInfo.ContextInfo != null ? "Context: '{0}'".Fmt(BindInfo.ContextInfo) : ""); } } protected abstract void OnFinalizeBinding(DiContainer container); protected void RegisterProvider<TContract>( DiContainer container, IProvider provider) { RegisterProvider(container, typeof(TContract), provider); } protected void RegisterProvider( DiContainer container, Type contractType, IProvider provider) { if (BindInfo.OnlyBindIfNotBound && container.HasBindingId(contractType, BindInfo.Identifier)) { return; } container.RegisterProvider( new BindingId(contractType, BindInfo.Identifier), BindInfo.Condition, provider, BindInfo.NonLazy); if (contractType.IsValueType() && !(contractType.IsGenericType() && contractType.GetGenericTypeDefinition() == typeof(Nullable<>))) { var nullableType = typeof(Nullable<>).MakeGenericType(contractType); // Also bind to nullable primitives // this is useful so that we can have optional primitive dependencies container.RegisterProvider( new BindingId(nullableType, BindInfo.Identifier), BindInfo.Condition, provider, BindInfo.NonLazy); } } protected void RegisterProviderPerContract( DiContainer container, Func<DiContainer, Type, IProvider> providerFunc) { foreach (var contractType in BindInfo.ContractTypes) { var provider = providerFunc(container, contractType); if (BindInfo.MarkAsUniqueSingleton) { container.SingletonMarkRegistry.MarkSingleton(contractType); } else if (BindInfo.MarkAsCreationBinding) { container.SingletonMarkRegistry.MarkNonSingleton(contractType); } RegisterProvider(container, contractType, provider); } } protected void RegisterProviderForAllContracts( DiContainer container, IProvider provider) { foreach (var contractType in BindInfo.ContractTypes) { if (BindInfo.MarkAsUniqueSingleton) { container.SingletonMarkRegistry.MarkSingleton(contractType); } else if (BindInfo.MarkAsCreationBinding) { container.SingletonMarkRegistry.MarkNonSingleton(contractType); } RegisterProvider(container, contractType, provider); } } protected void RegisterProvidersPerContractAndConcreteType( DiContainer container, List<Type> concreteTypes, Func<Type, Type, IProvider> providerFunc) { Assert.That(!BindInfo.ContractTypes.IsEmpty()); Assert.That(!concreteTypes.IsEmpty()); foreach (var contractType in BindInfo.ContractTypes) { foreach (var concreteType in concreteTypes) { if (ValidateBindTypes(concreteType, contractType)) { RegisterProvider(container, contractType, providerFunc(contractType, concreteType)); } } } } // Returns true if the bind should continue, false to skip bool ValidateBindTypes(Type concreteType, Type contractType) { bool isConcreteOpenGenericType = concreteType.IsOpenGenericType(); bool isContractOpenGenericType = contractType.IsOpenGenericType(); if (isConcreteOpenGenericType != isContractOpenGenericType) { return false; } #if !(UNITY_WSA && ENABLE_DOTNET) // TODO: Is it possible to do this on WSA? if (isContractOpenGenericType) { Assert.That(isConcreteOpenGenericType); if (TypeExtensions.IsAssignableToGenericType(concreteType, contractType)) { return true; } } else if (concreteType.DerivesFromOrEqual(contractType)) { return true; } #else if (concreteType.DerivesFromOrEqual(contractType)) { return true; } #endif if (BindInfo.InvalidBindResponse == InvalidBindResponses.Assert) { throw Assert.CreateException( "Expected type '{0}' to derive from or be equal to '{1}'", concreteType, contractType); } Assert.IsEqual(BindInfo.InvalidBindResponse, InvalidBindResponses.Skip); return false; } // Note that if multiple contract types are provided per concrete type, // it will re-use the same provider for each contract type // (each concrete type will have its own provider though) protected void RegisterProvidersForAllContractsPerConcreteType( DiContainer container, List<Type> concreteTypes, Func<DiContainer, Type, IProvider> providerFunc) { Assert.That(!BindInfo.ContractTypes.IsEmpty()); Assert.That(!concreteTypes.IsEmpty()); var providerMap = DictionaryPool<Type, IProvider>.Instance.Spawn(); try { foreach (var concreteType in concreteTypes) { var provider = providerFunc(container, concreteType); providerMap[concreteType] = provider; if (BindInfo.MarkAsUniqueSingleton) { container.SingletonMarkRegistry.MarkSingleton(concreteType); } else if (BindInfo.MarkAsCreationBinding) { container.SingletonMarkRegistry.MarkNonSingleton(concreteType); } } foreach (var contractType in BindInfo.ContractTypes) { foreach (var concreteType in concreteTypes) { if (ValidateBindTypes(concreteType, contractType)) { RegisterProvider(container, contractType, providerMap[concreteType]); } } } } finally { DictionaryPool<Type, IProvider>.Instance.Despawn(providerMap); } } } }
// 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.Xml; using System.Collections; using System.Diagnostics; namespace System.Data { // This is an internal helper class used during Xml load to DataSet/DataDocument. // XmlToDatasetMap class provides functionality for binding elemants/attributes // to DataTable / DataColumn internal sealed class XmlToDatasetMap { private sealed class XmlNodeIdentety { public string LocalName; public string NamespaceURI; public XmlNodeIdentety(string localName, string namespaceURI) { LocalName = localName; NamespaceURI = namespaceURI; } public override int GetHashCode() { return LocalName.GetHashCode(); } public override bool Equals(object obj) { XmlNodeIdentety id = (XmlNodeIdentety)obj; return ( (string.Equals(LocalName, id.LocalName, StringComparison.OrdinalIgnoreCase)) && (string.Equals(NamespaceURI, id.NamespaceURI, StringComparison.OrdinalIgnoreCase)) ); } } // This class exist to avoid alocatin of XmlNodeIdentety to every access to the hash table. // Unfortunetely XmlNode doesn't export single identety object. internal sealed class XmlNodeIdHashtable : Hashtable { private XmlNodeIdentety _id = new XmlNodeIdentety(string.Empty, string.Empty); public XmlNodeIdHashtable(int capacity) : base(capacity) { } public object this[XmlNode node] { get { _id.LocalName = node.LocalName; _id.NamespaceURI = node.NamespaceURI; return this[_id]; } } public object this[XmlReader dataReader] { get { _id.LocalName = dataReader.LocalName; _id.NamespaceURI = dataReader.NamespaceURI; return this[_id]; } } public object this[DataTable table] { get { _id.LocalName = table.EncodedTableName; _id.NamespaceURI = table.Namespace; return this[_id]; } } public object this[string name] { get { _id.LocalName = name; _id.NamespaceURI = string.Empty; return this[_id]; } } } private sealed class TableSchemaInfo { public DataTable TableSchema; public XmlNodeIdHashtable ColumnsSchemaMap; public TableSchemaInfo(DataTable tableSchema) { TableSchema = tableSchema; ColumnsSchemaMap = new XmlNodeIdHashtable(tableSchema.Columns.Count); } } private XmlNodeIdHashtable _tableSchemaMap; // Holds all the tables information private TableSchemaInfo _lastTableSchemaInfo = null; // Used to infer schema public XmlToDatasetMap(DataSet dataSet, XmlNameTable nameTable) { Debug.Assert(dataSet != null, "DataSet can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(dataSet, nameTable); } // Used to read data with known schema public XmlToDatasetMap(XmlNameTable nameTable, DataSet dataSet) { Debug.Assert(dataSet != null, "DataSet can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(nameTable, dataSet); } // Used to infer schema public XmlToDatasetMap(DataTable dataTable, XmlNameTable nameTable) { Debug.Assert(dataTable != null, "DataTable can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(dataTable, nameTable); } // Used to read data with known schema public XmlToDatasetMap(XmlNameTable nameTable, DataTable dataTable) { Debug.Assert(dataTable != null, "DataTable can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(nameTable, dataTable); } internal static bool IsMappedColumn(DataColumn c) { return (c.ColumnMapping != MappingType.Hidden); } // Used to infere schema private TableSchemaInfo AddTableSchema(DataTable table, XmlNameTable nameTable) { // SDUB: Because in our case reader already read the document all names that we can meet in the // document already has an entry in NameTable. // If in future we will build identity map before reading XML we can replace Get() to Add() // Sdub: GetIdentity is called from two places: BuildIdentityMap() and LoadRows() // First case deals with decoded names; Second one with encoded names. // We decided encoded names in first case (instead of decoding them in second) // because it save us time in LoadRows(). We have, as usual, more data them schemas string tableLocalName = nameTable.Get(table.EncodedTableName); string tableNamespace = nameTable.Get(table.Namespace); if (tableLocalName == null) { // because name of this table isn't present in XML we don't need mapping for it. // Less mapping faster we work. return null; } TableSchemaInfo tableSchemaInfo = new TableSchemaInfo(table); _tableSchemaMap[new XmlNodeIdentety(tableLocalName, tableNamespace)] = tableSchemaInfo; return tableSchemaInfo; } private TableSchemaInfo AddTableSchema(XmlNameTable nameTable, DataTable table) { // Enzol:This is the opposite of the previous function: // we populate the nametable so that the hash comparison can happen as // object comparison instead of strings. // Sdub: GetIdentity is called from two places: BuildIdentityMap() and LoadRows() // First case deals with decoded names; Second one with encoded names. // We decided encoded names in first case (instead of decoding them in second) // because it save us time in LoadRows(). We have, as usual, more data them schemas string _tableLocalName = table.EncodedTableName; // Table name string tableLocalName = nameTable.Get(_tableLocalName); // Look it up in nametable if (tableLocalName == null) { // If not found tableLocalName = nameTable.Add(_tableLocalName); // Add it } table._encodedTableName = tableLocalName; // And set it back string tableNamespace = nameTable.Get(table.Namespace); // Look ip table namespace if (tableNamespace == null) { // If not found tableNamespace = nameTable.Add(table.Namespace); // Add it } else { if (table._tableNamespace != null) // Update table namespace table._tableNamespace = tableNamespace; } TableSchemaInfo tableSchemaInfo = new TableSchemaInfo(table); // Create new table schema info _tableSchemaMap[new XmlNodeIdentety(tableLocalName, tableNamespace)] = tableSchemaInfo; // And add it to the hashtable return tableSchemaInfo; // Return it as we have to populate // Column schema map and Child table // schema map in it } private bool AddColumnSchema(DataColumn col, XmlNameTable nameTable, XmlNodeIdHashtable columns) { string columnLocalName = nameTable.Get(col.EncodedColumnName); string columnNamespace = nameTable.Get(col.Namespace); if (columnLocalName == null) { return false; } XmlNodeIdentety idColumn = new XmlNodeIdentety(columnLocalName, columnNamespace); columns[idColumn] = col; if (col.ColumnName.StartsWith("xml", StringComparison.OrdinalIgnoreCase)) { HandleSpecialColumn(col, nameTable, columns); } return true; } private bool AddColumnSchema(XmlNameTable nameTable, DataColumn col, XmlNodeIdHashtable columns) { string _columnLocalName = XmlConvert.EncodeLocalName(col.ColumnName); string columnLocalName = nameTable.Get(_columnLocalName); // Look it up in a name table if (columnLocalName == null) { // Not found? columnLocalName = nameTable.Add(_columnLocalName); // Add it } col._encodedColumnName = columnLocalName; // And set it back string columnNamespace = nameTable.Get(col.Namespace); // Get column namespace from nametable if (columnNamespace == null) { // Not found ? columnNamespace = nameTable.Add(col.Namespace); // Add it } else { if (col._columnUri != null) // Update namespace col._columnUri = columnNamespace; } // Create XmlNodeIdentety // for this column XmlNodeIdentety idColumn = new XmlNodeIdentety(columnLocalName, columnNamespace); columns[idColumn] = col; // And add it to hashtable if (col.ColumnName.StartsWith("xml", StringComparison.OrdinalIgnoreCase)) { HandleSpecialColumn(col, nameTable, columns); } return true; } private void BuildIdentityMap(DataSet dataSet, XmlNameTable nameTable) { _tableSchemaMap = new XmlNodeIdHashtable(dataSet.Tables.Count); foreach (DataTable t in dataSet.Tables) { TableSchemaInfo tableSchemaInfo = AddTableSchema(t, nameTable); if (tableSchemaInfo != null) { foreach (DataColumn c in t.Columns) { // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { AddColumnSchema(c, nameTable, tableSchemaInfo.ColumnsSchemaMap); } } } } } // This one is used while reading data with preloaded schema private void BuildIdentityMap(XmlNameTable nameTable, DataSet dataSet) { _tableSchemaMap = new XmlNodeIdHashtable(dataSet.Tables.Count); // This hash table contains // tables schemas as TableSchemaInfo objects // These objects holds reference to the table. // Hash tables with columns schema maps // and child tables schema maps string dsNamespace = nameTable.Get(dataSet.Namespace); // Attept to look up DataSet namespace // in the name table if (dsNamespace == null) { // Found ? dsNamespace = nameTable.Add(dataSet.Namespace); // Nope. Add it } dataSet._namespaceURI = dsNamespace; // Set a DataSet namespace URI foreach (DataTable t in dataSet.Tables) { // For each table TableSchemaInfo tableSchemaInfo = AddTableSchema(nameTable, t); // Add table schema info to hash table if (tableSchemaInfo != null) { foreach (DataColumn c in t.Columns) { // Add column schema map // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { // If mapped column AddColumnSchema(nameTable, c, tableSchemaInfo.ColumnsSchemaMap); } // Add it to the map } // Add child nested tables to the schema foreach (DataRelation r in t.ChildRelations) { // Do we have a child tables ? if (r.Nested) { // Is it nested? // don't include non nested tables // Handle namespaces and names as usuall string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName); string tableLocalName = nameTable.Get(_tableLocalName); if (tableLocalName == null) { tableLocalName = nameTable.Add(_tableLocalName); } string tableNamespace = nameTable.Get(r.ChildTable.Namespace); if (tableNamespace == null) { tableNamespace = nameTable.Add(r.ChildTable.Namespace); } XmlNodeIdentety idTable = new XmlNodeIdentety(tableLocalName, tableNamespace); tableSchemaInfo.ColumnsSchemaMap[idTable] = r.ChildTable; } } } } } // Used for inference private void BuildIdentityMap(DataTable dataTable, XmlNameTable nameTable) { _tableSchemaMap = new XmlNodeIdHashtable(1); TableSchemaInfo tableSchemaInfo = AddTableSchema(dataTable, nameTable); if (tableSchemaInfo != null) { foreach (DataColumn c in dataTable.Columns) { // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { AddColumnSchema(c, nameTable, tableSchemaInfo.ColumnsSchemaMap); } } } } // This one is used while reading data with preloaded schema private void BuildIdentityMap(XmlNameTable nameTable, DataTable dataTable) { ArrayList tableList = GetSelfAndDescendants(dataTable); // Get list of tables we're loading // This includes our table and // related tables tree _tableSchemaMap = new XmlNodeIdHashtable(tableList.Count); // Create hash table to hold all // tables to load. foreach (DataTable t in tableList) { // For each table TableSchemaInfo tableSchemaInfo = AddTableSchema(nameTable, t); // Create schema info if (tableSchemaInfo != null) { foreach (DataColumn c in t.Columns) { // Add column information // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { AddColumnSchema(nameTable, c, tableSchemaInfo.ColumnsSchemaMap); } } foreach (DataRelation r in t.ChildRelations) { // Add nested tables information if (r.Nested) { // Is it nested? // don't include non nested tables // Handle namespaces and names as usuall string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName); string tableLocalName = nameTable.Get(_tableLocalName); if (tableLocalName == null) { tableLocalName = nameTable.Add(_tableLocalName); } string tableNamespace = nameTable.Get(r.ChildTable.Namespace); if (tableNamespace == null) { tableNamespace = nameTable.Add(r.ChildTable.Namespace); } XmlNodeIdentety idTable = new XmlNodeIdentety(tableLocalName, tableNamespace); tableSchemaInfo.ColumnsSchemaMap[idTable] = r.ChildTable; } } } } } private ArrayList GetSelfAndDescendants(DataTable dt) { // breadth-first ArrayList tableList = new ArrayList(); tableList.Add(dt); int nCounter = 0; while (nCounter < tableList.Count) { foreach (DataRelation childRelations in ((DataTable)tableList[nCounter]).ChildRelations) { if (!tableList.Contains(childRelations.ChildTable)) tableList.Add(childRelations.ChildTable); } nCounter++; } return tableList; } // Used to infer schema and top most node public object GetColumnSchema(XmlNode node, bool fIgnoreNamespace) { Debug.Assert(node != null, "Argument validation"); TableSchemaInfo tableSchemaInfo = null; XmlNode nodeRegion = (node.NodeType == XmlNodeType.Attribute) ? ((XmlAttribute)node).OwnerElement : node.ParentNode; do { if (nodeRegion == null || nodeRegion.NodeType != XmlNodeType.Element) { return null; } tableSchemaInfo = (TableSchemaInfo)(fIgnoreNamespace ? _tableSchemaMap[nodeRegion.LocalName] : _tableSchemaMap[nodeRegion]); nodeRegion = nodeRegion.ParentNode; } while (tableSchemaInfo == null); if (fIgnoreNamespace) return tableSchemaInfo.ColumnsSchemaMap[node.LocalName]; else return tableSchemaInfo.ColumnsSchemaMap[node]; } public object GetColumnSchema(DataTable table, XmlReader dataReader, bool fIgnoreNamespace) { if ((_lastTableSchemaInfo == null) || (_lastTableSchemaInfo.TableSchema != table)) { _lastTableSchemaInfo = (TableSchemaInfo)(fIgnoreNamespace ? _tableSchemaMap[table.EncodedTableName] : _tableSchemaMap[table]); } if (fIgnoreNamespace) return _lastTableSchemaInfo.ColumnsSchemaMap[dataReader.LocalName]; return _lastTableSchemaInfo.ColumnsSchemaMap[dataReader]; } // Used to infer schema public object GetSchemaForNode(XmlNode node, bool fIgnoreNamespace) { TableSchemaInfo tableSchemaInfo = null; if (node.NodeType == XmlNodeType.Element) { // If element tableSchemaInfo = (TableSchemaInfo)(fIgnoreNamespace ? _tableSchemaMap[node.LocalName] : _tableSchemaMap[node]); } // Look up table schema info for it if (tableSchemaInfo != null) { // Got info ? return tableSchemaInfo.TableSchema; // Yes, Return table } return GetColumnSchema(node, fIgnoreNamespace); // Attempt to locate column } public DataTable GetTableForNode(XmlReader node, bool fIgnoreNamespace) { TableSchemaInfo tableSchemaInfo = (TableSchemaInfo)(fIgnoreNamespace ? _tableSchemaMap[node.LocalName] : _tableSchemaMap[node]); if (tableSchemaInfo != null) { _lastTableSchemaInfo = tableSchemaInfo; return _lastTableSchemaInfo.TableSchema; } return null; } private void HandleSpecialColumn(DataColumn col, XmlNameTable nameTable, XmlNodeIdHashtable columns) { // if column name starts with xml, we encode it manualy and add it for look up Debug.Assert(col.ColumnName.StartsWith("xml", StringComparison.OrdinalIgnoreCase), "column name should start with xml"); string tempColumnName; if ('x' == col.ColumnName[0]) { tempColumnName = "_x0078_"; // lower case xml... -> _x0078_ml... } else { tempColumnName = "_x0058_"; // upper case Xml... -> _x0058_ml... } tempColumnName = string.Concat(tempColumnName, col.ColumnName.AsSpan(1)); if (nameTable.Get(tempColumnName) == null) { nameTable.Add(tempColumnName); } string columnNamespace = nameTable.Get(col.Namespace); XmlNodeIdentety idColumn = new XmlNodeIdentety(tempColumnName, columnNamespace); columns[idColumn] = col; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Desktop.Analyzers.UnitTests { public class TypesShouldNotExtendCertainBaseTypesTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new TypesShouldNotExtendCertainBaseTypesAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new TypesShouldNotExtendCertainBaseTypesAnalyzer(); } [Fact] public void TypesShouldNotExtendCertainBaseTypes_CSharp_NoDiagnostic() { VerifyCSharp(@" using System; class C : Attribute { } "); } [Fact] public void TypesShouldNotExtendCertainBaseTypes_CSharp_ApplicationException() { var source = @" using System; class C1 : ApplicationException { } "; DiagnosticResult[] expected = new[] { GetCSharpApplicationExceptionResultAt(4, 7, "C1", "System.ApplicationException") }; VerifyCSharp(source, expected); } [Fact] public void TypesShouldNotExtendCertainBaseTypes_CSharp_XmlDocument() { var source = @" using System.Xml; class C1 : XmlDocument { } "; DiagnosticResult[] expected = new[] { GetCSharpXmlDocumentResultAt(4, 7, "C1", "System.Xml.XmlDocument") }; VerifyCSharp(source, expected); } [Fact] public void TypesShouldNotExtendCertainBaseTypes_CSharp_Collection() { var source = @" using System.Collections; class C1 : CollectionBase { } class C2 : DictionaryBase { } class C3 : Queue { } class C4 : ReadOnlyCollectionBase { } class C5 : SortedList { } class C6 : Stack { }"; DiagnosticResult[] expected = new[] { GetCSharpCollectionBaseResultAt(4, 7, "C1", "System.Collections.CollectionBase"), GetCSharpDictionaryBaseResultAt(8, 7, "C2", "System.Collections.DictionaryBase"), GetCSharpQueueResultAt(12, 7, "C3", "System.Collections.Queue"), GetCSharpReadOnlyCollectionResultAt(16, 7, "C4", "System.Collections.ReadOnlyCollectionBase"), GetCSharpSortedListResultAt(20, 7, "C5", "System.Collections.SortedList"), GetCSharpStackResultAt(24, 7, "C6", "System.Collections.Stack") }; VerifyCSharp(source, expected); } [Fact] public void TypesShouldNotExtendCertainBaseTypes_Basic_NoDiagnostic() { VerifyBasic(@" Imports System Public Class Class2 Inherits Attribute End Class "); } [Fact] public void TypesShouldNotExtendCertainBaseTypes_Basic_ApplicationException() { var source = @" Imports System Public Class C1 Inherits ApplicationException End Class "; DiagnosticResult[] expected = new[] { GetBasicApplicationExceptionResultAt(4, 14, "C1", "System.ApplicationException") }; VerifyBasic(source, expected); } [Fact] public void TypesShouldNotExtendCertainBaseTypes_Basic_XmlDocument() { var source = @" Imports System.Xml Public Class C1 Inherits XmlDocument End Class "; DiagnosticResult[] expected = new[] { GetBasicXmlDocumentResultAt(4, 14, "C1", "System.Xml.XmlDocument") }; VerifyBasic(source, expected); } [Fact] public void TypesShouldNotExtendCertainBaseTypes_Basic_Collection() { var source = @" Imports System.Collections Public Class C1 Inherits CollectionBase End Class Public Class C2 Inherits DictionaryBase End Class Public Class C3 Inherits Queue End Class Public Class C4 Inherits ReadOnlyCollectionBase End Class Public Class C5 Inherits SortedList End Class Public Class C6 Inherits Stack End Class "; DiagnosticResult[] expected = new[] { GetBasicCollectionBaseResultAt(4, 14, "C1", "System.Collections.CollectionBase"), GetBasicDictionaryBaseResultAt(9, 14, "C2", "System.Collections.DictionaryBase"), GetBasicQueueResultAt(14, 14, "C3", "System.Collections.Queue"), GetBasicReadOnlyCollectionBaseResultAt(19, 14, "C4", "System.Collections.ReadOnlyCollectionBase"), GetBasicSortedListResultAt(24, 14, "C5", "System.Collections.SortedList"), GetBasicStackResultAt(29, 14, "C6", "System.Collections.Stack") }; VerifyBasic(source, expected); } private static DiagnosticResult GetCSharpCollectionBaseResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsCollectionBase, declaredTypeName, badBaseTypeName); return GetCSharpResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicCollectionBaseResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsCollectionBase, declaredTypeName, badBaseTypeName); return GetBasicResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetCSharpDictionaryBaseResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsDictionaryBase, declaredTypeName, badBaseTypeName); return GetCSharpResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicDictionaryBaseResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsDictionaryBase, declaredTypeName, badBaseTypeName); return GetBasicResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetCSharpQueueResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsQueue, declaredTypeName, badBaseTypeName); return GetCSharpResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicQueueResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsQueue, declaredTypeName, badBaseTypeName); return GetBasicResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetCSharpReadOnlyCollectionResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsReadOnlyCollectionBase, declaredTypeName, badBaseTypeName); return GetCSharpResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicReadOnlyCollectionBaseResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsReadOnlyCollectionBase, declaredTypeName, badBaseTypeName); return GetBasicResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetCSharpSortedListResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsSortedList, declaredTypeName, badBaseTypeName); return GetCSharpResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicSortedListResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsSortedList, declaredTypeName, badBaseTypeName); return GetBasicResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetCSharpStackResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsStack, declaredTypeName, badBaseTypeName); return GetCSharpResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicStackResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsStack, declaredTypeName, badBaseTypeName); return GetBasicResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetCSharpApplicationExceptionResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemApplicationException, declaredTypeName, badBaseTypeName); return GetCSharpResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicApplicationExceptionResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemApplicationException, declaredTypeName, badBaseTypeName); return GetBasicResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetCSharpXmlDocumentResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemXmlXmlDocument, declaredTypeName, badBaseTypeName); return GetCSharpResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicXmlDocumentResultAt(int line, int column, string declaredTypeName, string badBaseTypeName) { string message = string.Format(DesktopAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemXmlXmlDocument, declaredTypeName, badBaseTypeName); return GetBasicResultAt(line, column, TypesShouldNotExtendCertainBaseTypesAnalyzer.RuleId, message); } } }
// 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 Xunit; namespace System.SpanTests { public static partial class ReadOnlySpanTests { public static readonly TheoryData<(uint[] Array, uint Value, int ExpectedIndex)> s_casesUInt = new TheoryData<(uint[] Array, uint Value, int ExpectedIndex)> { (new uint[] { }, 0u, -1), (new uint[] { 1u }, 0u, -1), (new uint[] { 1u }, 1u, 0), (new uint[] { 1u }, 2u, -2), (new uint[] { 1u, 2u, 4u, 5u }, 0u, -1), (new uint[] { 1u, 2u, 4u, 5u }, 1u, 0), (new uint[] { 1u, 2u, 4u, 5u }, 2u, 1), (new uint[] { 1u, 2u, 4u, 5u }, 3u, -3), (new uint[] { 1u, 2u, 4u, 5u }, 4u, 2), (new uint[] { 1u, 2u, 4u, 5u }, 5u, 3), (new uint[] { 1u, 2u, 4u, 5u }, 6u, -5), (new uint[] { 1u, 2u, 2u, 2u }, 2u, 1), }; public static readonly TheoryData<(double[] Array, double Value, int ExpectedIndex)> s_casesDouble = new TheoryData<(double[] Array, double Value, int ExpectedIndex)> { (new double[] { }, 0.0, -1), (new double[] { 1.0 }, 0.0, -1), (new double[] { 1.0 }, 1.0, 0), (new double[] { 1.0 }, 2.0, -2), (new double[] { 1.0, 2.0, 4.0, 5.0 }, 0.0, -1), (new double[] { 1.0, 2.0, 4.0, 5.0 }, 1.0, 0), (new double[] { 1.0, 2.0, 4.0, 5.0 }, 2.0, 1), (new double[] { 1.0, 2.0, 4.0, 5.0 }, 3.0, -3), (new double[] { 1.0, 2.0, 4.0, 5.0 }, 4.0, 2), (new double[] { 1.0, 2.0, 4.0, 5.0 }, 5.0, 3), (new double[] { 1.0, 2.0, 4.0, 5.0 }, 6.0, -5), (new double[] { 2.0, 2.0, 2.0, 1.0 }, 2.0, 1), }; public static readonly TheoryData<(string[] Array, string Value, int ExpectedIndex)> s_casesString = new TheoryData<(string[] Array, string Value, int ExpectedIndex)> { (new string[] { }, "a", -1), (new string[] { "b" }, "a", -1), (new string[] { "b" }, "b", 0), (new string[] { "b" }, "c", -2), (new string[] { "b", "c", "e", "f" }, "a", -1), (new string[] { "b", "c", "e", "f" }, "b", 0), (new string[] { "b", "c", "e", "f" }, "c", 1), (new string[] { "b", "c", "e", "f" }, "d", -3), (new string[] { "b", "c", "e", "f" }, "e", 2), (new string[] { "b", "c", "e", "f" }, "f", 3), (new string[] { "b", "c", "e", "f" }, "g", -5), (new string[] { "b", "b", "c", "c" }, "c", 2), }; [Theory, MemberData(nameof(s_casesUInt))] public static void BinarySearch_UInt( (uint[] Array, uint Value, int ExpectedIndex) testCase) { TestOverloads(testCase.Array, testCase.Value, testCase.ExpectedIndex); } [Theory, MemberData(nameof(s_casesDouble))] public static void BinarySearch_Double( (double[] Array, double Value, int ExpectedIndex) testCase) { TestOverloads(testCase.Array, testCase.Value, testCase.ExpectedIndex); } [Theory, MemberData(nameof(s_casesString))] public static void BinarySearch_String( (string[] Array, string Value, int ExpectedIndex) testCase) { TestOverloads(testCase.Array, testCase.Value, testCase.ExpectedIndex); } [Fact] public static void BinarySearch_Slice() { var array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var span = new ReadOnlySpan<int>(array, 1, array.Length - 2); Assert.Equal(-1, span.BinarySearch(1)); Assert.Equal(0, span.BinarySearch(2)); Assert.Equal(3, span.BinarySearch(5)); Assert.Equal(6, span.BinarySearch(8)); Assert.Equal(-8, span.BinarySearch(9)); } [Fact] public static void BinarySearch_NullComparableThrows() { Assert.Throws<ArgumentNullException>(() => new Span<int>(new int[] { }).BinarySearch<int>(null)); Assert.Throws<ArgumentNullException>(() => new ReadOnlySpan<int>(new int[] { }).BinarySearch<int>(null)); Assert.Throws<ArgumentNullException>(() => new Span<int>(new int[] { }).BinarySearch<int, IComparable<int>>(null)); Assert.Throws<ArgumentNullException>(() => new ReadOnlySpan<int>(new int[] { }).BinarySearch<int, IComparable<int>>(null)); } [Fact] public static void BinarySearch_NullComparerThrows() { Assert.Throws<ArgumentNullException>(() => new Span<int>(new int[] { }).BinarySearch<int, IComparer<int>>(0, null)); Assert.Throws<ArgumentNullException>(() => new ReadOnlySpan<int>(new int[] { }).BinarySearch<int, IComparer<int>>(0, null)); } // NOTE: BinarySearch_MaxLength_NoOverflow test is constrained to run on Windows and MacOSX because it causes // problems on Linux due to the way deferred memory allocation works. On Linux, the allocation can // succeed even if there is not enough memory but then the test may get killed by the OOM killer at the // time the memory is accessed which triggers the full memory allocation. [Fact] [OuterLoop] [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] public static unsafe void BinarySearch_MaxLength_NoOverflow() { if (sizeof(IntPtr) == sizeof(long)) { // Allocate maximum length span native memory var length = int.MaxValue; if (!AllocationHelper.TryAllocNative(new IntPtr(length), out IntPtr memory)) { Console.WriteLine($"Span.BinarySearch test {nameof(BinarySearch_MaxLength_NoOverflow)} skipped (could not alloc memory)."); return; } try { var span = new Span<byte>(memory.ToPointer(), length); span.Fill(0); // Fill last two elements span[int.MaxValue - 2] = 2; span[int.MaxValue - 1] = 3; Assert.Equal(int.MaxValue / 2, span.BinarySearch((byte)0)); // Search at end and assert no overflow Assert.Equal(~(int.MaxValue - 2), span.BinarySearch((byte)1)); Assert.Equal(int.MaxValue - 2, span.BinarySearch((byte)2)); Assert.Equal(int.MaxValue - 1, span.BinarySearch((byte)3)); Assert.Equal(int.MinValue, span.BinarySearch((byte)4)); } finally { AllocationHelper.ReleaseNative(ref memory); } } } private static void TestOverloads<T, TComparable>( T[] array, TComparable value, int expectedIndex) where TComparable : IComparable<T>, T { TestSpan(array, value, expectedIndex); TestReadOnlySpan(array, value, expectedIndex); TestIComparableSpan(array, value, expectedIndex); TestIComparableReadOnlySpan(array, value, expectedIndex); TestComparerSpan(array, value, expectedIndex); TestComparerReadOnlySpan(array, value, expectedIndex); } private static void TestSpan<T, TComparable>( T[] array, TComparable value, int expectedIndex) where TComparable : IComparable<T> { var span = new Span<T>(array); var index = span.BinarySearch(value); Assert.Equal(expectedIndex, index); } private static void TestReadOnlySpan<T, TComparable>( T[] array, TComparable value, int expectedIndex) where TComparable : IComparable<T> { var span = new ReadOnlySpan<T>(array); var index = span.BinarySearch(value); Assert.Equal(expectedIndex, index); } private static void TestIComparableSpan<T, TComparable>( T[] array, TComparable value, int expectedIndex) where TComparable : IComparable<T>, T { var span = new Span<T>(array); var index = span.BinarySearch((IComparable<T>)value); Assert.Equal(expectedIndex, index); } private static void TestIComparableReadOnlySpan<T, TComparable>( T[] array, TComparable value, int expectedIndex) where TComparable : IComparable<T>, T { var span = new ReadOnlySpan<T>(array); var index = span.BinarySearch((IComparable<T>)value); Assert.Equal(expectedIndex, index); } private static void TestComparerSpan<T, TComparable>( T[] array, TComparable value, int expectedIndex) where TComparable : IComparable<T>, T { var span = new Span<T>(array); var index = span.BinarySearch(value, Comparer<T>.Default); Assert.Equal(expectedIndex, index); } private static void TestComparerReadOnlySpan<T, TComparable>( T[] array, TComparable value, int expectedIndex) where TComparable : IComparable<T>, T { var span = new ReadOnlySpan<T>(array); var index = span.BinarySearch(value, Comparer<T>.Default); Assert.Equal(expectedIndex, index); } } }
// ========================================================================== // This software is subject to the provisions of the Zope Public License, // Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. // THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED // WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS // FOR A PARTICULAR PURPOSE. // ========================================================================== using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Security; namespace Python.Runtime { /// <summary> /// The ClassManager is responsible for creating and managing instances /// that implement the Python type objects that reflect managed classes. /// /// Each managed type reflected to Python is represented by an instance /// of a concrete subclass of ClassBase. Each instance is associated with /// a generated Python type object, whose slots point to static methods /// of the managed instance's class. /// </summary> internal class ClassManager { static Dictionary<Type, ClassBase> cache; static Type dtype; private ClassManager() {} static ClassManager() { cache = new Dictionary<Type, ClassBase>(128); // SEE: http://msdn.microsoft.com/en-us/library/96b1ayy4%28VS.90%29.aspx // ""All delegates inherit from MulticastDelegate, which inherits from Delegate."" // Was Delegate, which caused a null MethodInfo returned from GetMethode("Invoke") // and crashed on Linux under Mono. dtype = typeof(System.MulticastDelegate); } //==================================================================== // Return the ClassBase-derived instance that implements a particular // reflected managed type, creating it if it doesn't yet exist. //==================================================================== internal static ClassBase GetClass(Type type) { ClassBase cb = null; cache.TryGetValue(type, out cb); if (cb != null) { return cb; } cb = CreateClass(type); cache.Add(type, cb); return cb; } //==================================================================== // Create a new ClassBase-derived instance that implements a reflected // managed type. The new object will be associated with a generated // Python type object. //==================================================================== private static ClassBase CreateClass(Type type) { // First, we introspect the managed type and build some class // information, including generating the member descriptors // that we'll be putting in the Python class __dict__. ClassInfo info = GetClassInfo(type); // Next, select the appropriate managed implementation class. // Different kinds of types, such as array types or interface // types, want to vary certain implementation details to make // sure that the type semantics are consistent in Python. ClassBase impl; // Check to see if the given type extends System.Exception. This // lets us check once (vs. on every lookup) in case we need to // wrap Exception-derived types in old-style classes if (type.ContainsGenericParameters) { impl = new GenericType(type); } else if (type.IsSubclassOf(dtype)) { impl = new DelegateObject(type); } else if (type.IsArray) { impl = new ArrayObject(type); } else if (type.IsInterface) { impl = new InterfaceObject(type); } else if (type == typeof(Exception) || type.IsSubclassOf(typeof(Exception))) { impl = new ExceptionClassObject(type); } else { impl = new ClassObject(type); } impl.indexer = info.indexer; // Now we allocate the Python type object to reflect the given // managed type, filling the Python type slots with thunks that // point to the managed methods providing the implementation. IntPtr tp = TypeManager.GetTypeHandle(impl, type); impl.tpHandle = tp; // Finally, initialize the class __dict__ and return the object. IntPtr dict = Marshal.ReadIntPtr(tp, TypeOffset.tp_dict); IDictionaryEnumerator iter = info.members.GetEnumerator(); while(iter.MoveNext()) { ManagedType item = (ManagedType)iter.Value; string name = (string)iter.Key; Runtime.PyDict_SetItemString(dict, name, item.pyHandle); } // If class has constructors, generate an __doc__ attribute. IntPtr doc; Type marker = typeof(DocStringAttribute); Attribute[] attrs = (Attribute[])type.GetCustomAttributes(marker, false); if (attrs.Length == 0) { doc = IntPtr.Zero; } else { DocStringAttribute attr = (DocStringAttribute)attrs[0]; string docStr = attr.DocString; doc = Runtime.PyString_FromString(docStr); Runtime.PyDict_SetItemString(dict, "__doc__", doc); Runtime.Decref(doc); } ClassObject co = impl as ClassObject; // If this is a ClassObject AND it has constructors, generate a __doc__ attribute. // required that the ClassObject.ctors be changed to internal if (co != null) { if (co.ctors.Length > 0) { // Implement Overloads on the class object ConstructorBinding ctors = new ConstructorBinding(type, tp, co.binder); // ExtensionType types are untracked, so don't Incref() them. // XXX deprecate __overloads__ soon... Runtime.PyDict_SetItemString(dict, "__overloads__", ctors.pyHandle); Runtime.PyDict_SetItemString(dict, "Overloads", ctors.pyHandle); if (doc == IntPtr.Zero) { doc = co.GetDocString(); Runtime.PyDict_SetItemString(dict, "__doc__", doc); Runtime.Decref(doc); } } } return impl; } private static ClassInfo GetClassInfo(Type type) { ClassInfo ci = new ClassInfo(type); Hashtable methods = new Hashtable(); ArrayList list; MethodInfo meth; ManagedType ob; String name; Object item; Type tp; int i, n; // This is complicated because inheritance in Python is name // based. We can't just find DeclaredOnly members, because we // could have a base class A that defines two overloads of a // method and a class B that defines two more. The name-based // descriptor Python will find needs to know about inherited // overloads as well as those declared on the sub class. BindingFlags flags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; MemberInfo[] info = type.GetMembers(flags); Hashtable local = new Hashtable(); ArrayList items = new ArrayList(); MemberInfo m; // Loop through once to find out which names are declared for (i = 0; i < info.Length; i++) { m = info[i]; if (m.DeclaringType == type) { local[m.Name] = 1; } } // Now again to filter w/o losing overloaded member info for (i = 0; i < info.Length; i++) { m = info[i]; if (local[m.Name] != null) { items.Add(m); } } if (type.IsInterface) { // Interface inheritance seems to be a different animal: // more contractual, less structural. Thus, a Type that // represents an interface that inherits from another // interface does not return the inherited interface's // methods in GetMembers. For example ICollection inherits // from IEnumerable, but ICollection's GetMemebers does not // return GetEnumerator. // // Not sure if this is the correct way to fix this, but it // seems to work. Thanks to Bruce Dodson for the fix. Type[] inheritedInterfaces = type.GetInterfaces(); for (i = 0; i < inheritedInterfaces.Length; ++i) { Type inheritedType = inheritedInterfaces[i]; MemberInfo[] imembers = inheritedType.GetMembers(flags); for (n = 0; n < imembers.Length; n++) { m = imembers[n]; if (local[m.Name] == null) { items.Add(m); } } } } for (i = 0; i < items.Count; i++) { MemberInfo mi = (MemberInfo)items[i]; switch(mi.MemberType) { case MemberTypes.Method: meth = (MethodInfo) mi; if (!(meth.IsPublic || meth.IsFamily || meth.IsFamilyOrAssembly)) continue; name = meth.Name; item = methods[name]; if (item == null) { item = methods[name] = new ArrayList(); } list = (ArrayList) item; list.Add(meth); continue; case MemberTypes.Property: PropertyInfo pi = (PropertyInfo) mi; MethodInfo mm = null; try { mm = pi.GetGetMethod(true); if (mm == null) { mm = pi.GetSetMethod(true); } } catch (SecurityException) { // GetGetMethod may try to get a method protected by // StrongNameIdentityPermission - effectively private. continue; } if (mm == null) { continue; } if (!(mm.IsPublic || mm.IsFamily || mm.IsFamilyOrAssembly)) continue; // Check for indexer ParameterInfo[] args = pi.GetIndexParameters(); if (args.GetLength(0) > 0) { Indexer idx = ci.indexer; if (idx == null) { ci.indexer = new Indexer(); idx = ci.indexer; } idx.AddProperty(pi); continue; } ob = new PropertyObject(pi); ci.members[pi.Name] = ob; continue; case MemberTypes.Field: FieldInfo fi = (FieldInfo) mi; if (!(fi.IsPublic || fi.IsFamily || fi.IsFamilyOrAssembly)) continue; ob = new FieldObject(fi); ci.members[mi.Name] = ob; continue; case MemberTypes.Event: EventInfo ei = (EventInfo)mi; MethodInfo me = ei.GetAddMethod(true); if (!(me.IsPublic || me.IsFamily || me.IsFamilyOrAssembly)) continue; ob = new EventObject(ei); ci.members[ei.Name] = ob; continue; case MemberTypes.NestedType: tp = (Type) mi; if (!(tp.IsNestedPublic || tp.IsNestedFamily || tp.IsNestedFamORAssem)) continue; ob = ClassManager.GetClass(tp); ci.members[mi.Name] = ob; continue; } } IDictionaryEnumerator iter = methods.GetEnumerator(); while(iter.MoveNext()) { name = (string) iter.Key; list = (ArrayList) iter.Value; MethodInfo[] mlist = (MethodInfo[])list.ToArray( typeof(MethodInfo) ); ob = new MethodObject(name, mlist); ci.members[name] = ob; } return ci; } } internal class ClassInfo { internal ClassInfo(Type t) { members = new Hashtable(); indexer = null; } public Hashtable members; public Indexer indexer; } }
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk) // Copyright 2014 - Spartaco Giubbolini, Felix Obermaier // // This file is part of SharpMap. // SharpMap is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // SharpMap is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License // along with SharpMap; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Serialization; using NetTopologySuite; using NetTopologySuite.Geometries; using NetTopologySuite.IO; namespace SharpMap.Data { /// <summary> /// Represents an in-memory cache of spatial data. The FeatureDataSet is an extension of System.Data.DataSet /// </summary> /// <remarks>Serialization is achieved using the approach described in http://support.microsoft.com/kb/829740/en-us /// </remarks> [Serializable] public class FeatureDataSet : DataSet, ISerializable { /// <summary> /// Initializes a new instance of the FeatureDataSet class. /// </summary> public FeatureDataSet() {} /// <summary> /// Initializes a new instance of the FeatureDataSet class. /// </summary> /// <param name="info">serialization info</param> /// <param name="context">streaming context</param> protected FeatureDataSet(SerializationInfo info, StreamingContext context) { DataSetName = info.GetString("name"); Namespace = info.GetString("ns"); Prefix = info.GetString("prefix"); CaseSensitive = info.GetBoolean("case"); Locale = new CultureInfo(info.GetInt32("locale")); EnforceConstraints = info.GetBoolean("enforceCons"); var tables = (DataTable[]) info.GetValue("tables", typeof (DataTable[])); base.Tables.AddRange(tables); var constraints = (ArrayList)info.GetValue("constraints", typeof(ArrayList)); SetForeignKeyConstraints(constraints); var relations = (ArrayList)info.GetValue("relations", typeof(ArrayList)); SetRelations(relations); var extendedProperties = (PropertyCollection)info.GetValue("extendedProperties", typeof (PropertyCollection)); if (extendedProperties.Count > 0) // otherwise the next foreach throws exception... weird. foreach (DictionaryEntry keyPair in extendedProperties) ExtendedProperties.Add(keyPair.Key, keyPair.Value); } /// <summary> /// Gets the collection of tables contained in the FeatureDataSet /// </summary> public new FeatureTableCollection Tables { get { return new FeatureTableCollection(base.Tables); } } /// <summary> /// Copies the structure of the FeatureDataSet, including all FeatureDataTable schemas, relations, and constraints. Does not copy any data. /// </summary> /// <returns></returns> public new FeatureDataSet Clone() { var cln = ((FeatureDataSet) (base.Clone())); return cln; } //private void InitClass() //{ // Prefix = ""; // Namespace = "sm"; // Locale = new CultureInfo("en-US"); // CaseSensitive = false; // EnforceConstraints = true; //} void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("name", DataSetName); info.AddValue("ns", Namespace); info.AddValue("prefix", Prefix); info.AddValue("case", CaseSensitive); info.AddValue("locale", Locale.LCID); info.AddValue("enforceCons", EnforceConstraints); info.AddValue("tables", base.Tables.OfType<DataTable>().ToArray()); info.AddValue("constraints", GetForeignKeyConstraints()); info.AddValue("relations", GetRelations()); info.AddValue("extendedProperties", ExtendedProperties); } private ArrayList GetForeignKeyConstraints() { var constraintList = new ArrayList(); var tables = base.Tables; for (int i = 0; i < tables.Count; i++) { DataTable dt = tables[i]; for (int j = 0; j < dt.Constraints.Count; j++) { Constraint c = dt.Constraints[j]; if (c is ForeignKeyConstraint fk) { string constraintName = c.ConstraintName; var parentInfo = new int[fk.RelatedColumns.Length + 1]; parentInfo[0] = tables.IndexOf(fk.RelatedTable); for (int k = 1; k < parentInfo.Length; k++) { parentInfo[k] = fk.RelatedColumns[k - 1].Ordinal; } int[] childInfo = new int[fk.Columns.Length + 1]; childInfo[0] = i;//Since the constraint is on the current table, this is the child table. for (int k = 1; k < childInfo.Length; k++) { childInfo[k] = fk.Columns[k - 1].Ordinal; } var list = new ArrayList { constraintName, parentInfo, childInfo, new[] {(int) fk.AcceptRejectRule, (int) fk.UpdateRule, (int) fk.DeleteRule} }; var extendedProperties = new Hashtable(); if (fk.ExtendedProperties.Keys.Count > 0) { foreach (object propertyKey in fk.ExtendedProperties.Keys) { extendedProperties.Add(propertyKey, fk.ExtendedProperties[propertyKey]); } } list.Add(extendedProperties); constraintList.Add(list); } } } return constraintList; } private ArrayList GetRelations() { var relationList = new ArrayList(); var tables = base.Tables; foreach (DataRelation rel in Relations) { string relationName = rel.RelationName; var parentInfo = new int[rel.ParentColumns.Length + 1]; parentInfo[0] = tables.IndexOf(rel.ParentTable); for (int j = 1; j < parentInfo.Length; j++) { parentInfo[j] = rel.ParentColumns[j - 1].Ordinal; } var childInfo = new int[rel.ChildColumns.Length + 1]; childInfo[0] = tables.IndexOf(rel.ChildTable); for (int j = 1; j < childInfo.Length; j++) { childInfo[j] = rel.ChildColumns[j - 1].Ordinal; } var list = new ArrayList {relationName, parentInfo, childInfo, rel.Nested}; var extendedProperties = new Hashtable(); if (rel.ExtendedProperties.Keys.Count > 0) { foreach (object propertyKey in rel.ExtendedProperties.Keys) { extendedProperties.Add(propertyKey, rel.ExtendedProperties[propertyKey]); } } list.Add(extendedProperties); relationList.Add(list); } return relationList; } private void SetForeignKeyConstraints(ArrayList constraintList) { Debug.Assert(constraintList != null); var tables = base.Tables; foreach (ArrayList list in constraintList) { Debug.Assert(list.Count == 5); string constraintName = (string)list[0]; int[] parentInfo = (int[])list[1]; int[] childInfo = (int[])list[2]; int[] rules = (int[])list[3]; Hashtable extendedProperties = (Hashtable)list[4]; //ParentKey Columns. Debug.Assert(parentInfo.Length >= 1); DataColumn[] parentkeyColumns = new DataColumn[parentInfo.Length - 1]; for (int i = 0; i < parentkeyColumns.Length; i++) { Debug.Assert(tables.Count > parentInfo[0]); Debug.Assert(tables[parentInfo[0]].Columns.Count > parentInfo[i + 1]); parentkeyColumns[i] = tables[parentInfo[0]].Columns[parentInfo[i + 1]]; } //ChildKey Columns. Debug.Assert(childInfo.Length >= 1); DataColumn[] childkeyColumns = new DataColumn[childInfo.Length - 1]; for (int i = 0; i < childkeyColumns.Length; i++) { Debug.Assert(tables.Count > childInfo[0]); Debug.Assert(tables[childInfo[0]].Columns.Count > childInfo[i + 1]); childkeyColumns[i] = tables[childInfo[0]].Columns[childInfo[i + 1]]; } //Create the Constraint. ForeignKeyConstraint fk = new ForeignKeyConstraint(constraintName, parentkeyColumns, childkeyColumns); Debug.Assert(rules.Length == 3); fk.AcceptRejectRule = (AcceptRejectRule)rules[0]; fk.UpdateRule = (Rule)rules[1]; fk.DeleteRule = (Rule)rules[2]; //Extended Properties. Debug.Assert(extendedProperties != null); if (extendedProperties.Keys.Count > 0) { foreach (object propertyKey in extendedProperties.Keys) { fk.ExtendedProperties.Add(propertyKey, extendedProperties[propertyKey]); } } //Add the constraint to the child datatable. Debug.Assert(tables.Count > childInfo[0]); tables[childInfo[0]].Constraints.Add(fk); } } private void SetRelations(ArrayList relationList) { Debug.Assert(relationList != null); var tables = base.Tables; foreach (ArrayList list in relationList) { Debug.Assert(list.Count == 5); var relationName = (string)list[0]; var parentInfo = (int[])list[1]; var childInfo = (int[])list[2]; var isNested = (bool)list[3]; var extendedProperties = (Hashtable)list[4]; //ParentKey Columns. Debug.Assert(parentInfo.Length >= 1); var parentkeyColumns = new DataColumn[parentInfo.Length - 1]; for (int i = 0; i < parentkeyColumns.Length; i++) { Debug.Assert(tables.Count > parentInfo[0]); Debug.Assert(tables[parentInfo[0]].Columns.Count > parentInfo[i + 1]); parentkeyColumns[i] = tables[parentInfo[0]].Columns[parentInfo[i + 1]]; } //ChildKey Columns. Debug.Assert(childInfo.Length >= 1); var childkeyColumns = new DataColumn[childInfo.Length - 1]; for (int i = 0; i < childkeyColumns.Length; i++) { Debug.Assert(tables.Count > childInfo[0]); Debug.Assert(tables[childInfo[0]].Columns.Count > childInfo[i + 1]); childkeyColumns[i] = tables[childInfo[0]].Columns[childInfo[i + 1]]; } //Create the Relation, without any constraints[Assumption: The constraints are added earlier than the relations] var rel = new DataRelation(relationName, parentkeyColumns, childkeyColumns, false) { Nested = isNested }; //Extended Properties. Debug.Assert(extendedProperties != null); if (extendedProperties.Keys.Count > 0) { foreach (object propertyKey in extendedProperties.Keys) { rel.ExtendedProperties.Add(propertyKey, extendedProperties[propertyKey]); } } //Add the relations to the dataset. Relations.Add(rel); } } } /// <summary> /// Represents the method that will handle the RowChanging, RowChanged, RowDeleting, and RowDeleted events of a FeatureDataTable. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public delegate void FeatureDataRowChangeEventHandler(object sender, FeatureDataRowChangeEventArgs e); /// <summary> /// Represents one feature table of in-memory spatial data. /// </summary> [DebuggerStepThrough] [Serializable] public class FeatureDataTable : DataTable, IEnumerable { /// <summary> /// Initializes a new instance of the FeatureDataTable class with no arguments. /// </summary> public FeatureDataTable() { //InitClass(); } /// <summary> /// Creates an instance of this class from serialization /// </summary> /// <param name="info">The serialization info</param> /// <param name="context">The streaming context</param> public FeatureDataTable(SerializationInfo info, StreamingContext context) : base(info, context) { using (var ms = new MemoryStream((byte[]) info.GetValue("geometries", typeof(byte[])))) { using (var reader = new BinaryReader(ms)) { while (reader.BaseStream.Position < reader.BaseStream.Length) { var rowIndex = reader.ReadInt32(); var row = (FeatureDataRow) Rows[rowIndex]; var srid = reader.ReadInt32(); #pragma warning disable CS0612 // Type or member is obsolete var wkbReader = new WKBReader(NtsGeometryServices.Instance); #pragma warning restore CS0612 // Type or member is obsolete var wkbSize = reader.ReadInt32(); var wkb = reader.ReadBytes(wkbSize); row.Geometry = wkbReader.Read(wkb); } }} } /// <summary> /// Initializes a new instance of the FeatureDataTable class with the specified table name. /// </summary> /// <param name="table"></param> public FeatureDataTable(DataTable table) : base(table.TableName) { if (table.DataSet != null) { if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { CaseSensitive = table.CaseSensitive; } if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { Locale = table.Locale; } if ((table.Namespace != table.DataSet.Namespace)) { Namespace = table.Namespace; } } Prefix = table.Prefix; MinimumCapacity = table.MinimumCapacity; DisplayExpression = table.DisplayExpression; } /// <summary> /// Gets the number of rows in the table /// </summary> [Browsable(false)] public int Count { get { return Rows.Count; } } /// <summary> /// Gets the feature data row at the specified index /// </summary> /// <param name="index">row index</param> /// <returns>FeatureDataRow</returns> public FeatureDataRow this[int index] { get { return (FeatureDataRow) Rows[index]; } } #region IEnumerable Members /// <summary> /// Returns an enumerator for enumerating the rows of the FeatureDataTable /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return Rows.GetEnumerator(); } #endregion /// <summary> /// Occurs after a FeatureDataRow has been changed successfully. /// </summary> public event FeatureDataRowChangeEventHandler FeatureDataRowChanged; /// <summary> /// Occurs when a FeatureDataRow is changing. /// </summary> public event FeatureDataRowChangeEventHandler FeatureDataRowChanging; /// <summary> /// Occurs after a row in the table has been deleted. /// </summary> public event FeatureDataRowChangeEventHandler FeatureDataRowDeleted; /// <summary> /// Occurs before a row in the table is about to be deleted. /// </summary> public event FeatureDataRowChangeEventHandler FeatureDataRowDeleting; /// <summary> /// Adds a row to the FeatureDataTable /// </summary> /// <param name="row"></param> public void AddRow(FeatureDataRow row) { Rows.Add(row); } /// <summary> /// Clones the structure of the FeatureDataTable, including all FeatureDataTable schemas and constraints. /// </summary> /// <returns></returns> public new FeatureDataTable Clone() { var cln = ((FeatureDataTable) (base.Clone())); //cln.InitVars(); return cln; } /// <summary> /// /// </summary> /// <returns></returns> protected override DataTable CreateInstance() { return new FeatureDataTable(); } //internal void InitVars() //{ // //this.columnFeatureGeometry = this.Columns["FeatureGeometry"]; //} //private void InitClass() //{ // //this.columnFeatureGeometry = new DataColumn("FeatureGeometry", typeof(NetTopologySuite.Geometries.Geometry), null, System.Data.MappingType.Element); // //this.Columns.Add(this.columnFeatureGeometry); //} /// <summary> /// Creates a new FeatureDataRow with the same schema as the table. /// </summary> /// <returns></returns> public new FeatureDataRow NewRow() { return (FeatureDataRow) base.NewRow(); } /// <summary> /// Creates a new FeatureDataRow with the same schema as the table, based on a datarow builder /// </summary> /// <param name="builder"></param> /// <returns></returns> protected override DataRow NewRowFromBuilder(DataRowBuilder builder) { return new FeatureDataRow(builder); } /// <summary> /// /// </summary> /// <returns></returns> protected override Type GetRowType() { return typeof (FeatureDataRow); } /// <summary> /// Raises the FeatureDataRowChanged event. /// </summary> /// <param name="e"></param> protected override void OnRowChanged(DataRowChangeEventArgs e) { base.OnRowChanged(e); if ((FeatureDataRowChanged != null)) { FeatureDataRowChanged(this, new FeatureDataRowChangeEventArgs(((FeatureDataRow) (e.Row)), e.Action)); } } /// <summary> /// Raises the FeatureDataRowChanging event. /// </summary> /// <param name="e"></param> protected override void OnRowChanging(DataRowChangeEventArgs e) { base.OnRowChanging(e); if ((FeatureDataRowChanging != null)) { FeatureDataRowChanging(this, new FeatureDataRowChangeEventArgs(((FeatureDataRow) (e.Row)), e.Action)); } } /// <summary> /// Raises the FeatureDataRowDeleted event /// </summary> /// <param name="e"></param> protected override void OnRowDeleted(DataRowChangeEventArgs e) { base.OnRowDeleted(e); if ((FeatureDataRowDeleted != null)) { FeatureDataRowDeleted(this, new FeatureDataRowChangeEventArgs(((FeatureDataRow) (e.Row)), e.Action)); } } /// <summary> /// Raises the FeatureDataRowDeleting event. /// </summary> /// <param name="e"></param> protected override void OnRowDeleting(DataRowChangeEventArgs e) { base.OnRowDeleting(e); if ((FeatureDataRowDeleting != null)) { FeatureDataRowDeleting(this, new FeatureDataRowChangeEventArgs(((FeatureDataRow) (e.Row)), e.Action)); } } ///// <summary> ///// Gets the collection of rows that belong to this table. ///// </summary> //public new DataRowCollection Rows //{ // get { throw (new NotSupportedException()); } // set { throw (new NotSupportedException()); } //} /// <summary> /// Removes the row from the table /// </summary> /// <param name="row">Row to remove</param> public void RemoveRow(FeatureDataRow row) { Rows.Remove(row); } /// <summary> /// Populates a serialization information object with the data needed to serialize the <see cref="T:System.Data.DataTable"/>. /// </summary> /// <param name="info">A <see cref="T:System.Runtime.Serialization.SerializationInfo"/> object that holds the serialized data associated with the <see cref="T:System.Data.DataTable"/>.</param><param name="context">A <see cref="T:System.Runtime.Serialization.StreamingContext"/> object that contains the source and destination of the serialized stream associated with the <see cref="T:System.Data.DataTable"/>.</param><exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is a null reference (Nothing in Visual Basic).</exception> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); var rowIndex = 0; using (var ms = new MemoryStream()) { using (var writer = new BinaryWriter(ms)) { foreach (FeatureDataRow row in Rows) { if (row.IsFeatureGeometryNull()) continue; writer.Write(rowIndex++); writer.Write(row.Geometry.SRID); var wkb = row.Geometry.AsBinary(); writer.Write(wkb.Length); writer.Write(wkb); } ms.Seek(0, SeekOrigin.Begin); info.AddValue("geometries", ms.ToArray(), typeof(byte[])); } } } } /* /// <summary> /// Represents the collection of tables for the FeatureDataSet. /// </summary> [Serializable()] public class FeatureTableCollection : List<FeatureDataTable> { } */ /// <summary> /// Represents the collection of tables for the FeatureDataSet. /// It is a proxy to the <see cref="DataSet.Tables"/> object. /// It filters out those <see cref="T:System.Data.DataTable"/> /// that are <see cref="T:SharpMap.Data.FeatureDataTable"/>s. /// </summary> public class FeatureTableCollection : ICollection<FeatureDataTable> { private readonly DataTableCollection _dataTables; internal FeatureTableCollection(DataTableCollection dataTables) { _dataTables = dataTables; } public IEnumerator<FeatureDataTable> GetEnumerator() { var dataTables = new DataTable[_dataTables.Count]; _dataTables.CopyTo(dataTables, 0); foreach (var dataTable in dataTables) { if (dataTable is FeatureDataTable) yield return (FeatureDataTable) dataTable; } } /// <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> /// <filterpriority>2</filterpriority> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Method to add a <see cref="FeatureDataTable"/> to this set. /// </summary> /// <remarks>If <paramref name="item"/> belongs to a different <see cref="FeatureDataSet"/>, /// this method attempts to remove it from that. If that is not possible, <paramref name="item"/> /// is copied (<see cref="DataTable.Copy"/>) and the copy is then added. /// </remarks> /// <param name="item">The feature data table to add</param> public void Add(FeatureDataTable item) { var itemDataSet = item.DataSet; if (itemDataSet != null) { if (itemDataSet.Tables.CanRemove(item)) itemDataSet.Tables.Remove(item); else item = (FeatureDataTable) item.Copy(); } _dataTables.Add(item); } /// <summary> /// Method to add a range of <see cref="FeatureDataTable"/>s to the (Feature)DataTableCollection. /// </summary> /// <param name="items">The tables to add</param> public void AddRange(IEnumerable<FeatureDataTable> items) { foreach (var item in items) { _dataTables.Add(item); } } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception> public void Clear() { _dataTables.Clear(); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> public bool Contains(FeatureDataTable item) { return _dataTables.Contains(item.TableName, item.Namespace); } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException">The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.</exception> public void CopyTo(FeatureDataTable[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < 0) throw new ArgumentException("Negative arrayIndex"); var j = 0; for (var i = 0; i < _dataTables.Count; i++) { if (_dataTables[i] is FeatureDataTable) { if (j >= array.Length) throw new ArgumentException("Insufficient space provided for array"); array[j++] = (FeatureDataTable) _dataTables[i]; } } } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public bool Remove(FeatureDataTable item) { if (_dataTables.CanRemove(item)) { _dataTables.Remove(item); return true; } return false; } /// <summary> /// Remove the feature data table at the provided index /// </summary> /// <param name="index">The index of the table to remove</param> /// <returns><c>true</c> if the table was successfully removed</returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public bool RemoveAt(int index) { if (index < 0) throw new ArgumentOutOfRangeException("index"); var tmp = 0; DataTable tableToRemove = null; foreach (DataTable dataTable in _dataTables) { if (dataTable is FeatureDataTable) { if (tmp == index) { tableToRemove = dataTable; break; } tmp++; } } if (tableToRemove != null) return Remove((FeatureDataTable)tableToRemove); return false; } /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> public int Count { get { var i = 0; foreach (var dataTable in _dataTables) { if (dataTable is FeatureDataTable) i++; } return i; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false. /// </returns> public bool IsReadOnly { get { return false; } } /// <summary> /// An indexer to the feature data tables in this set /// </summary> /// <param name="index">The index of the feature data table to get</param> /// <returns>The feature data table at index <paramref name="index"/>.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown, if the index is not in the valid range.</exception> public FeatureDataTable this[int index] { get { var i = 0; foreach (var dataTable in _dataTables) { if (dataTable is FeatureDataTable) { if (i == index) return (FeatureDataTable) dataTable; i++; } } throw new ArgumentOutOfRangeException("index"); } } } /// <summary> /// Represents a row of data in a FeatureDataTable. /// </summary> [DebuggerStepThrough] [Serializable] public class FeatureDataRow : DataRow { //private FeatureDataTable tableFeatureTable; private Geometry _geometry; /// <summary> /// Creates an instance of this class /// </summary> /// <param name="rb">The row builder</param> public FeatureDataRow(DataRowBuilder rb) : base(rb) { } /// <summary> /// The geometry of the current feature /// </summary> public Geometry Geometry { get { return _geometry; } set { if (_geometry == null) { _geometry = value; } else { if (ReferenceEquals(_geometry, value)) return; if (_geometry != null && _geometry.EqualsTopologically(value)) return; _geometry = value; if (RowState == DataRowState.Unchanged) SetModified(); } } } /// <summary> /// Returns true of the geometry is null /// </summary> /// <returns></returns> public bool IsFeatureGeometryNull() { return _geometry == null; } /// <summary> /// Sets the geometry column to null /// </summary> public void SetFeatureGeometryNull() { _geometry = null; } } /// <summary> /// Occurs after a FeatureDataRow has been changed successfully. /// </summary> [DebuggerStepThrough] public class FeatureDataRowChangeEventArgs : EventArgs { private readonly DataRowAction _eventAction; private readonly FeatureDataRow _eventRow; /// <summary> /// Initializes a new instance of the FeatureDataRowChangeEventArgs class. /// </summary> /// <param name="row"></param> /// <param name="action"></param> public FeatureDataRowChangeEventArgs(FeatureDataRow row, DataRowAction action) { _eventRow = row; _eventAction = action; } /// <summary> /// Gets the row upon which an action has occurred. /// </summary> public FeatureDataRow Row { get { return _eventRow; } } /// <summary> /// Gets the action that has occurred on a FeatureDataRow. /// </summary> public DataRowAction Action { get { return _eventAction; } } } }
using System; using System.Collections.Generic; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Publishing; namespace Umbraco.Core.Services { /// <summary> /// Defines the ContentService, which is an easy access to operations involving <see cref="IContent"/> /// </summary> public interface IContentService : IService { /// <summary> /// Assigns a single permission to the current content item for the specified user ids /// </summary> /// <param name="entity"></param> /// <param name="permission"></param> /// <param name="userIds"></param> void AssignContentPermission(IContent entity, char permission, IEnumerable<int> userIds); /// <summary> /// Gets the list of permissions for the content item /// </summary> /// <param name="content"></param> /// <returns></returns> IEnumerable<EntityPermission> GetPermissionsForEntity(IContent content); bool SendToPublication(IContent content, int userId = 0); IEnumerable<IContent> GetByIds(IEnumerable<int> ids); /// <summary> /// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IContent without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new content objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parentId">Id of Parent for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContent(string name, int parentId, string contentTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IContent without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new content objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContent(string name, IContent parent, string contentTypeAlias, int userId = 0); /// <summary> /// Gets an <see cref="IContent"/> object by Id /// </summary> /// <param name="id">Id of the Content to retrieve</param> /// <returns><see cref="IContent"/></returns> IContent GetById(int id); /// <summary> /// Gets an <see cref="IContent"/> object by its 'UniqueId' /// </summary> /// <param name="key">Guid key of the Content to retrieve</param> /// <returns><see cref="IContent"/></returns> IContent GetById(Guid key); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by the Id of the <see cref="IContentType"/> /// </summary> /// <param name="id">Id of the <see cref="IContentType"/></param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentOfContentType(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Level /// </summary> /// <param name="level">The level to retrieve Content from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetByLevel(int level); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetChildren(int id); /// <summary> /// Gets a collection of an <see cref="IContent"/> objects versions by its Id /// </summary> /// <param name="id"></param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetVersions(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which reside at the first level / root /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetRootContent(); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which has an expiration date greater then today /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentForExpiration(); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which has a release date greater then today /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentForRelease(); /// <summary> /// Gets a collection of an <see cref="IContent"/> objects, which resides in the Recycle Bin /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentInRecycleBin(); /// <summary> /// Saves a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IContent"/> objects. /// </summary> /// <param name="contents">Collection of <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true); /// <summary> /// Deletes all content of specified type. All children of deleted content is moved to Recycle Bin. /// </summary> /// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> /// <param name="contentTypeId">Id of the <see cref="IContentType"/></param> /// <param name="userId">Optional Id of the user issueing the delete operation</param> void DeleteContentOfType(int contentTypeId, int userId = 0); /// <summary> /// Permanently deletes versions from an <see cref="IContent"/> object prior to a specific date. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> object to delete versions from</param> /// <param name="versionDate">Latest version date</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersions(int id, DateTime versionDate, int userId = 0); /// <summary> /// Permanently deletes a specific version from an <see cref="IContent"/> object. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> object to delete a version from</param> /// <param name="versionId">Id of the version to delete</param> /// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0); /// <summary> /// Deletes an <see cref="IContent"/> object by moving it to the Recycle Bin /// </summary> /// <remarks>Move an item to the Recycle Bin will result in the item being unpublished</remarks> /// <param name="content">The <see cref="IContent"/> to delete</param> /// <param name="userId">Optional Id of the User deleting the Content</param> void MoveToRecycleBin(IContent content, int userId = 0); /// <summary> /// Moves an <see cref="IContent"/> object to a new location /// </summary> /// <param name="content">The <see cref="IContent"/> to move</param> /// <param name="parentId">Id of the Content's new Parent</param> /// <param name="userId">Optional Id of the User moving the Content</param> void Move(IContent content, int parentId, int userId = 0); /// <summary> /// Empties the Recycle Bin by deleting all <see cref="IContent"/> that resides in the bin /// </summary> void EmptyRecycleBin(); /// <summary> /// Rollback an <see cref="IContent"/> object to a previous version. /// This will create a new version, which is a copy of all the old data. /// </summary> /// <param name="id">Id of the <see cref="IContent"/>being rolled back</param> /// <param name="versionId">Id of the version to rollback to</param> /// <param name="userId">Optional Id of the User issueing the rollback of the Content</param> /// <returns>The newly created <see cref="IContent"/> object</returns> IContent Rollback(int id, Guid versionId, int userId = 0); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by its name or partial name /// </summary> /// <param name="parentId">Id of the Parent to retrieve Children from</param> /// <param name="name">Full or partial name of the children</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetChildrenByName(int parentId, string name); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetDescendants(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="content"><see cref="IContent"/> item to retrieve Descendants from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetDescendants(IContent content); /// <summary> /// Gets a specific version of an <see cref="IContent"/> item. /// </summary> /// <param name="versionId">Id of the version to retrieve</param> /// <returns>An <see cref="IContent"/> item</returns> IContent GetByVersion(Guid versionId); /// <summary> /// Gets the published version of an <see cref="IContent"/> item /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve version from</param> /// <returns>An <see cref="IContent"/> item</returns> IContent GetPublishedVersion(int id); /// <summary> /// Checks whether an <see cref="IContent"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IContent"/></param> /// <returns>True if the content has any children otherwise False</returns> bool HasChildren(int id); /// <summary> /// Checks whether an <see cref="IContent"/> item has any published versions /// </summary> /// <param name="id">Id of the <see cref="IContent"/></param> /// <returns>True if the content has any published version otherwise False</returns> bool HasPublishedVersion(int id); /// <summary> /// Re-Publishes all Content /// </summary> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> bool RePublishAll(int userId = 0); /// <summary> /// Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> bool Publish(IContent content, int userId = 0); /// <summary> /// Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>The published status attempt</returns> Attempt<PublishStatus> PublishWithStatus(IContent content, int userId = 0); /// <summary> /// Publishes a <see cref="IContent"/> object and all its children /// </summary> /// <param name="content">The <see cref="IContent"/> to publish along with its children</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> [Obsolete("Use PublishWithChildrenWithStatus instead, that method will provide more detailed information on the outcome and also allows the includeUnpublished flag")] bool PublishWithChildren(IContent content, int userId = 0); /// <summary> /// Publishes a <see cref="IContent"/> object and all its children /// </summary> /// <param name="content">The <see cref="IContent"/> to publish along with its children</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="includeUnpublished"></param> /// <returns>The list of statuses for all published items</returns> IEnumerable<Attempt<PublishStatus>> PublishWithChildrenWithStatus(IContent content, int userId = 0, bool includeUnpublished = false); /// <summary> /// UnPublishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if unpublishing succeeded, otherwise False</returns> bool UnPublish(IContent content, int userId = 0); /// <summary> /// Saves and Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save and publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param> /// <returns>True if publishing succeeded, otherwise False</returns> [Obsolete("Use SaveAndPublishWithStatus instead, that method will provide more detailed information on the outcome")] bool SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves and Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save and publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param> /// <returns>True if publishing succeeded, otherwise False</returns> Attempt<PublishStatus> SaveAndPublishWithStatus(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Permanently deletes an <see cref="IContent"/> object. /// </summary> /// <remarks> /// This method will also delete associated media files, child content and possibly associated domains. /// </remarks> /// <remarks>Please note that this method will completely remove the Content from the database</remarks> /// <param name="content">The <see cref="IContent"/> to delete</param> /// <param name="userId">Optional Id of the User deleting the Content</param> void Delete(IContent content, int userId = 0); /// <summary> /// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current /// to the new copy which is returned. /// </summary> /// <param name="content">The <see cref="IContent"/> to copy</param> /// <param name="parentId">Id of the Content's new Parent</param> /// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param> /// <param name="userId">Optional Id of the User copying the Content</param> /// <returns>The newly created <see cref="IContent"/> object</returns> IContent Copy(IContent content, int parentId, bool relateToOriginal, int userId = 0); /// <summary> /// Checks if the passed in <see cref="IContent"/> can be published based on the anscestors publish state. /// </summary> /// <param name="content"><see cref="IContent"/> to check if anscestors are published</param> /// <returns>True if the Content can be published, otherwise False</returns> bool IsPublishable(IContent content); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetAncestors(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content. /// </summary> /// <param name="content"><see cref="IContent"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetAncestors(IContent content); /// <summary> /// Sorts a collection of <see cref="IContent"/> objects by updating the SortOrder according /// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>. /// </summary> /// <remarks> /// Using this method will ensure that the Published-state is maintained upon sorting /// so the cache is updated accordingly - as needed. /// </remarks> /// <param name="items"></param> /// <param name="userId"></param> /// <param name="raiseEvents"></param> /// <returns>True if sorting succeeded, otherwise False</returns> bool Sort(IEnumerable<IContent> items, int userId = 0, bool raiseEvents = true); /// <summary> /// Gets the parent of the current content as an <see cref="IContent"/> item. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IContent"/> object</returns> IContent GetParent(int id); /// <summary> /// Gets the parent of the current content as an <see cref="IContent"/> item. /// </summary> /// <param name="content"><see cref="IContent"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IContent"/> object</returns> IContent GetParent(IContent content); /// <summary> /// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IContent"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContentWithIdentity(string name, IContent parent, string contentTypeAlias, int userId = 0); /// <summary> /// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IContent"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parentId">Id of Parent for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContentWithIdentity(string name, int parentId, string contentTypeAlias, int userId = 0); } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // SmtpClientTest.cs - NUnit Test Cases for System.Net.Mail.SmtpClient // // Authors: // John Luke (john.luke@gmail.com) // // (C) 2006 John Luke // using System.IO; using System.Net.NetworkInformation; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Mail.Tests { public class SmtpClientTest : FileCleanupTestBase { private SmtpClient _smtp; private SmtpClient Smtp { get { return _smtp ?? (_smtp = new SmtpClient()); } } private string TempFolder { get { return TestDirectory; } } protected override void Dispose(bool disposing) { if (_smtp != null) { _smtp.Dispose(); } base.Dispose(disposing); } [Theory] [InlineData(SmtpDeliveryMethod.SpecifiedPickupDirectory)] [InlineData(SmtpDeliveryMethod.PickupDirectoryFromIis)] [InlineData(SmtpDeliveryMethod.PickupDirectoryFromIis)] public void DeliveryMethodTest(SmtpDeliveryMethod method) { Smtp.DeliveryMethod = method; Assert.Equal(method, Smtp.DeliveryMethod); } [Theory] [InlineData(true)] [InlineData(false)] public void EnableSslTest(bool value) { Smtp.EnableSsl = value; Assert.Equal(value, Smtp.EnableSsl); } [Theory] [InlineData("127.0.0.1")] [InlineData("smtp.ximian.com")] public void HostTest(string host) { Smtp.Host = host; Assert.Equal(host, Smtp.Host); } [Fact] public void InvalidHostTest() { Assert.Throws<ArgumentNullException>(() => Smtp.Host = null); AssertExtensions.Throws<ArgumentException>("value", () => Smtp.Host = ""); } [Fact] public void ServicePoint_GetsCachedInstanceSpecificToHostPort() { using (var smtp1 = new SmtpClient("localhost1", 25)) using (var smtp2 = new SmtpClient("localhost1", 25)) using (var smtp3 = new SmtpClient("localhost2", 25)) using (var smtp4 = new SmtpClient("localhost2", 26)) { ServicePoint s1 = smtp1.ServicePoint; ServicePoint s2 = smtp2.ServicePoint; ServicePoint s3 = smtp3.ServicePoint; ServicePoint s4 = smtp4.ServicePoint; Assert.NotNull(s1); Assert.NotNull(s2); Assert.NotNull(s3); Assert.NotNull(s4); Assert.Same(s1, s2); Assert.NotSame(s2, s3); Assert.NotSame(s2, s4); Assert.NotSame(s3, s4); } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [Fact] public void ServicePoint_NetCoreApp_AddressIsAccessible() { using (var smtp = new SmtpClient("localhost", 25)) { Assert.Equal("mailto", smtp.ServicePoint.Address.Scheme); Assert.Equal("localhost", smtp.ServicePoint.Address.Host); Assert.Equal(25, smtp.ServicePoint.Address.Port); } } [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] [Fact] public void ServicePoint_NetFramework_AddressIsInaccessible() { using (var smtp = new SmtpClient("localhost", 25)) { ServicePoint sp = smtp.ServicePoint; Assert.Throws<NotSupportedException>(() => sp.Address); } } [Fact] public void ServicePoint_ReflectsHostAndPortChange() { using (var smtp = new SmtpClient("localhost1", 25)) { ServicePoint s1 = smtp.ServicePoint; smtp.Host = "localhost2"; ServicePoint s2 = smtp.ServicePoint; smtp.Host = "localhost2"; ServicePoint s3 = smtp.ServicePoint; Assert.NotSame(s1, s2); Assert.Same(s2, s3); smtp.Port = 26; ServicePoint s4 = smtp.ServicePoint; smtp.Port = 26; ServicePoint s5 = smtp.ServicePoint; Assert.NotSame(s3, s4); Assert.Same(s4, s5); } } [Theory] [InlineData("")] [InlineData(null)] [InlineData("shouldnotexist")] [InlineData("\0")] [InlineData("C:\\some\\path\\like\\string")] public void PickupDirectoryLocationTest(string folder) { Smtp.PickupDirectoryLocation = folder; Assert.Equal(folder, Smtp.PickupDirectoryLocation); } [Theory] [InlineData(25)] [InlineData(1)] [InlineData(int.MaxValue)] public void PortTest(int value) { Smtp.Port = value; Assert.Equal(value, Smtp.Port); } [Fact] public void TestDefaultsOnProperties() { Assert.Equal(25, Smtp.Port); Assert.Equal(100000, Smtp.Timeout); Assert.Null(Smtp.Host); Assert.Null(Smtp.Credentials); Assert.False(Smtp.EnableSsl); Assert.False(Smtp.UseDefaultCredentials); Assert.Equal(SmtpDeliveryMethod.Network, Smtp.DeliveryMethod); Assert.Null(Smtp.PickupDirectoryLocation); } [Theory] [InlineData(0)] [InlineData(-1)] [InlineData(int.MinValue)] public void Port_Value_Invalid(int value) { Assert.Throws<ArgumentOutOfRangeException>(() => Smtp.Port = value); } [Fact] public void Send_Message_Null() { Assert.Throws<ArgumentNullException>(() => Smtp.Send(null)); } [Fact] public void Send_Network_Host_Null() { Assert.Throws<InvalidOperationException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello")); } [Fact] public void Send_Network_Host_Whitespace() { Smtp.Host = " \r\n "; Assert.Throws<InvalidOperationException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello")); } [Fact] public void Send_SpecifiedPickupDirectory() { Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; Smtp.PickupDirectoryLocation = TempFolder; Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello"); string[] files = Directory.GetFiles(TempFolder, "*"); Assert.Equal(1, files.Length); Assert.Equal(".eml", Path.GetExtension(files[0])); } [Theory] [InlineData("some_path_not_exist")] [InlineData("")] [InlineData(null)] [InlineData("\0abc")] public void Send_SpecifiedPickupDirectoryInvalid(string location) { Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; Smtp.PickupDirectoryLocation = location; Assert.Throws<SmtpException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello")); } [Theory] [InlineData(0)] [InlineData(50)] [InlineData(int.MaxValue)] [InlineData(int.MinValue)] [InlineData(-1)] public void TestTimeout(int value) { if (value < 0) { Assert.Throws<ArgumentOutOfRangeException>(() => Smtp.Timeout = value); return; } Smtp.Timeout = value; Assert.Equal(value, Smtp.Timeout); } [Fact] public void Send_ServerDoesntExist_Throws() { using (var smtp = new SmtpClient(Guid.NewGuid().ToString("N"))) { Assert.Throws<SmtpException>(() => smtp.Send("anyone@anyone.com", "anyone@anyone.com", "subject", "body")); } } [Fact] public async Task SendAsync_ServerDoesntExist_Throws() { using (var smtp = new SmtpClient(Guid.NewGuid().ToString("N"))) { await Assert.ThrowsAsync<SmtpException>(() => smtp.SendMailAsync("anyone@anyone.com", "anyone@anyone.com", "subject", "body")); } } [Fact] public void TestMailDelivery() { SmtpServer server = new SmtpServer(); SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port); client.Credentials = new NetworkCredential("user", "password"); MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo"); string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower(); try { Thread t = new Thread(server.Run); t.Start(); client.Send(msg); t.Join(); Assert.Equal("<foo@example.com>", server.MailFrom); Assert.Equal("<bar@example.com>", server.MailTo); Assert.Equal("hello", server.Subject); Assert.Equal("howdydoo", server.Body); Assert.Equal(clientDomain, server.ClientDomain); } finally { server.Stop(); } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework has a bug and could hang in case of null or empty body")] [Theory] [InlineData("howdydoo")] [InlineData("")] [InlineData(null)] public async Task TestMailDeliveryAsync(string body) { SmtpServer server = new SmtpServer(); SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port); MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", body); string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower(); try { Thread t = new Thread(server.Run); t.Start(); await client.SendMailAsync(msg).TimeoutAfter((int)TimeSpan.FromSeconds(30).TotalMilliseconds); t.Join(); Assert.Equal("<foo@example.com>", server.MailFrom); Assert.Equal("<bar@example.com>", server.MailTo); Assert.Equal("hello", server.Subject); Assert.Equal(body ?? "", server.Body); Assert.Equal(clientDomain, server.ClientDomain); } finally { server.Stop(); } } [Fact] public async Task TestCredentialsCopyInAsyncContext() { SmtpServer server = new SmtpServer(); SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port); MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo"); string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower(); CredentialCache cache = new CredentialCache(); cache.Add("localhost", server.EndPoint.Port, "NTLM", CredentialCache.DefaultNetworkCredentials); client.Credentials = cache; try { Thread t = new Thread(server.Run); t.Start(); await client.SendMailAsync(msg); t.Join(); Assert.Equal("<foo@example.com>", server.MailFrom); Assert.Equal("<bar@example.com>", server.MailTo); Assert.Equal("hello", server.Subject); Assert.Equal("howdydoo", server.Body); Assert.Equal(clientDomain, server.ClientDomain); } finally { server.Stop(); } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NETFX doesn't have the fix for encoding")] [Theory] [InlineData(false, false, false)] [InlineData(false, false, true)] // Received subjectText. [InlineData(false, true, false)] [InlineData(false, true, true)] [InlineData(true, false, false)] [InlineData(true, false, true)] // Received subjectText. [InlineData(true, true, false)] [InlineData(true, true, true)] // Received subjectBase64. If subjectText is received, the test fails, and the results are inconsistent with those of synchronous methods. public void SendMail_DeliveryFormat_SubjectEncoded(bool useAsyncSend, bool useSevenBit, bool useSmtpUTF8) { // If the server support `SMTPUTF8` and use `SmtpDeliveryFormat.International`, the server should received this subject. const string subjectText = "Test \u6d4b\u8bd5 Contain \u5305\u542b UTF8"; // If the server does not support `SMTPUTF8` or use `SmtpDeliveryFormat.SevenBit`, the server should received this subject. const string subjectBase64 = "=?utf-8?B?VGVzdCDmtYvor5UgQ29udGFpbiDljIXlkKsgVVRGOA==?="; SmtpServer server = new SmtpServer(); // Setting up Server Support for `SMTPUTF8`. server.SupportSmtpUTF8 = useSmtpUTF8; SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port); if (useSevenBit) { // Subject will be encoded by Base64. client.DeliveryFormat = SmtpDeliveryFormat.SevenBit; } else { // If the server supports `SMTPUTF8`, subject will not be encoded. Otherwise, subject will be encoded by Base64. client.DeliveryFormat = SmtpDeliveryFormat.International; } MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", subjectText, "hello \u9ad8\u575a\u679c"); msg.HeadersEncoding = msg.BodyEncoding = msg.SubjectEncoding = System.Text.Encoding.UTF8; try { Thread t = new Thread(server.Run); t.Start(); if (useAsyncSend) { client.SendMailAsync(msg).Wait(); } else { client.Send(msg); } if (useSevenBit || !useSmtpUTF8) { Assert.Equal(subjectBase64, server.Subject); } else { Assert.Equal(subjectText, server.Subject); } } finally { server.Stop(); } } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Branding.UIElementPersonalizationWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NodaTime; using System.Linq; using QuantConnect.Data; using QuantConnect.Util; using QuantConnect.Interfaces; using QuantConnect.Securities; using QuantConnect.Data.Market; using System.Collections.Generic; namespace QuantConnect.Algorithm { public partial class QCAlgorithm { /// <summary> /// Gets or sets the history provider for the algorithm /// </summary> public IHistoryProvider HistoryProvider { get; set; } /// <summary> /// Gets whether or not this algorithm is still warming up /// </summary> public bool IsWarmingUp { get; private set; } /// <summary> /// Sets the warm up period to the specified value /// </summary> /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param> public void SetWarmup(TimeSpan timeSpan) { SetWarmUp(timeSpan, null); } /// <summary> /// Sets the warm up period to the specified value /// </summary> /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param> public void SetWarmUp(TimeSpan timeSpan) { SetWarmup(timeSpan); } /// <summary> /// Sets the warm up period to the specified value /// </summary> /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param> /// <param name="resolution">The resolution to request</param> public void SetWarmup(TimeSpan timeSpan, Resolution? resolution) { if (_locked) { throw new InvalidOperationException("QCAlgorithm.SetWarmup(): This method cannot be used after algorithm initialized"); } _warmupBarCount = null; _warmupTimeSpan = timeSpan; _warmupResolution = resolution; } /// <summary> /// Sets the warm up period to the specified value /// </summary> /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param> /// <param name="resolution">The resolution to request</param> public void SetWarmUp(TimeSpan timeSpan, Resolution? resolution) { SetWarmup(timeSpan, resolution); } /// <summary> /// Sets the warm up period by resolving a start date that would send that amount of data into /// the algorithm. The highest (smallest) resolution in the securities collection will be used. /// For example, if an algorithm has minute and daily data and 200 bars are requested, that would /// use 200 minute bars. /// </summary> /// <param name="barCount">The number of data points requested for warm up</param> public void SetWarmup(int barCount) { SetWarmUp(barCount, null); } /// <summary> /// Sets the warm up period by resolving a start date that would send that amount of data into /// the algorithm. The highest (smallest) resolution in the securities collection will be used. /// For example, if an algorithm has minute and daily data and 200 bars are requested, that would /// use 200 minute bars. /// </summary> /// <param name="barCount">The number of data points requested for warm up</param> public void SetWarmUp(int barCount) { SetWarmup(barCount); } /// <summary> /// Sets the warm up period by resolving a start date that would send that amount of data into /// the algorithm. /// </summary> /// <param name="barCount">The number of data points requested for warm up</param> /// <param name="resolution">The resolution to request</param> public void SetWarmup(int barCount, Resolution? resolution) { if (_locked) { throw new InvalidOperationException("QCAlgorithm.SetWarmup(): This method cannot be used after algorithm initialized"); } _warmupTimeSpan = null; _warmupBarCount = barCount; _warmupResolution = resolution; } /// <summary> /// Sets the warm up period by resolving a start date that would send that amount of data into /// the algorithm. /// </summary> /// <param name="barCount">The number of data points requested for warm up</param> /// <param name="resolution">The resolution to request</param> public void SetWarmUp(int barCount, Resolution? resolution) { SetWarmup(barCount, resolution); } /// <summary> /// Sets <see cref="IAlgorithm.IsWarmingUp"/> to false to indicate this algorithm has finished its warm up /// </summary> public void SetFinishedWarmingUp() { IsWarmingUp = false; // notify the algorithm OnWarmupFinished(); } /// <summary> /// Message for exception that is thrown when the implicit conversion between symbol and string fails /// </summary> private readonly string _symbolEmptyErrorMessage = "Cannot create history for the given ticker. " + "Either explicitly use a symbol object to make the history request " + "or ensure the symbol has been added using the AddSecurity() method before making the history request."; /// <summary> /// Gets the history requests required for provide warm up data for the algorithm /// </summary> /// <returns></returns> public IEnumerable<HistoryRequest> GetWarmupHistoryRequests() { if (_warmupBarCount.HasValue) { return CreateBarCountHistoryRequests(Securities.Keys, _warmupBarCount.Value, _warmupResolution); } if (_warmupTimeSpan.HasValue) { var end = UtcTime.ConvertFromUtc(TimeZone); return CreateDateRangeHistoryRequests(Securities.Keys, end - _warmupTimeSpan.Value, end, _warmupResolution); } // if not warmup requested return nothing return Enumerable.Empty<HistoryRequest>(); } /// <summary> /// Get the history for all configured securities over the requested span. /// This will use the resolution and other subscription settings for each security. /// The symbols must exist in the Securities collection. /// </summary> /// <param name="span">The span over which to request data. This is a calendar span, so take into consideration weekends and such</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns> public IEnumerable<Slice> History(TimeSpan span, Resolution? resolution = null) { return History(Securities.Keys, Time - span, Time, resolution).Memoize(); } /// <summary> /// Get the history for all configured securities over the requested span. /// This will use the resolution and other subscription settings for each security. /// The symbols must exist in the Securities collection. /// </summary> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns> public IEnumerable<Slice> History(int periods, Resolution? resolution = null) { return History(Securities.Keys, periods, resolution).Memoize(); } /// <summary> /// Gets the historical data for all symbols of the requested type over the requested span. /// The symbol's configured values for resolution and fill forward behavior will be used /// The symbols must exist in the Securities collection. /// </summary> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<DataDictionary<T>> History<T>(TimeSpan span, Resolution? resolution = null) where T : IBaseData { return History<T>(Securities.Keys, span, resolution).Memoize(); } /// <summary> /// Gets the historical data for the specified symbols over the requested span. /// The symbols must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbols</typeparam> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, TimeSpan span, Resolution? resolution = null) where T : IBaseData { return History<T>(symbols, Time - span, Time, resolution).Memoize(); } /// <summary> /// Gets the historical data for the specified symbols. The exact number of bars will be returned for /// each symbol. This may result in some data start earlier/later than others due to when various /// exchanges are open. The symbols must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbols</typeparam> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null) where T : IBaseData { var requests = symbols.Select(x => { var config = GetMatchingSubscription(x, typeof(T)); if (config == null) return null; var exchange = GetExchangeHours(x); var res = GetResolution(x, resolution); var start = _historyRequestFactory.GetStartTimeAlgoTz(x, periods, res, exchange, config.DataTimeZone); return _historyRequestFactory.CreateHistoryRequest(config, start, Time, exchange, res); }); return History(requests.Where(x => x != null)).Get<T>().Memoize(); } /// <summary> /// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbols</typeparam> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null) where T : IBaseData { var requests = symbols.Select(x => { var config = GetMatchingSubscription(x, typeof(T)); if (config == null) return null; return _historyRequestFactory.CreateHistoryRequest(config, start, end, GetExchangeHours(x), resolution); }); return History(requests.Where(x => x != null)).Get<T>().Memoize(); } /// <summary> /// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbol</typeparam> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<T> History<T>(Symbol symbol, TimeSpan span, Resolution? resolution = null) where T : IBaseData { return History<T>(symbol, Time - span, Time, resolution).Memoize(); } /// <summary> /// Gets the historical data for the specified symbol. The exact number of bars will be returned. /// The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<TradeBar> History(Symbol symbol, int periods, Resolution? resolution = null) { if (symbol == null) throw new ArgumentException(_symbolEmptyErrorMessage); resolution = GetResolution(symbol, resolution); var marketHours = GetMarketHours(symbol); var start = _historyRequestFactory.GetStartTimeAlgoTz(symbol, periods, resolution.Value, marketHours.ExchangeHours, marketHours.DataTimeZone); return History(symbol, start, Time, resolution); } /// <summary> /// Gets the historical data for the specified symbol. The exact number of bars will be returned. /// The symbol must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbol</typeparam> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<T> History<T>(Symbol symbol, int periods, Resolution? resolution = null) where T : IBaseData { if (resolution == Resolution.Tick) throw new ArgumentException("History functions that accept a 'periods' parameter can not be used with Resolution.Tick"); var config = GetHistoryRequestConfig(symbol, typeof(T), resolution); resolution = GetResolution(symbol, resolution); var start = _historyRequestFactory.GetStartTimeAlgoTz(symbol, periods, resolution.Value, GetExchangeHours(symbol), config.DataTimeZone); return History<T>(symbol, start, Time, resolution).Memoize(); } /// <summary> /// Gets the historical data for the specified symbol between the specified dates. The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<T> History<T>(Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null) where T : IBaseData { var config = GetHistoryRequestConfig(symbol, typeof(T), resolution); var request = _historyRequestFactory.CreateHistoryRequest(config, start, end, GetExchangeHours(symbol), resolution); return History(request).Get<T>(symbol).Memoize(); } /// <summary> /// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<TradeBar> History(Symbol symbol, TimeSpan span, Resolution? resolution = null) { return History(symbol, Time - span, Time, resolution); } /// <summary> /// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<TradeBar> History(Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null) { var securityType = symbol.ID.SecurityType; if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd) { Error("Calling History<TradeBar> method on a Forex or CFD security will return an empty result. Please use the generic version with QuoteBar type parameter."); } var resolutionToUse = resolution ?? GetResolution(symbol, resolution); if (resolutionToUse == Resolution.Tick) { throw new InvalidOperationException("Calling History<TradeBar> method with Resolution.Tick will return an empty result." + " Please use the generic version with Tick type parameter or provide a list of Symbols to use the Slice history request API."); } return History(new[] { symbol }, start, end, resolutionToUse).Get(symbol).Memoize(); } /// <summary> /// Gets the historical data for the specified symbols over the requested span. /// The symbol's configured values for resolution and fill forward behavior will be used /// The symbols must exist in the Securities collection. /// </summary> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, TimeSpan span, Resolution? resolution = null) { return History(symbols, Time - span, Time, resolution).Memoize(); } /// <summary> /// Gets the historical data for the specified symbols. The exact number of bars will be returned for /// each symbol. This may result in some data start earlier/later than others due to when various /// exchanges are open. The symbols must exist in the Securities collection. /// </summary> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null) { if (resolution == Resolution.Tick) throw new ArgumentException("History functions that accept a 'periods' parameter can not be used with Resolution.Tick"); return History(CreateBarCountHistoryRequests(symbols, periods, resolution)).Memoize(); } /// <summary> /// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection. /// </summary> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <param name="fillForward">True to fill forward missing data, false otherwise</param> /// <param name="extendedMarket">True to include extended market hours data, false otherwise</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarket = null) { return History(CreateDateRangeHistoryRequests(symbols, start, end, resolution, fillForward, extendedMarket)).Memoize(); } /// <summary> /// Executes the specified history request /// </summary> /// <param name="request">the history request to execute</param> /// <returns>An enumerable of slice satisfying the specified history request</returns> public IEnumerable<Slice> History(HistoryRequest request) { return History(new[] { request }).Memoize(); } /// <summary> /// Executes the specified history requests /// </summary> /// <param name="requests">the history requests to execute</param> /// <returns>An enumerable of slice satisfying the specified history request</returns> public IEnumerable<Slice> History(IEnumerable<HistoryRequest> requests) { return History(requests, TimeZone).Memoize(); } /// <summary> /// Yields data to warmup a security for all it's subscribed data types /// </summary> /// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param> /// <returns>Securities historical data</returns> public IEnumerable<BaseData> GetLastKnownPrices(Security security) { return GetLastKnownPrices(security.Symbol); } /// <summary> /// Yields data to warmup a security for all it's subscribed data types /// </summary> /// <param name="symbol">The symbol we want to get seed data for</param> /// <returns>Securities historical data</returns> public IEnumerable<BaseData> GetLastKnownPrices(Symbol symbol) { if (symbol.IsCanonical() || HistoryProvider == null) { return Enumerable.Empty<BaseData>(); } var result = new Dictionary<TickType, BaseData>(); // For speed and memory usage, use Resolution.Minute as the minimum resolution var resolution = (Resolution)Math.Max((int)Resolution.Minute, (int)SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).GetHighestResolution()); Func<int, bool> requestData = period => { var historyRequests = CreateBarCountHistoryRequests(new[] { symbol }, period, resolution) .Select(request => { // force no fill forward behavior request.FillForwardResolution = null; return request; }) // request only those tick types we didn't get the data we wanted .Where(request => !result.ContainsKey(request.TickType)) .ToList(); foreach (var slice in History(historyRequests)) { for (var i = 0; i < historyRequests.Count; i++) { var historyRequest = historyRequests[i]; var data = slice.Get(historyRequest.DataType); if (data.ContainsKey(symbol)) { // keep the last data point per tick type result[historyRequest.TickType] = (BaseData)data[symbol]; } } } // true when all history requests tick types have a data point return historyRequests.All(request => result.ContainsKey(request.TickType)); }; if (!requestData(5)) { // If the first attempt to get the last know price returns null, it maybe the case of an illiquid security. // We increase the look-back period for this case accordingly to the resolution to cover 3 trading days var periods = resolution == Resolution.Daily ? 3 : resolution == Resolution.Hour ? 24 : 1440; requestData(periods); } // return the data ordered by time ascending return result.Values.OrderBy(data => data.Time); } /// <summary> /// Get the last known price using the history provider. /// Useful for seeding securities with the correct price /// </summary> /// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param> /// <returns>A single <see cref="BaseData"/> object with the last known price</returns> [Obsolete("This method is obsolete please use 'GetLastKnownPrices' which will return the last data point" + " for each type associated with the requested security")] public BaseData GetLastKnownPrice(Security security) { return GetLastKnownPrices(security.Symbol) // since we are returning a single data point let's respect order .OrderByDescending(data => GetTickTypeOrder(data.Symbol.SecurityType, LeanData.GetCommonTickTypeForCommonDataTypes(data.GetType(), data.Symbol.SecurityType))) .LastOrDefault(); } /// <summary> /// Centralized logic to get a configuration for a symbol, a data type and a resolution /// </summary> private SubscriptionDataConfig GetHistoryRequestConfig(Symbol symbol, Type requestedType, Resolution? resolution = null) { if (symbol == null) throw new ArgumentException(_symbolEmptyErrorMessage); // verify the types match var config = GetMatchingSubscription(symbol, requestedType, resolution); if (config == null) { var actualType = GetMatchingSubscription(symbol, typeof(BaseData)).Type; var message = $"The specified security is not of the requested type. Symbol: {symbol} Requested Type: {requestedType.Name} Actual Type: {actualType}"; if (resolution.HasValue) { message += $" Requested Resolution.{resolution.Value}"; } throw new ArgumentException(message); } return config; } private IEnumerable<Slice> History(IEnumerable<HistoryRequest> requests, DateTimeZone timeZone) { var sentMessage = false; // filter out any universe securities that may have made it this far var filteredRequests = requests.Where(hr => !UniverseManager.ContainsKey(hr.Symbol)).ToList(); for (var i = 0; i < filteredRequests.Count; i++) { var request = filteredRequests[i]; // prevent future requests if (request.EndTimeUtc > UtcTime) { var endTimeUtc = UtcTime; var startTimeUtc = request.StartTimeUtc; if (request.StartTimeUtc > request.EndTimeUtc) { startTimeUtc = request.EndTimeUtc; } filteredRequests[i] = new HistoryRequest(startTimeUtc, endTimeUtc, request.DataType, request.Symbol, request.Resolution, request.ExchangeHours, request.DataTimeZone, request.FillForwardResolution, request.IncludeExtendedMarketHours, request.IsCustomData, request.DataNormalizationMode, request.TickType); if (!sentMessage) { sentMessage = true; Debug("Request for future history modified to end now."); } } } // filter out future data to prevent look ahead bias return ((IAlgorithm)this).HistoryProvider.GetHistory(filteredRequests, timeZone); } /// <summary> /// Helper method to create history requests from a date range /// </summary> private IEnumerable<HistoryRequest> CreateDateRangeHistoryRequests(IEnumerable<Symbol> symbols, DateTime startAlgoTz, DateTime endAlgoTz, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarket = null) { return symbols.Where(x => !x.IsCanonical()).SelectMany(x => { var requests = new List<HistoryRequest>(); foreach (var config in GetMatchingSubscriptions(x, typeof(BaseData), resolution)) { var request = _historyRequestFactory.CreateHistoryRequest(config, startAlgoTz, endAlgoTz, GetExchangeHours(x), resolution); // apply overrides var res = GetResolution(x, resolution); if (fillForward.HasValue) request.FillForwardResolution = fillForward.Value ? res : (Resolution?)null; if (extendedMarket.HasValue) request.IncludeExtendedMarketHours = extendedMarket.Value; requests.Add(request); } return requests; }); } /// <summary> /// Helper methods to create a history request for the specified symbols and bar count /// </summary> private IEnumerable<HistoryRequest> CreateBarCountHistoryRequests(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null) { return symbols.Where(x => !x.IsCanonical()).SelectMany(x => { var res = GetResolution(x, resolution); var exchange = GetExchangeHours(x); var configs = GetMatchingSubscriptions(x, typeof(BaseData), resolution).ToList(); if (!configs.Any()) { return Enumerable.Empty<HistoryRequest>(); } var start = _historyRequestFactory.GetStartTimeAlgoTz(x, periods, res, exchange, configs.First().DataTimeZone); var end = Time; return configs.Select(config => _historyRequestFactory.CreateHistoryRequest(config, start, end, exchange, res)); }); } private SubscriptionDataConfig GetMatchingSubscription(Symbol symbol, Type type, Resolution? resolution = null) { // find the first subscription matching the requested type with a higher resolution than requested return GetMatchingSubscriptions(symbol, type, resolution).FirstOrDefault(); } private int GetTickTypeOrder(SecurityType securityType, TickType tickType) { return SubscriptionManager.AvailableDataTypes[securityType].IndexOf(tickType); } private IEnumerable<SubscriptionDataConfig> GetMatchingSubscriptions(Symbol symbol, Type type, Resolution? resolution = null) { var matchingSubscriptions = SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(symbol, includeInternalConfigs:true) // find all subscriptions matching the requested type with a higher resolution than requested .OrderByDescending(s => s.Resolution) // lets make sure to respect the order of the data types .ThenByDescending(config => GetTickTypeOrder(config.SecurityType, config.TickType)) .ThenBy(config => config.IsInternalFeed ? 1 : 0) .Where(s => SubscriptionDataConfigTypeFilter(type, s.Type)) .ToList(); // we use the subscription manager registered configurations here, we can not rely on the Securities collection // since this might be called when creating a security and warming it up if (matchingSubscriptions.Count != 0) { if (resolution.HasValue && (resolution == Resolution.Daily || resolution == Resolution.Hour) && symbol.SecurityType == SecurityType.Equity) { // for Daily and Hour resolution, for equities, we have to // filter out any existing subscriptions that could be of Quote type // This could happen if they were Resolution.Minute/Second/Tick return matchingSubscriptions.Where(s => s.TickType != TickType.Quote); } return matchingSubscriptions; } else { var entry = MarketHoursDatabase.GetEntry(symbol, new []{ type }); resolution = GetResolution(symbol, resolution); return SubscriptionManager .LookupSubscriptionConfigDataTypes(symbol.SecurityType, resolution.Value, symbol.IsCanonical()) .Where(tuple => SubscriptionDataConfigTypeFilter(type, tuple.Item1)) .Select(x => new SubscriptionDataConfig( x.Item1, symbol, resolution.Value, entry.DataTimeZone, entry.ExchangeHours.TimeZone, UniverseSettings.FillForward, UniverseSettings.ExtendedMarketHours, true, false, x.Item2, true, UniverseSettings.DataNormalizationMode)); } } /// <summary> /// Helper method to determine if the provided config type passes the filter of the target type /// </summary> /// <remarks>If the target type is <see cref="BaseData"/>, <see cref="OpenInterest"/> config types will return false. /// This is useful to filter OpenInterest by default from history requests unless it's explicitly requested</remarks> private bool SubscriptionDataConfigTypeFilter(Type targetType, Type configType) { var targetIsGenericType = targetType == typeof(BaseData); return targetType.IsAssignableFrom(configType) && (!targetIsGenericType || configType != typeof(OpenInterest)); } private SecurityExchangeHours GetExchangeHours(Symbol symbol) { return GetMarketHours(symbol).ExchangeHours; } private MarketHoursDatabase.Entry GetMarketHours(Symbol symbol) { var hoursEntry = MarketHoursDatabase.GetEntry(symbol.ID.Market, symbol, symbol.ID.SecurityType); // user can override the exchange hours in algorithm, i.e. HistoryAlgorithm Security security; if (Securities.TryGetValue(symbol, out security)) { return new MarketHoursDatabase.Entry(hoursEntry.DataTimeZone, security.Exchange.Hours); } return hoursEntry; } private Resolution GetResolution(Symbol symbol, Resolution? resolution) { Security security; if (Securities.TryGetValue(symbol, out security)) { return resolution ?? SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(symbol) .GetHighestResolution(); } else { return resolution ?? UniverseSettings.Resolution; } } } }
/* * 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 log4net; using Nini.Config; using OpenSim.Framework; using OpenMetaverse; using OpenSim.Region.PhysicsModules.SharedBase; /* * Steps to add a new prioritization policy: * * - Add a new value to the UpdatePrioritizationSchemes enum. * - Specify this new value in the [InterestManagement] section of your * OpenSim.ini. The name in the config file must match the enum value name * (although it is not case sensitive). * - Write a new GetPriorityBy*() method in this class. * - Add a new entry to the switch statement in GetUpdatePriority() that calls * your method. */ namespace OpenSim.Region.Framework.Scenes { public enum UpdatePrioritizationSchemes { Time = 0, Distance = 1, SimpleAngularDistance = 2, FrontBack = 3, BestAvatarResponsiveness = 4, } public class Prioritizer { private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; public Prioritizer(Scene scene) { m_scene = scene; } /// <summary> /// Returns the priority queue into which the update should be placed. Updates within a /// queue will be processed in arrival order. There are currently 12 priority queues /// implemented in PriorityQueue class in LLClientView. Queue 0 is generally retained /// for avatar updates. The fair queuing discipline for processing the priority queues /// assumes that the number of entities in each priority queues increases exponentially. /// So for example... if queue 1 contains all updates within 10m of the avatar or camera /// then queue 2 at 20m is about 3X bigger in space & about 3X bigger in total number /// of updates. /// </summary> public uint GetUpdatePriority(IClientAPI client, ISceneEntity entity) { // If entity is null we have a serious problem if (entity == null) { m_log.WarnFormat("[PRIORITIZER] attempt to prioritize null entity"); throw new InvalidOperationException("Prioritization entity not defined"); } // If this is an update for our own avatar give it the highest priority if (client.AgentId == entity.UUID) return 0; uint priority; // HACK return GetPriorityByBestAvatarResponsiveness(client, entity); switch (m_scene.UpdatePrioritizationScheme) { case UpdatePrioritizationSchemes.Time: priority = GetPriorityByTime(client, entity); break; case UpdatePrioritizationSchemes.Distance: priority = GetPriorityByDistance(client, entity); break; case UpdatePrioritizationSchemes.SimpleAngularDistance: priority = GetPriorityByDistance(client, entity); // TODO: Reimplement SimpleAngularDistance break; case UpdatePrioritizationSchemes.FrontBack: priority = GetPriorityByFrontBack(client, entity); break; case UpdatePrioritizationSchemes.BestAvatarResponsiveness: priority = GetPriorityByBestAvatarResponsiveness(client, entity); break; default: throw new InvalidOperationException("UpdatePrioritizationScheme not defined."); } return priority; } private uint GetPriorityByTime(IClientAPI client, ISceneEntity entity) { // And anything attached to this avatar gets top priority as well if (entity is SceneObjectPart) { SceneObjectPart sop = (SceneObjectPart)entity; if (sop.ParentGroup.IsAttachment && client.AgentId == sop.ParentGroup.AttachedAvatar) return 1; } return PriorityQueue.NumberOfImmediateQueues; // first queue past the immediate queues } private uint GetPriorityByDistance(IClientAPI client, ISceneEntity entity) { // And anything attached to this avatar gets top priority as well if (entity is SceneObjectPart) { SceneObjectPart sop = (SceneObjectPart)entity; if (sop.ParentGroup.IsAttachment && client.AgentId == sop.ParentGroup.AttachedAvatar) return 1; } return ComputeDistancePriority(client,entity,false); } private uint GetPriorityByFrontBack(IClientAPI client, ISceneEntity entity) { // And anything attached to this avatar gets top priority as well if (entity is SceneObjectPart) { SceneObjectPart sop = (SceneObjectPart)entity; if (sop.ParentGroup.IsAttachment && client.AgentId == sop.ParentGroup.AttachedAvatar) return 1; } return ComputeDistancePriority(client,entity,true); } private uint GetPriorityByBestAvatarResponsiveness(IClientAPI client, ISceneEntity entity) { uint pqueue = 2; // keep compiler happy ScenePresence presence = m_scene.GetScenePresence(client.AgentId); if (presence != null) { // All avatars other than our own go into pqueue 1 if (entity is ScenePresence) return 1; if (entity is SceneObjectPart) { // Attachments are high priority, if (((SceneObjectPart)entity).ParentGroup.IsAttachment) return 2; pqueue = ComputeDistancePriority(client, entity, false); // Non physical prims are lower priority than physical prims PhysicsActor physActor = ((SceneObjectPart)entity).ParentGroup.RootPart.PhysActor; if (physActor == null || !physActor.IsPhysical) pqueue++; } } else pqueue = ComputeDistancePriority(client, entity, false); return pqueue; } private uint ComputeDistancePriority(IClientAPI client, ISceneEntity entity, bool useFrontBack) { // Get this agent's position ScenePresence presence = m_scene.GetScenePresence(client.AgentId); if (presence == null) { // this shouldn't happen, it basically means that we are prioritizing // updates to send to a client that doesn't have a presence in the scene // seems like there's race condition here... // m_log.WarnFormat("[PRIORITIZER] attempt to use agent {0} not in the scene",client.AgentId); // throw new InvalidOperationException("Prioritization agent not defined"); return PriorityQueue.NumberOfQueues - 1; } // Use group position for child prims, since we are putting child prims in // the same queue with the root of the group, the root prim (which goes into // the queue first) should always be sent first, no need to adjust child prim // priorities Vector3 entityPos = entity.AbsolutePosition; if (entity is SceneObjectPart) { SceneObjectGroup group = (entity as SceneObjectPart).ParentGroup; entityPos = group.AbsolutePosition; } // Use the camera position for local agents and avatar position for remote agents // Why would I want that? They could be camming but I still see them at the // avatar position, so why should I update them as if they were at their // camera positions? Makes no sense! // TODO: Fix this mess //Vector3 presencePos = (presence.IsChildAgent) ? // presence.AbsolutePosition : // presence.CameraPosition; Vector3 presencePos = presence.AbsolutePosition; // Compute the distance... double distance = Vector3.Distance(presencePos, entityPos); // And convert the distance to a priority queue, this computation gives queues // at 10, 20, 40, 80, 160, 320, 640, and 1280m uint pqueue = PriorityQueue.NumberOfImmediateQueues + 1; // reserve attachments queue uint queues = PriorityQueue.NumberOfQueues - PriorityQueue.NumberOfImmediateQueues; /* for (int i = 0; i < queues - 1; i++) { if (distance < 30 * Math.Pow(2.0,i)) break; pqueue++; } */ if (distance > 10f) { float tmp = (float)Math.Log((double)distance) * 1.4426950408889634073599246810019f - 3.3219280948873623478703194294894f; // for a map identical to original: // now // 1st constant is 1/(log(2)) (natural log) so we get log2(distance) // 2st constant makes it be log2(distance/10) pqueue += (uint)tmp; if (pqueue > queues - 1) pqueue = queues - 1; } // If this is a root agent, then determine front & back // Bump up the priority queue (drop the priority) for any objects behind the avatar if (useFrontBack && ! presence.IsChildAgent) { // Root agent, decrease priority for objects behind us Vector3 camPosition = presence.CameraPosition; Vector3 camAtAxis = presence.CameraAtAxis; // Plane equation float d = -Vector3.Dot(camPosition, camAtAxis); float p = Vector3.Dot(camAtAxis, entityPos) + d; if (p < 0.0f) pqueue++; } return pqueue; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Worker; using Microsoft.VisualStudio.Services.Agent.Worker.LegacyTestResults; using TestRunContext = Microsoft.TeamFoundation.TestClient.PublishTestResults.TestRunContext; using Moq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using Xunit; namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker.Results { public class CTestResultReaderTests : IDisposable { private Mock<IExecutionContext> _ec; private static CTestResultReader _cTestReader; private static TestRunData _testRunData; private static string _fileName; private static string _cResultsToBeRead; [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void ResultsWithoutMandatoryFieldsAreSkippedCTest() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultsWithoutMandatoryFields; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.NotNull(_testRunData); Assert.Equal(0, _testRunData.Results.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void PublishBasicCResultsXml() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.NotNull(_testRunData); Assert.Equal(6, _testRunData.Results.Length); Assert.Equal(3, _testRunData.Results.Count(r => r.Outcome.Equals("Passed"))); Assert.Equal(2, _testRunData.Results.Count(r => r.Outcome.Equals("Failed"))); Assert.Equal(1, _testRunData.Results.Count(r => r.Outcome.Equals("NotExecuted"))); Assert.Equal("CTest Test Run configuration platform", _testRunData.Name); Assert.Equal("releaseUri", _testRunData.ReleaseUri); Assert.Equal("releaseEnvironmentUri", _testRunData.ReleaseEnvironmentUri); Assert.Equal("owner", _testRunData.Results[0].RunBy.DisplayName); Assert.Equal("owner", _testRunData.Results[0].Owner.DisplayName); Assert.Equal("Completed", _testRunData.Results[0].State); Assert.Equal("./libs/MgmtVisualization/tests/LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback", _testRunData.Results[0].AutomatedTestName); Assert.Equal("./libs/MgmtVisualization/tests", _testRunData.Results[0].AutomatedTestStorage); Assert.Equal("LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback", _testRunData.Results[0].TestCaseTitle); Assert.Equal(null, _testRunData.Results[0].AutomatedTestId); Assert.Equal(null, _testRunData.Results[0].AutomatedTestTypeId); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyTestRunDurationCTest() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); var timeSpan = DateTime.Parse(_testRunData.CompleteDate) - DateTime.Parse(_testRunData.StartDate); Assert.Equal(382, timeSpan.TotalSeconds); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyTestCaseDurationWhenTestCaseTimeIsInSeconds() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); var time = TimeSpan.FromMilliseconds(_testRunData.Results[0].DurationInMs); Assert.Equal(0.074, time.TotalSeconds); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyRunTypeIsSet() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXml; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.Equal(CTestResultReader.ParserName, _testRunData.Results[0].AutomatedTestType); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyPublishingStandardLogs() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXmlWithOneTest; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.NotNull(_testRunData); Assert.Equal(1, _testRunData.Results.Length); Assert.Equal("output : [----------] Global test environment set-up.", _testRunData.Results[0].AttachmentData.ConsoleLog); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyTestCaseStartDate() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXmlWithOneTest; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.Equal(_testRunData.StartDate, _testRunData.Results[0].StartedDate.ToString("o")); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyLastTestCaseEndDateNotGreaterThanTestRunTotalTime() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXmlWithOneTest; ReadResults(); var testCaseCompletedDate = _testRunData.Results[0].CompletedDate; var testRunCompletedDate = _testRunData.Results[0].StartedDate .AddTicks(DateTime.Parse(_testRunData.CompleteDate).Ticks); Assert.True(testCaseCompletedDate <= testRunCompletedDate, "first test case end should be within test run completed time"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyCTestReadResultsDoesNotFailWithoutStartTime() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXmlWithoutStartTime; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.Equal(_testRunData.Results.Length, 1); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyCTestReadResultsDoesNotFailWithoutFinishTime() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXmlWithoutEndTime; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.Equal(_testRunData.Results.Length, 1); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyStackTraceForFailedTest() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXmlWithFailedTest; string expectedStackTrace = "-- Download of file://\\abc-mang.md5.txtfailed with message: [37]\"couldn't read a file:// file\"CMake Error at modules/Logging.cmake:121 (message):test BAR_wget_file succeed: result is \"OFF\" instead of \"ON\"Call Stack (most recent call first):modules/Test.cmake:74 (BAR_msg_fatal)modules/testU/WGET-testU-noMD5.cmake:14 (BAR_check_equal)"; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.Equal(expectedStackTrace, _testRunData.Results[0].StackTrace); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyTestRunTimeIsEmptyIfTimestampIsNotParseable() { SetupMocks(); _cResultsToBeRead = _cTestResultXmlWithNegativeTimeStamp; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.Equal(string.Empty, _testRunData.StartDate); Assert.Equal(string.Empty, _testRunData.CompleteDate); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyTestRunTimeIsSetToZeroIfDurationIsNegative() { SetupMocks(); _cResultsToBeRead = _cTestResultXmlWithNegativeDuration; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.Equal(0, _testRunData.Results[0].DurationInMs); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishResults")] public void VerifyTestRunTimeIsSetToUTCTime() { SetupMocks(); _cResultsToBeRead = _cTestSimpleResultXmlWithLocalTime; ReadResults(new TestRunContext("owner", "platform", "configuration", 1, "buildUri", "releaseUri", "releaseEnvironmentUri")); Assert.Equal("2019-01-03T12:21:19.0000000Z", _testRunData.StartDate); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "TestHostContext")] private void SetupMocks([CallerMemberName] string name = "") { TestHostContext hc = new TestHostContext(this, name); _ec = new Mock<IExecutionContext>(); List<string> warnings; var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings); _ec.Setup(x => x.Variables).Returns(variables); } private void ReadResults(TestRunContext runContext = null) { _fileName = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); File.WriteAllText(_fileName, _cResultsToBeRead); _cTestReader = new CTestResultReader(); _testRunData = _cTestReader.ReadResults(_ec.Object, _fileName, runContext); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { try { File.Delete(_fileName); } catch { } } } #region Constants private const string _cTestSimpleResultsWithoutMandatoryFields = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Site BuildName=\"(empty)\" BuildStamp=\"20180515-1731-Experimental\" Name=\"(empty)\" Generator=\"ctest-3.11.0\" " + "CompilerName=\"\" CompilerVersion=\"\" OSName=\"Linux\" Hostname=\"3tnavBuild\" OSRelease=\"4.4.0-116-generic\" " + "OSVersion=\"#140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018\" OSPlatform=\"x86_64\" Is64Bits=\"1\">" + "<Testing>" + "<StartDateTime>May 15 10:31 PDT</StartDateTime>" + "<StartTestTime>1526405497</StartTestTime>" + "<TestList>" + "<Test>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Test>" + "<Test>./tools/simulator/test/simulator.SimulatorTest.readEventFile_mediaDetectedEvent_oneSignalEmitted</Test>" + "</TestList>" + "<Test Status =\"passed\">" + "<Path>./libs/MgmtVisualization/tests</Path>" + "<FullName>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</FullName>" + "<FullCommandLine>/home/ctc/jenkins/workspace/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</FullCommandLine>" + "</Test>" + "<Test Status =\"notrun\">" + "<Name>simulator.SimulatorTest.readEventFile_mediaDetectedEvent_oneSignalEmitted</Name>" + "<Path>./tools/simulator/test</Path>" + "<FullCommandLine></FullCommandLine>" + "</Test>" + "<EndDateTime>May 15 10:37 PDT</EndDateTime>" + "<EndTestTime>1526405879</EndTestTime>" + "<ElapsedMinutes>6</ElapsedMinutes>" + "</Testing>" + "</Site>"; private const string _cTestSimpleResultXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Site BuildName=\"(empty)\" BuildStamp=\"20180515-1731-Experimental\" Name=\"(empty)\" Generator=\"ctest-3.11.0\" " + "CompilerName=\"\" CompilerVersion=\"\" OSName=\"Linux\" Hostname=\"3tnavBuild\" OSRelease=\"4.4.0-116-generic\" " + "OSVersion=\"#140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018\" OSPlatform=\"x86_64\" Is64Bits=\"1\">" + "<Testing>" + "<StartDateTime>May 15 10:31 PDT</StartDateTime>" + "<StartTestTime>1526405497</StartTestTime>" + "<TestList>" + "<Test>./libs/MgmtVisualization/tests/LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback</Test>" + "<Test>./tools/simulator/test/simulator.SimulatorTest.readEventFile_mediaDetectedEvent_oneSignalEmitted</Test>" + "</TestList>" + "<Test Status =\"passed\">" + "<Name>LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback</Name>" + "<Path>./libs/MgmtVisualization/tests</Path>" + "<FullName>./libs/MgmtVisualization/tests/LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback</FullName>" + "<FullCommandLine>D:/a/r1/a/libs/MgmtVisualization/tests/MgmtVisualizationResultsAPI \"--gtest_filter=LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback\"</FullCommandLine>" + "<Results>" + "<NamedMeasurement type =\"numeric/double\" name=\"Execution Time\">" + "<Value>0.074303</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"numeric/double\" name=\"Processors\">" + "<Value>1</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Completion Status\">" + "<Value>Completed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Command Line\">" + "<Value>/home/ctc/jenkins/workspace/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>output : [----------] Global test environment set-up.</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<Test Status =\"notrun\">" + "<Name>simulator.SimulatorTest.readEventFile_mediaDetectedEvent_oneSignalEmitted</Name>" + "<Path>./tools/simulator/test</Path>" + "<FullName>./tools/simulator/test/simulator.SimulatorTest.readEventFile_mediaDetectedEvent_oneSignalEmitted</FullName>" + "<FullCommandLine></FullCommandLine>" + "<Results>" + "<NamedMeasurement type =\"numeric/double\" name=\"Processors\">" + "<Value>1</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Completion Status\">" + "<Value>Disabled</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Command Line\">" + "<Value></Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>Disabled</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<Test Status=\"passed\">" + "<Name>test_cgreen_run_named_test</Name>" + "<Path>./tests</Path>" + "<FullName>./tests/test_cgreen_run_named_test</FullName>" + "<FullCommandLine>/var/lib/jenkins/workspace/Cgreen-thoni56/build/build-c/tests/test_cgreen_c &quot;integer_one_should_assert_true&quot;</FullCommandLine>" + "<Results>" + "<NamedMeasurement type=\"numeric/double\" name=\"Execution Time\"><Value>0.00615707</Value></NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Completion Status\"><Value>Completed</Value></NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Command Line\"><Value>/var/lib/jenkins/workspace/Cgreen-thoni56/build/build-c/tests/test_cgreen_c &quot;integer_one_should_assert_true&quot;</Value></NamedMeasurement>" + "<Measurement>" + "<Value>Running &quot;all_c_tests&quot; (136 tests)..." + "Completed &quot;assertion_tests&quot;: 1 pass, 0 failures, 0 exceptions in 0ms." + "Completed &quot;all_c_tests&quot;: 1 pass, 0 failures, 0 exceptions in 0ms." + "</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<Test Status=\"passed\">" + "<Name>runner_test_cgreen_c</Name>" + "<Path>./tests</Path>" + "<FullName>./tests/runner_test_cgreen_c</FullName>" + "<FullCommandLine>D:/a/r1/a/Cgreen-thoni56/build/build-c/tools/cgreen-runner &quot;-x&quot; &quot;TEST&quot; &quot;libcgreen_c_tests.so&quot;</FullCommandLine>" + "<Results>" + "<NamedMeasurement type=\"numeric/double\" name=\"Execution Time\"><Value>0.499399</Value></NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Completion Status\"><Value>Completed</Value></NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Command Line\"><Value>/var/lib/jenkins/workspace/Cgreen-thoni56/build/build-c/tools/cgreen-runner &quot;-x&quot; &quot;TEST&quot; &quot;libcgreen_c_tests.so&quot;</Value></NamedMeasurement>" + "<Measurement>" + "<Value> CGREEN EXCEPTION: Too many assertions within a single test." + "</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<Test Status=\"failed\">" + "<Name>WGET-testU-MD5-fail</Name>" + "<Path>E_/foo/sources</Path>" + "<FullName>E_/foo/sources/WGET-testU-MD5-fail</FullName>" + "<FullCommandLine>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe &quot;-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET&quot;" + "&quot;-P&quot; &quot;E:/foo/sources/modules/testU/WGET-testU-MD5-fail.cmake&quot;</FullCommandLine>" + "<Results>" + "<NamedMeasurement type=\"text/string\" name=\"Exit Code\">" + "<Value>Failed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Exit Value\">" + "<Value>0</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"numeric/double\" name=\"Execution Time\">" + "<Value>0.0760078</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Completion Status\">" + "<Value>Completed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Command Line\">" + "<Value>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe &quot;-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET&quot;" + "&quot;-P&quot; &quot;E:/foo/sources/modules/testU/WGET-testU-MD5-fail.cmake&quot;</Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>-- Download of file://\\abc-mang.md5.txt" + "failed with message: [37]&quot;couldn&apos;t read a file:// file&quot;" + "</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<Test Status=\"failed\">" + "<Name>WGET-testU-noMD5</Name>" + "<Path>E_/foo/sources</Path>" + "<FullName>E_/foo/sources/WGET-testU-noMD5</FullName>" + "<FullCommandLine>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe &quot;-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET&quot;" + "&quot;-P&quot; &quot;E:/foo/sources/modules/testU/WGET-testU-noMD5.cmake&quot;</FullCommandLine>" + "<Results>" + "<NamedMeasurement type=\"text/string\" name=\"Exit Code\">" + "<Value>Failed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Exit Value\">" + "<Value>1</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"numeric/double\" name=\"Execution Time\">" + "<Value>0.0820084</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Completion Status\">" + "<Value>Completed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Command Line\">" + "<Value>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe &quot;-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET&quot;" + "&quot;-P&quot; &quot;E:/foo/sources/modules/testU/WGET-testU-noMD5.cmake&quot;</Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>-- Download of file://\\abc-mang.md5.txt" + "failed with message: [37]&quot;couldn&apos;t read a file:// file&quot;" + "CMake Error at modules/Logging.cmake:121 (message):" + "" + "" + "test BAR_wget_file succeed: result is &quot;OFF&quot; instead of &quot;ON&quot;" + "" + "Call Stack (most recent call first):" + "modules/Test.cmake:74 (BAR_msg_fatal)" + "modules/testU/WGET-testU-noMD5.cmake:14 (BAR_check_equal)" + "" + "" + "</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<EndDateTime>May 15 10:37 PDT</EndDateTime>" + "<EndTestTime>1526405879</EndTestTime>" + "<ElapsedMinutes>6</ElapsedMinutes>" + "</Testing>" + "</Site>"; private const string _cTestSimpleResultXmlWithOneTest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Site BuildName=\"(empty)\" BuildStamp=\"20180515-1731-Experimental\" Name=\"(empty)\" Generator=\"ctest-3.11.0\" " + "CompilerName=\"\" CompilerVersion=\"\" OSName=\"Linux\" Hostname=\"3tnavBuild\" OSRelease=\"4.4.0-116-generic\" " + "OSVersion=\"#140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018\" OSPlatform=\"x86_64\" Is64Bits=\"1\">" + "<Testing>" + "<StartDateTime>May 15 10:31 PDT</StartDateTime>" + "<StartTestTime>1526405497</StartTestTime>" + "<TestList>" + "<Test>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Test>" + "</TestList>" + "<Test Status =\"passed\">" + "<Name>loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Name>" + "<Path>./libs/MgmtVisualization/tests</Path>" + "<FullName>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</FullName>" + "<FullCommandLine>D:/a/r1/a/libs/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</FullCommandLine>" + "<Results>" + "<NamedMeasurement type =\"numeric/double\" name=\"Execution Time\">" + "<Value>0.0074303</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"numeric/double\" name=\"Processors\">" + "<Value>1</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Completion Status\">" + "<Value>Completed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Command Line\">" + "<Value>D:/a/r1/a/libs/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>output : [----------] Global test environment set-up.</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<EndDateTime>May 15 10:37 PDT</EndDateTime>" + "<EndTestTime>1526405879</EndTestTime>" + "<ElapsedMinutes>6</ElapsedMinutes>" + "</Testing>" + "</Site>"; private const string _cTestSimpleResultXmlWithFailedTest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Site BuildName=\"(empty)\" BuildStamp=\"20180515-1731-Experimental\" Name=\"(empty)\" Generator=\"ctest-3.11.0\" " + "CompilerName=\"\" CompilerVersion=\"\" OSName=\"Linux\" Hostname=\"3tnavBuild\" OSRelease=\"4.4.0-116-generic\" " + "OSVersion=\"#140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018\" OSPlatform=\"x86_64\" Is64Bits=\"1\">" + "<Testing>" + "<StartDateTime>May 15 10:31 PDT</StartDateTime>" + "<StartTestTime>1526405497</StartTestTime>" + "<TestList>" + "<Test>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Test>" + "</TestList>" + "<Test Status=\"failed\">" + "<Name>WGET-testU-noMD5</Name>" + "<Path>E_/foo/sources</Path>" + "<FullName>E_/foo/sources/WGET-testU-noMD5</FullName>" + "<FullCommandLine>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe &quot;-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET&quot;" + "&quot;-P&quot; &quot;E:/foo/sources/modules/testU/WGET-testU-noMD5.cmake&quot;</FullCommandLine>" + "<Results>" + "<NamedMeasurement type=\"text/string\" name=\"Exit Code\">" + "<Value>Failed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Exit Value\">" + "<Value>1</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"numeric/double\" name=\"Execution Time\">" + "<Value>0.0820084</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Completion Status\">" + "<Value>Completed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Command Line\">" + "<Value>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe &quot;-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET&quot;" + "&quot;-P&quot; &quot;E:/foo/sources/modules/testU/WGET-testU-noMD5.cmake&quot;</Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>-- Download of file://\\abc-mang.md5.txt" + "failed with message: [37]&quot;couldn&apos;t read a file:// file&quot;" + "CMake Error at modules/Logging.cmake:121 (message):" + "" + "" + "test BAR_wget_file succeed: result is &quot;OFF&quot; instead of &quot;ON&quot;" + "" + "Call Stack (most recent call first):" + "modules/Test.cmake:74 (BAR_msg_fatal)" + "modules/testU/WGET-testU-noMD5.cmake:14 (BAR_check_equal)" + "" + "" + "</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<EndDateTime>May 15 10:37 PDT</EndDateTime>" + "<EndTestTime>1526405879</EndTestTime>" + "<ElapsedMinutes>6</ElapsedMinutes>" + "</Testing>" + "</Site>"; private const string _cTestSimpleResultXmlWithoutEndTime = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Site BuildName=\"(empty)\" BuildStamp=\"20180515-1731-Experimental\" Name=\"(empty)\" Generator=\"ctest-3.11.0\" " + "CompilerName=\"\" CompilerVersion=\"\" OSName=\"Linux\" Hostname=\"3tnavBuild\" OSRelease=\"4.4.0-116-generic\" " + "OSVersion=\"#140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018\" OSPlatform=\"x86_64\" Is64Bits=\"1\">" + "<Testing>" + "<StartDateTime>May 15 10:31 PDT</StartDateTime>" + "<StartTestTime>1526405497</StartTestTime>" + "<TestList>" + "<Test>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Test>" + "</TestList>" + "<Test Status =\"passed\">" + "<Name>loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Name>" + "<Path>./libs/MgmtVisualization/tests</Path>" + "<FullName>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</FullName>" + "<FullCommandLine>/home/ctc/jenkins/workspace/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</FullCommandLine>" + "<Results>" + "<NamedMeasurement type =\"numeric/double\" name=\"Execution Time\">" + "<Value>0.0074303</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"numeric/double\" name=\"Processors\">" + "<Value>1</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Completion Status\">" + "<Value>Completed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Command Line\">" + "<Value>/home/ctc/jenkins/workspace/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>output : [----------] Global test environment set-up.</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "</Testing>" + "</Site>"; private const string _cTestSimpleResultXmlWithoutStartTime = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Site BuildName=\"(empty)\" BuildStamp=\"20180515-1731-Experimental\" Name=\"(empty)\" Generator=\"ctest-3.11.0\" " + "CompilerName=\"\" CompilerVersion=\"\" OSName=\"Linux\" Hostname=\"3tnavBuild\" OSRelease=\"4.4.0-116-generic\" " + "OSVersion=\"#140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018\" OSPlatform=\"x86_64\" Is64Bits=\"1\">" + "<Testing>" + "<TestList>" + "<Test>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Test>" + "</TestList>" + "<Test Status =\"passed\">" + "<Name>loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Name>" + "<Path>./libs/MgmtVisualization/tests</Path>" + "<FullName>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</FullName>" + "<FullCommandLine>/home/ctc/jenkins/workspace/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</FullCommandLine>" + "<Results>" + "<NamedMeasurement type =\"numeric/double\" name=\"Execution Time\">" + "<Value>0.0074303</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"numeric/double\" name=\"Processors\">" + "<Value>1</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Completion Status\">" + "<Value>Completed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Command Line\">" + "<Value>/home/ctc/jenkins/workspace/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>output : [----------] Global test environment set-up.</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<EndDateTime>May 15 10:37 PDT</EndDateTime>" + "<EndTestTime>1526405879</EndTestTime>" + "<ElapsedMinutes>6</ElapsedMinutes>" + "</Testing>" + "</Site>"; private const string _cTestResultXmlWithNegativeTimeStamp = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Site BuildName=\"(empty)\" BuildStamp=\"20180515-1731-Experimental\" Name=\"(empty)\" Generator=\"ctest-3.11.0\" " + "CompilerName=\"\" CompilerVersion=\"\" OSName=\"Linux\" Hostname=\"3tnavBuild\" OSRelease=\"4.4.0-116-generic\" " + "OSVersion=\"#140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018\" OSPlatform=\"x86_64\" Is64Bits=\"1\">" + "<Testing>" + "<StartDateTime>May 15 10:31 PDT</StartDateTime>" + "<StartTestTime>-1526405497</StartTestTime>" + "<TestList>" + "<Test>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Test>" + "</TestList>" + "<Test Status =\"passed\">" + "<Name>loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Name>" + "<Path>./libs/MgmtVisualization/tests</Path>" + "<FullName>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</FullName>" + "<FullCommandLine>D:/a/r1/a/libs/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</FullCommandLine>" + "<Results>" + "<NamedMeasurement type =\"numeric/double\" name=\"Execution Time\">" + "<Value>0.0074303</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"numeric/double\" name=\"Processors\">" + "<Value>1</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Completion Status\">" + "<Value>Completed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Command Line\">" + "<Value>D:/a/r1/a/libs/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>output : [----------] Global test environment set-up.</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<EndDateTime>May 15 10:37 PDT</EndDateTime>" + "<EndTestTime>1526405879</EndTestTime>" + "<ElapsedMinutes>6</ElapsedMinutes>" + "</Testing>" + "</Site>"; private const string _cTestResultXmlWithNegativeDuration = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Site BuildName=\"(empty)\" BuildStamp=\"20180515-1731-Experimental\" Name=\"(empty)\" Generator=\"ctest-3.11.0\" " + "CompilerName=\"\" CompilerVersion=\"\" OSName=\"Linux\" Hostname=\"3tnavBuild\" OSRelease=\"4.4.0-116-generic\" " + "OSVersion=\"#140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018\" OSPlatform=\"x86_64\" Is64Bits=\"1\">" + "<Testing>" + "<StartDateTime>May 15 10:31 PDT</StartDateTime>" + "<StartTestTime>1526405497</StartTestTime>" + "<TestList>" + "<Test>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Test>" + "</TestList>" + "<Test Status =\"passed\">" + "<Name>loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Name>" + "<Path>./libs/MgmtVisualization/tests</Path>" + "<FullName>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</FullName>" + "<FullCommandLine>D:/a/r1/a/libs/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</FullCommandLine>" + "<Results>" + "<NamedMeasurement type =\"numeric/double\" name=\"Execution Time\">" + "<Value>-0.0074303</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"numeric/double\" name=\"Processors\">" + "<Value>1</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Completion Status\">" + "<Value>Completed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type =\"text/string\" name=\"Command Line\">" + "<Value>D:/a/r1/a/libs/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>output : [----------] Global test environment set-up.</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<EndDateTime>May 15 10:37 PDT</EndDateTime>" + "<EndTestTime>1526405879</EndTestTime>" + "<ElapsedMinutes>6</ElapsedMinutes>" + "</Testing>" + "</Site>"; private const string _cTestSimpleResultXmlWithLocalTime = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Site BuildName=\"(empty)\" BuildStamp=\"20180515-1731-Experimental\" Name=\"(empty)\" Generator=\"ctest-3.11.0\" " + "CompilerName=\"\" CompilerVersion=\"\" OSName=\"Linux\" Hostname=\"3tnavBuild\" OSRelease=\"4.4.0-116-generic\" " + "OSVersion=\"#140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018\" OSPlatform=\"x86_64\" Is64Bits=\"1\">" + "<Testing>" + "<StartDateTime>Jan 03 17:51 India Standard Time</StartDateTime>" + "<StartTestTime>1546518079</StartTestTime>" + "<TestList>" + "<Test>./libs/MgmtVisualization/tests/loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback</Test>" + "</TestList>" + "<Test Status=\"failed\">" + "<Name>WGET-testU-noMD5</Name>" + "<Path>E_/foo/sources</Path>" + "<FullName>E_/foo/sources/WGET-testU-noMD5</FullName>" + "<FullCommandLine>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe &quot;-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET&quot;" + "&quot;-P&quot; &quot;E:/foo/sources/modules/testU/WGET-testU-noMD5.cmake&quot;</FullCommandLine>" + "<Results>" + "<NamedMeasurement type=\"text/string\" name=\"Exit Code\">" + "<Value>Failed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Exit Value\">" + "<Value>1</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"numeric/double\" name=\"Execution Time\">" + "<Value>0.0820084</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Completion Status\">" + "<Value>Completed</Value>" + "</NamedMeasurement>" + "<NamedMeasurement type=\"text/string\" name=\"Command Line\">" + "<Value>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe &quot;-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET&quot;" + "&quot;-P&quot; &quot;E:/foo/sources/modules/testU/WGET-testU-noMD5.cmake&quot;</Value>" + "</NamedMeasurement>" + "<Measurement>" + "<Value>-- Download of file://\\abc-mang.md5.txt" + "failed with message: [37]&quot;couldn&apos;t read a file:// file&quot;" + "CMake Error at modules/Logging.cmake:121 (message):" + "" + "" + "test BAR_wget_file succeed: result is &quot;OFF&quot; instead of &quot;ON&quot;" + "" + "Call Stack (most recent call first):" + "modules/Test.cmake:74 (BAR_msg_fatal)" + "modules/testU/WGET-testU-noMD5.cmake:14 (BAR_check_equal)" + "" + "" + "</Value>" + "</Measurement>" + "</Results>" + "</Test>" + "<EndDateTime>Jan 03 17:51 India Standard Time</EndDateTime>" + "<EndTestTime>1546518079</EndTestTime>" + "<ElapsedMinutes>6</ElapsedMinutes>" + "</Testing>" + "</Site>"; #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; using Azure.Communication.Pipeline; using Azure.Communication.Sms.Models; namespace Azure.Communication.Sms { /// <summary> /// The Azure Communication Services SMS client. /// </summary> public class SmsClient { private readonly ClientDiagnostics _clientDiagnostics; internal SmsRestClient RestClient { get; } #region public constructors - all arguments need null check /// <summary> Initializes a new instance of <see cref="SmsClient"/>.</summary> /// <param name="connectionString">Connection string acquired from the Azure Communication Services resource.</param> public SmsClient(string connectionString) : this( ConnectionString.Parse(Argument.CheckNotNullOrEmpty(connectionString, nameof(connectionString))), new SmsClientOptions()) { } /// <summary> Initializes a new instance of <see cref="SmsClient"/>.</summary> /// <param name="connectionString">Connection string acquired from the Azure Communication Services resource.</param> /// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param> public SmsClient(string connectionString, SmsClientOptions options) : this( ConnectionString.Parse(Argument.CheckNotNullOrEmpty(connectionString, nameof(connectionString))), options ?? new SmsClientOptions()) { } /// <summary> Initializes a new instance of <see cref="SmsClient"/>.</summary> /// <param name="endpoint">The URI of the Azure Communication Services resource.</param> /// <param name="keyCredential">The <see cref="AzureKeyCredential"/> used to authenticate requests.</param> /// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param> public SmsClient(Uri endpoint, AzureKeyCredential keyCredential, SmsClientOptions options = default) : this( Argument.CheckNotNull(endpoint, nameof(endpoint)).AbsoluteUri, Argument.CheckNotNull(keyCredential, nameof(keyCredential)), options ?? new SmsClientOptions()) { } /// <summary> Initializes a new instance of <see cref="SmsClient"/>.</summary> /// <param name="endpoint">The URI of the Azure Communication Services resource.</param> /// <param name="tokenCredential">The TokenCredential used to authenticate requests, such as DefaultAzureCredential.</param> /// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param> public SmsClient(Uri endpoint, TokenCredential tokenCredential, SmsClientOptions options = default) : this( Argument.CheckNotNull(endpoint, nameof(endpoint)).AbsoluteUri, Argument.CheckNotNull(tokenCredential, nameof(tokenCredential)), options ?? new SmsClientOptions()) { } #endregion #region private constructors private SmsClient(ConnectionString connectionString, SmsClientOptions options) : this(connectionString.GetRequired("endpoint"), options.BuildHttpPipeline(connectionString), options) { } private SmsClient(string endpoint, TokenCredential tokenCredential, SmsClientOptions options) : this(endpoint, options.BuildHttpPipeline(tokenCredential), options) { } private SmsClient(string endpoint, AzureKeyCredential keyCredential, SmsClientOptions options) : this(endpoint, options.BuildHttpPipeline(keyCredential), options) { } private SmsClient(string endpoint, HttpPipeline httpPipeline, SmsClientOptions options) { _clientDiagnostics = new ClientDiagnostics(options); RestClient = new SmsRestClient(_clientDiagnostics, httpPipeline, endpoint, options.ApiVersion); } #endregion /// <summary>Initializes a new instance of <see cref="SmsClient"/> for mocking.</summary> protected SmsClient() { _clientDiagnostics = null; RestClient = null; } /// <summary> /// Sends a SMS <paramref name="from"/> a phone number that is acquired by the authenticated account, <paramref name="to"/> another phone number. /// </summary> /// <param name="from">The sender's phone number that is owned by the authenticated account.</param> /// <param name="to">The recipient's phone number.</param> /// <param name="message">The contents of the message that will be sent to the recipient. The allowable content is defined by RFC 5724. If the message has more than 160 characters, the server will split it into multiple SMSs automatically.</param> /// <param name="options">Optional configuration for sending SMS messages.</param> /// <param name="cancellationToken">The cancellation token for the task.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <exception cref="ArgumentNullException"><paramref name="from"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="to"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="message"/> is null.</exception> public virtual async Task<Response<SmsSendResult>> SendAsync(string from, string to, string message, SmsSendOptions options = default, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(from, nameof(from)); Argument.AssertNotNullOrEmpty(to, nameof(to)); Response<IReadOnlyList<SmsSendResult>> response = await SendAsync(from, new[] { to }, message, options, cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value[0], response.GetRawResponse()); } /// <summary> /// Sends a SMS <paramref name="from"/> a phone number that is acquired by the authenticated account, <paramref name="to"/> another phone number. /// </summary> /// <param name="from">The sender's phone number that is owned by the authenticated account.</param> /// <param name="to">The recipient's phone number.</param> /// <param name="message">The contents of the message that will be sent to the recipient. The allowable content is defined by RFC 5724. If the message has more than 160 characters, the server will split it into multiple SMSs automatically.</param> /// <param name="options">Optional configuration for sending SMS messages.</param> /// <param name="cancellationToken">The cancellation token for the underlying request.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <exception cref="ArgumentNullException"><paramref name="from"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="to"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="message"/> is null.</exception> public virtual Response<SmsSendResult> Send(string from, string to, string message, SmsSendOptions options = default, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(from, nameof(from)); Argument.AssertNotNullOrEmpty(to, nameof(to)); Response<IReadOnlyList<SmsSendResult>> response = Send(from, new[] { to }, message, options, cancellationToken); return Response.FromValue(response.Value[0], response.GetRawResponse()); } /// <summary> Sends an SMS message from a phone number that belongs to the authenticated account. </summary> /// <param name="from"> The sender&apos;s phone number in E.164 format that is owned by the authenticated account. </param> /// <param name="to"> The recipient&apos;s phone number in E.164 format. In this version, up to 100 recipients in the list is supported. </param> /// <param name="message"> The contents of the message that will be sent to the recipient. The allowable content is defined by RFC 5724. </param> /// <param name="options"> Optional configuration for sending SMS messages. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <exception cref="ArgumentNullException"><paramref name="from"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="to"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="message"/> is null.</exception> public virtual async Task<Response<IReadOnlyList<SmsSendResult>>> SendAsync(string from, IEnumerable<string> to, string message, SmsSendOptions options = default, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(SmsClient)}.{nameof(Send)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(from, nameof(from)); Argument.AssertNotNullOrEmpty(to, nameof(to)); IEnumerable<SmsRecipient> recipients = to.Select(x => new SmsRecipient(Argument.CheckNotNullOrEmpty(x, nameof(to))) { RepeatabilityRequestId = Guid.NewGuid().ToString(), RepeatabilityFirstSent = DateTimeOffset.UtcNow.ToString("r", CultureInfo.InvariantCulture), }); Response<SmsSendResponse> response = await RestClient.SendAsync(from, recipients, message, options, cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Sends an SMS message from a phone number that belongs to the authenticated account. </summary> /// <param name="from"> The sender&apos;s phone number in E.164 format that is owned by the authenticated account. </param> /// <param name="to"> The recipient&apos;s phone number in E.164 format. In this version, up to 100 recipients in the list is supported. </param> /// <param name="message"> The contents of the message that will be sent to the recipient. The allowable content is defined by RFC 5724. </param> /// <param name="options"> Optional configuration for sending SMS messages. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <exception cref="ArgumentNullException"><paramref name="from"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="to"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="message"/> is null.</exception> public virtual Response<IReadOnlyList<SmsSendResult>> Send(string from, IEnumerable<string> to, string message, SmsSendOptions options = default, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(SmsClient)}.{nameof(Send)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(from, nameof(from)); Argument.AssertNotNullOrEmpty(to, nameof(to)); IEnumerable<SmsRecipient> recipients = to.Select(x => new SmsRecipient(Argument.CheckNotNullOrEmpty(x, nameof(to))) { RepeatabilityRequestId = Guid.NewGuid().ToString(), RepeatabilityFirstSent = DateTimeOffset.UtcNow.ToString("r", CultureInfo.InvariantCulture), }); Response<SmsSendResponse> response = RestClient.Send(from, recipients, message, options, cancellationToken); return Response.FromValue(response.Value.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } } }
using EFCore.BulkExtensions.SqlAdapters; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Caching.Memory; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Xunit; namespace EFCore.BulkExtensions.Tests { public class EFCoreBulkTestAsync { protected int EntitiesNumber => 10000; private static Func<TestContext, int> ItemsCountQuery = EF.CompileQuery<TestContext, int>(ctx => ctx.Items.Count()); private static Func<TestContext, Item> LastItemQuery = EF.CompileQuery<TestContext, Item>(ctx => ctx.Items.LastOrDefault()); private static Func<TestContext, IEnumerable<Item>> AllItemsQuery = EF.CompileQuery<TestContext, IEnumerable<Item>>(ctx => ctx.Items.AsNoTracking()); [Theory] [InlineData(DbServer.SQLServer, true)] [InlineData(DbServer.SQLite, true)] //[InlineData(DatabaseType.SqlServer, false)] // for speed comparison with Regular EF CUD operations public async Task OperationsTestAsync(DbServer dbServer, bool isBulk) { ContextUtil.DbServer = dbServer; //await DeletePreviousDatabaseAsync().ConfigureAwait(false); await new EFCoreBatchTestAsync().RunDeleteAllAsync(dbServer); // Test can be run individually by commenting others and running each separately in order one after another await RunInsertAsync(isBulk); await RunInsertOrUpdateAsync(isBulk, dbServer); await RunUpdateAsync(isBulk, dbServer); await RunReadAsync(isBulk); if (dbServer == DbServer.SQLServer) { await RunInsertOrUpdateOrDeleteAsync(isBulk); // Not supported for Sqlite (has only UPSERT), instead use BulkRead, then split list into sublists and call separately Bulk methods for Insert, Update, Delete. } //await RunDeleteAsync(isBulk, dbServer); } [Theory] [InlineData(DbServer.SQLServer)] //[InlineData(DbServer.Sqlite)] // has to be run separately as single test, otherwise throws (SQLite Error 1: 'table "#MyTempTable1" already exists'.) public async Task SideEffectsTestAsync(DbServer dbServer) { await BulkOperationShouldNotCloseOpenConnectionAsync(dbServer, context => context.BulkInsertAsync(new[] { new Item() }), "1"); await BulkOperationShouldNotCloseOpenConnectionAsync(dbServer, context => context.BulkUpdateAsync(new[] { new Item() }), "2"); } private async Task DeletePreviousDatabaseAsync() { using var context = new TestContext(ContextUtil.GetOptions()); await context.Database.EnsureDeletedAsync().ConfigureAwait(false); } private void WriteProgress(decimal percentage) { Debug.WriteLine(percentage); } private static async Task BulkOperationShouldNotCloseOpenConnectionAsync(DbServer dbServer, Func<TestContext, Task> bulkOperation, string tableSufix) { ContextUtil.DbServer = dbServer; using var context = new TestContext(ContextUtil.GetOptions()); var sqlHelper = context.GetService<ISqlGenerationHelper>(); await context.Database.OpenConnectionAsync(); try { // we use a temp table to verify whether the connection has been closed (and re-opened) inside BulkUpdate(Async) var columnName = sqlHelper.DelimitIdentifier("Id"); var tableName = sqlHelper.DelimitIdentifier("#MyTempTable" + tableSufix); var createTableSql = $" TABLE {tableName} ({columnName} INTEGER);"; createTableSql = dbServer switch { DbServer.SQLite => $"CREATE TEMPORARY {createTableSql}", DbServer.SQLServer => $"CREATE {createTableSql}", _ => throw new ArgumentException($"Unknown database type: '{dbServer}'.", nameof(dbServer)), }; await context.Database.ExecuteSqlRawAsync(createTableSql); await bulkOperation(context); await context.Database.ExecuteSqlRawAsync($"SELECT {columnName} FROM {tableName}"); } finally { await context.Database.CloseConnectionAsync(); } } private async Task RunInsertAsync(bool isBulk) { using var context = new TestContext(ContextUtil.GetOptions()); var entities = new List<Item>(); var subEntities = new List<ItemHistory>(); for (int i = 1; i < EntitiesNumber; i++) { var entity = new Item { ItemId = isBulk ? i : 0, Name = "name " + i, Description = "info " + Guid.NewGuid().ToString().Substring(0, 3), Quantity = i % 10, Price = i / (i % 5 + 1), TimeUpdated = DateTime.Now, ItemHistories = new List<ItemHistory>() }; var subEntity1 = new ItemHistory { ItemHistoryId = SeqGuid.Create(), Remark = $"some more info {i}.1" }; var subEntity2 = new ItemHistory { ItemHistoryId = SeqGuid.Create(), Remark = $"some more info {i}.2" }; entity.ItemHistories.Add(subEntity1); entity.ItemHistories.Add(subEntity2); entities.Add(entity); } if (isBulk) { if (ContextUtil.DbServer == DbServer.SQLServer) { using var transaction = await context.Database.BeginTransactionAsync(); var bulkConfig = new BulkConfig { //PreserveInsertOrder = true, // true is default SetOutputIdentity = true, BatchSize = 4000, CalculateStats = true }; await context.BulkInsertAsync(entities, bulkConfig, (a) => WriteProgress(a)); Assert.Equal(EntitiesNumber - 1, bulkConfig.StatsInfo.StatsNumberInserted); Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberUpdated); Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberDeleted); foreach (var entity in entities) { foreach (var subEntity in entity.ItemHistories) { subEntity.ItemId = entity.ItemId; // setting FK to match its linked PK that was generated in DB } subEntities.AddRange(entity.ItemHistories); } await context.BulkInsertAsync(subEntities); await transaction.CommitAsync(); } else if (ContextUtil.DbServer == DbServer.SQLite) { using var transaction = await context.Database.BeginTransactionAsync(); var bulkConfig = new BulkConfig() { SetOutputIdentity = true, }; await context.BulkInsertAsync(entities, bulkConfig); foreach (var entity in entities) { foreach (var subEntity in entity.ItemHistories) { subEntity.ItemId = entity.ItemId; // setting FK to match its linked PK that was generated in DB } subEntities.AddRange(entity.ItemHistories); } await context.BulkInsertAsync(subEntities, bulkConfig); await transaction.CommitAsync(); } } else { await context.Items.AddRangeAsync(entities); await context.SaveChangesAsync(); } // TEST int entitiesCount = await context.Items.CountAsync(); // = ItemsCountQuery(context); Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault(); // = LastItemQuery(context); Assert.Equal(EntitiesNumber - 1, entitiesCount); Assert.NotNull(lastEntity); Assert.Equal("name " + (EntitiesNumber - 1), lastEntity.Name); } private async Task RunInsertOrUpdateAsync(bool isBulk, DbServer dbServer) { using (var context = new TestContext(ContextUtil.GetOptions())) { var entities = new List<Item>(); var dateTimeNow = DateTime.Now; var dateTimeOffsetNow = DateTimeOffset.UtcNow; for (int i = 2; i <= EntitiesNumber; i += 2) { entities.Add(new Item { ItemId = i, Name = "name InsertOrUpdate " + i, Description = "info", Quantity = i, Price = i / (i % 5 + 1), TimeUpdated = dateTimeNow }); } if (isBulk) { var bulkConfig = new BulkConfig() { SetOutputIdentity = true, CalculateStats = true }; await context.BulkInsertOrUpdateAsync(entities, bulkConfig); if (dbServer == DbServer.SQLServer) { Assert.Equal(1, bulkConfig.StatsInfo.StatsNumberInserted); Assert.Equal(EntitiesNumber / 2 - 1, bulkConfig.StatsInfo.StatsNumberUpdated); Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberDeleted); } } else { await context.Items.AddRangeAsync(entities); await context.SaveChangesAsync(); } // TEST int entitiesCount = await context.Items.CountAsync(); Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault(); Assert.Equal(EntitiesNumber, entitiesCount); Assert.NotNull(lastEntity); Assert.Equal("name InsertOrUpdate " + EntitiesNumber, lastEntity.Name); } } private async Task RunInsertOrUpdateOrDeleteAsync(bool isBulk) { using var context = new TestContext(ContextUtil.GetOptions()); var entities = new List<Item>(); var dateTimeNow = DateTime.Now; var dateTimeOffsetNow = DateTimeOffset.UtcNow; for (int i = 2; i <= EntitiesNumber; i += 2) { entities.Add(new Item { ItemId = i, Name = "name InsertOrUpdateOrDelete " + i, Description = "info", Quantity = i, Price = i / (i % 5 + 1), TimeUpdated = dateTimeNow }); } int? keepEntityItemId = null; if (isBulk) { var bulkConfig = new BulkConfig() { SetOutputIdentity = true, CalculateStats = true }; keepEntityItemId = 3; bulkConfig.SetSynchronizeFilter<Item>(e => e.ItemId != keepEntityItemId.Value); await context.BulkInsertOrUpdateOrDeleteAsync(entities, bulkConfig); Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberInserted); Assert.Equal(EntitiesNumber / 2, bulkConfig.StatsInfo.StatsNumberUpdated); Assert.Equal((EntitiesNumber / 2) -1, bulkConfig.StatsInfo.StatsNumberDeleted); } else { var existingItems = context.Items; var removedItems = existingItems.Where(x => !entities.Any(y => y.ItemId == x.ItemId)); context.Items.RemoveRange(removedItems); await context.Items.AddRangeAsync(entities); await context.SaveChangesAsync(); } // TEST using var contextRead = new TestContext(ContextUtil.GetOptions()); int entitiesCount = await contextRead.Items.CountAsync(); // = ItemsCountQuery(context); Item firstEntity = contextRead.Items.OrderBy(a => a.ItemId).FirstOrDefault(); // = LastItemQuery(context); Item lastEntity = contextRead.Items.OrderByDescending(a => a.ItemId).FirstOrDefault(); Assert.Equal(EntitiesNumber / 2 + (keepEntityItemId != null ? 1 : 0), entitiesCount); Assert.NotNull(firstEntity); Assert.Equal("name InsertOrUpdateOrDelete 2", firstEntity.Name); Assert.NotNull(lastEntity); Assert.Equal("name InsertOrUpdateOrDelete " + EntitiesNumber, lastEntity.Name); if (keepEntityItemId != null) { Assert.NotNull(context.Items.Where(x => x.ItemId == keepEntityItemId.Value).FirstOrDefault()); } if (isBulk) { var bulkConfig = new BulkConfig() { SetOutputIdentity = true, CalculateStats = true }; bulkConfig.SetSynchronizeFilter<Item>(e => e.ItemId != keepEntityItemId.Value); await context.BulkInsertOrUpdateOrDeleteAsync(new List<Item>(), bulkConfig); var storedEntities = contextRead.Items.ToList(); Assert.Single(storedEntities); Assert.Equal(3, storedEntities[0].ItemId); } } private async Task RunUpdateAsync(bool isBulk, DbServer dbServer) { using var context = new TestContext(ContextUtil.GetOptions()); int counter = 1; var entities = AllItemsQuery(context).ToList(); foreach (var entity in entities) { entity.Description = "Desc Update " + counter++; entity.TimeUpdated = DateTime.Now; } if (isBulk) { var bulkConfig = new BulkConfig() { SetOutputIdentity = true, CalculateStats = true }; await context.BulkUpdateAsync(entities, bulkConfig); if (dbServer == DbServer.SQLServer) { Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberInserted); Assert.Equal(EntitiesNumber, bulkConfig.StatsInfo.StatsNumberUpdated); Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberDeleted); } } else { context.Items.UpdateRange(entities); await context.SaveChangesAsync(); } // TEST int entitiesCount = await context.Items.CountAsync(); Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault(); Assert.Equal(EntitiesNumber, entitiesCount); Assert.NotNull(lastEntity); Assert.Equal("Desc Update " + EntitiesNumber, lastEntity.Description); } private async Task RunReadAsync(bool isBulk) { using var context = new TestContext(ContextUtil.GetOptions()); var entities = new List<Item>(); for (int i = 1; i < EntitiesNumber; i++) { entities.Add(new Item { Name = "name " + i }); } var bulkConfig = new BulkConfig { UpdateByProperties = new List<string> { nameof(Item.Name) }}; await context.BulkReadAsync(entities, bulkConfig).ConfigureAwait(false); Assert.Equal(1, entities[0].ItemId); Assert.Equal(0, entities[1].ItemId); Assert.Equal(3, entities[2].ItemId); Assert.Equal(0, entities[3].ItemId); } private async Task RunDeleteAsync(bool isBulk, DbServer dbServer) { using var context = new TestContext(ContextUtil.GetOptions()); var entities = AllItemsQuery(context).ToList(); // ItemHistories will also be deleted because of Relationship - ItemId (Delete Rule: Cascade) if (isBulk) { var bulkConfig = new BulkConfig() { CalculateStats = true }; await context.BulkDeleteAsync(entities, bulkConfig); if (dbServer == DbServer.SQLServer) { Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberInserted); Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberUpdated); Assert.Equal(EntitiesNumber / 2, bulkConfig.StatsInfo.StatsNumberDeleted); } } else { context.Items.RemoveRange(entities); await context.SaveChangesAsync(); } // TEST int entitiesCount = await context.Items.CountAsync(); Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault(); Assert.Equal(0, entitiesCount); Assert.Null(lastEntity); // RESET AutoIncrement string deleteTableSql = dbServer switch { DbServer.SQLServer => $"DBCC CHECKIDENT('[dbo].[{nameof(Item)}]', RESEED, 0);", DbServer.SQLite => $"DELETE FROM sqlite_sequence WHERE name = '{nameof(Item)}';", _ => throw new ArgumentException($"Unknown database type: '{dbServer}'.", nameof(dbServer)), }; await context.Database.ExecuteSqlRawAsync(deleteTableSql).ConfigureAwait(false); } } }
//#define DEBUG using System; using System.Collections.Generic; namespace ICSimulator { public class SwapNode { public delegate int Rank(Flit f1, Flit f2); Rank m_r; public bool changeRing; public bool swapped; public Flit in_port, out_port, inject_port, eject_port; public SwapNode(Rank r) { m_r = r; } public void doStep() { if (eject_port != null) throw new Exception("Ejection port not already empty"); if (out_port != null) throw new Exception("Out port not already empty"); if(changeRing || (inject_port != null && m_r(in_port, inject_port) > 1)) { out_port = inject_port; eject_port = in_port; } else { out_port = in_port; eject_port = inject_port; } } } // Linked Rings public abstract class Router_LinkedRings : Router { // injectSlot is from Node; injectSlot2 is higher-priority from // network-level re-injection (e.g., placeholder schemes) protected Flit m_injectSlot, m_injectSlot2; public Router_LinkedRings(Coord myCoord) : base(myCoord) { m_injectSlot = null; m_injectSlot2 = null; } // accept one ejected flit into rxbuf void acceptFlit(Flit f) { statsEjectFlit(f); if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits) statsEjectPacket(f.packet); m_n.receiveFlit(f); } Flit[] m_ej = new Flit[4] { null, null, null, null }; int m_ej_rr = 0; Flit ejectLocalNew() { for (int dir = 0; dir < 4; dir++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.dest.ID == ID && m_ej[dir] == null) { m_ej[dir] = linkIn[dir].Out; linkIn[dir].Out = null; } m_ej_rr++; m_ej_rr %= 4; Flit ret = null; if (m_ej[m_ej_rr] != null) { ret = m_ej[m_ej_rr]; m_ej[m_ej_rr] = null; } return ret; } /* * Injects flits */ void inject(out bool injected) { injected = false; if (input[4] != null) { int i = (Simulator.rand.Next(2) == 1) ? Simulator.DIR_RIGHT : Simulator.DIR_LEFT; if (input[i] == null) { injected = true; input[i] = input[4]; input[4] = null; return; } } } void swap(int dir1, int dir2) { Flit tempFlit = input[dir1]; input[dir1] = input[dir2]; input[dir2] = tempFlit; } int getFreeFlit(int dir1, int dir2) { Flit f1 = (dir1 == -1) ? null : input[dir1]; Flit f2 = (dir2 == -1) ? null : input[dir2]; int ret = rank(f1, f2); switch (ret) { case 0: return (Simulator.rand.Next(2) == 1) ? dir1 : dir2; //throw new Exception("Tiebraker wasn't decided"); case -1: return dir2; case 1: return dir1; default: throw new Exception("Should I allow for larger values than 1 and -1"); } } void route() { Flit[] temp = new Flit[5]; input[Simulator.DIR_UP] = temp[Simulator.DIR_DOWN]; input[Simulator.DIR_DOWN] = temp[Simulator.DIR_UP]; input[Simulator.DIR_LEFT] = temp[Simulator.DIR_RIGHT]; input[Simulator.DIR_RIGHT] = temp[Simulator.DIR_LEFT]; } Flit[] input = new Flit[5]; // keep this as a member var so we don't // have to allocate on every step (why can't // we have arrays on the stack like in C?) protected override void _doStep() { /* Ejection selection and ejection */ Flit eject = null; eject = ejectLocalNew(); /* Setup the inputs */ for (int dir = 0; dir < 4; dir++) { if (linkIn[dir] != null && linkIn[dir].Out != null) { input[dir] = linkIn[dir].Out; input[dir].inDir = dir; } else input[dir] = null; } /* Injection */ Flit inj = null; bool injected = false; /* Pick slot to inject */ if (m_injectSlot2 != null) { inj = m_injectSlot2; m_injectSlot2 = null; } else if (m_injectSlot != null) { inj = m_injectSlot; m_injectSlot = null; } /* Port 4 becomes the injected line */ input[4] = inj; /* If there is data, set the injection direction */ if (inj != null) inj.inDir = -1; /* Go thorugh inputs, find their preferred directions */ for (int i = 0; i < 5; i++) { if (input[i] != null) { PreferredDirection pd = determineDirection(input[i]); if (pd.xDir != Simulator.DIR_NONE) input[i].prefDir = pd.xDir; else input[i].prefDir = pd.yDir; } } /* Inject and route flits in correct directions */ inject(out injected); #if DEBUG for (int dir = 0; dir < 4; dir++) if(input[dir] != null) Console.WriteLine("flit {0}.{1} at node {2} cyc {3} AFTER_INJ", input[dir].packet.ID, input[dir].flitNr, coord, Simulator.CurrentRound); #endif if (injected && input[4] != null) throw new Exception("Not removing injected flit from slot"); route(); #if DEBUG for (int dir = 0; dir < 4; dir++) if(input[dir] != null) Console.WriteLine("flit {0}.{1} at node {2} cyc {3} AFTER_ROUTE", input[dir].packet.ID, input[dir].flitNr, coord, Simulator.CurrentRound); #endif //for (int i = 0; i < 4; i++) //{ // if (input[i] != null) // { // input[i].Deflected = input[i].prefDir != i; // } //} /* If something wasn't injected, move the flit into the injection slots * * If it was injected, take stats */ if (!injected) { if (m_injectSlot == null) m_injectSlot = inj; else m_injectSlot2 = inj; } else statsInjectFlit(inj); /* Put ejected flit in reassembly buffer */ if (eject != null) acceptFlit(eject); /* Assign outputs */ for (int dir = 0; dir < 4; dir++) { if (input[dir] != null) { #if DEBUG Console.WriteLine("flit {0}.{1} at node {2} cyc {3} END", input[dir].packet.ID, input[dir].flitNr, coord, Simulator.CurrentRound); #endif if (linkOut[dir] == null) throw new Exception(String.Format("router {0} does not have link in dir {1}", coord, dir)); linkOut[dir].In = input[dir]; } #if DEBUG //else if(dir == Simulator.DIR_LEFT || dir == Simulator.DIR_RIGHT) // Console.WriteLine("no flit at node {0} cyc {1}", coord, Simulator.CurrentRound); #endif } } public override bool canInjectFlit(Flit f) { return m_injectSlot == null; } public override void InjectFlit(Flit f) { if (m_injectSlot != null) throw new Exception("Trying to inject twice in one cycle"); m_injectSlot = f; } public override void visitFlits(Flit.Visitor fv) { if (m_injectSlot != null) fv(m_injectSlot); if (m_injectSlot2 != null) fv(m_injectSlot2); } //protected abstract int rank(Flit f1, Flit f2); } public class Router_LinkedRings_Random : Router_LinkedRings { public Router_LinkedRings_Random(Coord myCoord) : base(myCoord) { } public override int rank(Flit f1, Flit f2) { return Router_Flit_Random._rank(f1, f2); } } public class Router_LinkedRings_OldestFirst : Router_LinkedRings { public Router_LinkedRings_OldestFirst(Coord myCoord) : base(myCoord) { } public override int rank(Flit f1, Flit f2) { return Router_Flit_OldestFirst._rank(f1, f2); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Commands; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal abstract class AbstractSnippetCommandHandler : ForegroundThreadAffinitizedObject, ICommandHandler<TabKeyCommandArgs>, ICommandHandler<BackTabKeyCommandArgs>, ICommandHandler<ReturnKeyCommandArgs>, ICommandHandler<EscapeKeyCommandArgs>, ICommandHandler<InsertSnippetCommandArgs> { protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService; protected readonly SVsServiceProvider ServiceProvider; public AbstractSnippetCommandHandler(IVsEditorAdaptersFactoryService editorAdaptersFactoryService, SVsServiceProvider serviceProvider) { this.EditorAdaptersFactoryService = editorAdaptersFactoryService; this.ServiceProvider = serviceProvider; } protected abstract AbstractSnippetExpansionClient GetSnippetExpansionClient(ITextView textView, ITextBuffer subjectBuffer); protected abstract bool IsSnippetExpansionContext(Document document, int startPosition, CancellationToken cancellationToken); protected abstract void InvokeInsertionUI(ITextView textView, ITextBuffer subjectBuffer, Action nextHandler, bool surroundWith = false); protected virtual bool TryInvokeSnippetPickerOnQuestionMark(ITextView textView, ITextBuffer textBuffer) { return false; } public void ExecuteCommand(TabKeyCommandArgs args, Action nextHandler) { AssertIsForeground(); if (!args.SubjectBuffer.GetOption(InternalFeatureOnOffOptions.Snippets)) { nextHandler(); return; } AbstractSnippetExpansionClient snippetExpansionClient; if (args.TextView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out snippetExpansionClient) && snippetExpansionClient.TryHandleTab()) { return; } // Insert snippet/show picker only if we don't have a selection: the user probably wants to indent instead if (args.TextView.Selection.IsEmpty) { if (TryHandleTypedSnippet(args.TextView, args.SubjectBuffer)) { return; } if (TryInvokeSnippetPickerOnQuestionMark(args.TextView, args.SubjectBuffer)) { return; } } nextHandler(); } public CommandState GetCommandState(TabKeyCommandArgs args, Func<CommandState> nextHandler) { AssertIsForeground(); Workspace workspace; if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace)) { return nextHandler(); } return CommandState.Available; } public void ExecuteCommand(ReturnKeyCommandArgs args, Action nextHandler) { AssertIsForeground(); if (!args.SubjectBuffer.GetOption(InternalFeatureOnOffOptions.Snippets)) { nextHandler(); return; } AbstractSnippetExpansionClient snippetExpansionClient; if (args.TextView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out snippetExpansionClient) && snippetExpansionClient.TryHandleReturn()) { return; } nextHandler(); } public CommandState GetCommandState(ReturnKeyCommandArgs args, Func<CommandState> nextHandler) { AssertIsForeground(); Workspace workspace; if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace)) { return nextHandler(); } return CommandState.Available; } public void ExecuteCommand(EscapeKeyCommandArgs args, Action nextHandler) { AssertIsForeground(); if (!args.SubjectBuffer.GetOption(InternalFeatureOnOffOptions.Snippets)) { nextHandler(); return; } AbstractSnippetExpansionClient snippetExpansionClient; if (args.TextView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out snippetExpansionClient) && snippetExpansionClient.TryHandleEscape()) { return; } nextHandler(); } public CommandState GetCommandState(EscapeKeyCommandArgs args, Func<CommandState> nextHandler) { AssertIsForeground(); Workspace workspace; if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace)) { return nextHandler(); } return CommandState.Available; } public void ExecuteCommand(BackTabKeyCommandArgs args, Action nextHandler) { AssertIsForeground(); if (!args.SubjectBuffer.GetOption(InternalFeatureOnOffOptions.Snippets)) { nextHandler(); return; } AbstractSnippetExpansionClient snippetExpansionClient; if (args.TextView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out snippetExpansionClient) && snippetExpansionClient.TryHandleBackTab()) { return; } nextHandler(); } public CommandState GetCommandState(BackTabKeyCommandArgs args, Func<CommandState> nextHandler) { AssertIsForeground(); Workspace workspace; if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace)) { return nextHandler(); } return CommandState.Available; } public void ExecuteCommand(InsertSnippetCommandArgs args, Action nextHandler) { AssertIsForeground(); if (!args.SubjectBuffer.GetOption(InternalFeatureOnOffOptions.Snippets)) { nextHandler(); return; } InvokeInsertionUI(args.TextView, args.SubjectBuffer, nextHandler); } public CommandState GetCommandState(InsertSnippetCommandArgs args, Func<CommandState> nextHandler) { Workspace workspace; if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace)) { return nextHandler(); } if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { return nextHandler(); } return CommandState.Available; } protected bool TryHandleTypedSnippet(ITextView textView, ITextBuffer subjectBuffer) { AssertIsForeground(); Document document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return false; } var currentText = subjectBuffer.AsTextContainer().CurrentText; var syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var endPositionInSubjectBuffer = textView.GetCaretPoint(subjectBuffer); if (endPositionInSubjectBuffer == null) { return false; } var endPosition = endPositionInSubjectBuffer.Value.Position; var startPosition = endPosition; // Find the snippet shortcut while (startPosition > 0) { char c = currentText[startPosition - 1]; if (!syntaxFactsService.IsIdentifierPartCharacter(c) && c != '#' && c != '~') { break; } startPosition--; } if (startPosition == endPosition) { return false; } if (!IsSnippetExpansionContext(document, startPosition, CancellationToken.None)) { return false; } return GetSnippetExpansionClient(textView, subjectBuffer).TryInsertExpansion(startPosition, endPosition); } protected bool TryGetExpansionManager(out IVsExpansionManager expansionManager) { var textManager = (IVsTextManager2)ServiceProvider.GetService(typeof(SVsTextManager)); if (textManager == null) { expansionManager = null; return false; } textManager.GetExpansionManager(out expansionManager); return expansionManager != null; } } }
// Copyright (c) Oleg Zudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Zu.Chrome.DriverCore; using Zu.WebBrowser.BasicTypes; using Zu.WebBrowser.AsyncInteractions; using System.IO; using Zu.Chrome.DevTools; using Zu.WebBrowser.BrowserOptions; namespace Zu.Chrome { public class AsyncChromeDriver : IAsyncChromeDriver { #region IAsyncWebBrowserClient public IMouse Mouse => _mouse ?? (_mouse = new ChromeDriverMouse(this)); public IKeyboard Keyboard => _keyboard ?? (_keyboard = new ChromeDriverKeyboard(this)); public IOptions Options => _options ?? (_options = new ChromeDriverOptions(this)); public IAlert Alert => _alert ?? (_alert = new ChromeDriverAlert(this)); public ICoordinates Coordinates => _coordinates ?? (_coordinates = new ChromeDriverCoordinates(this)); public ITakesScreenshot Screenshot => _screenshot ?? (_screenshot = new ChromeDriverScreenshot(this)); public ITouchScreen TouchScreen => _touchScreen ?? (_touchScreen = new ChromeDriverTouchScreen(this)); public INavigation Navigation => _navigation ?? (_navigation = new ChromeDriverNavigation(this)); public IJavaScriptExecutor JavaScriptExecutor => _javaScriptExecutor ?? (_javaScriptExecutor = new ChromeDriverJavaScriptExecutor(this)); public ITargetLocator TargetLocator => _targetLocator ?? (_targetLocator = new ChromeDriverTargetLocator(this)); public IElements Elements => _elements ?? (_elements = new ChromeDriverElements(this)); public IActionExecutor ActionExecutor => _actionExecutor ?? (_actionExecutor = new ChromeDriverActionExecutor(this)); private ChromeDriverNavigation _navigation; private ChromeDriverTouchScreen _touchScreen; private ChromeDriverScreenshot _screenshot; private ChromeDriverCoordinates _coordinates; private ChromeDriverAlert _alert; private ChromeDriverOptions _options; private ChromeDriverKeyboard _keyboard; private ChromeDriverMouse _mouse; private ChromeDriverJavaScriptExecutor _javaScriptExecutor; private ChromeDriverTargetLocator _targetLocator; private ChromeDriverElements _elements; private ChromeDriverActionExecutor _actionExecutor; #endregion public bool IsConnected = false; public ChromeDevToolsConnection DevTools { get; set; } public FrameTracker FrameTracker { get; private set; } public DomTracker DomTracker { get; private set; } public Session Session { get; private set; } public WebView WebView { get; private set; } public ElementCommands ElementCommands { get; private set; } public ElementUtils ElementUtils { get; private set; } public WindowCommands WindowCommands { get; private set; } public ChromeDriverConfig Config { get; set; } public int Port { get => Config.Port; set => Config.Port = value; } public string UserDir { get => Config.UserDir; set => Config.SetUserDir(value); } public bool IsTempProfile { get => Config.IsTempProfile; set => Config.IsTempProfile = value; } public bool DoConnectWhenCheckConnected { get; set; } = true; static int _sessionId = 0; public ChromeProcessInfo ChromeProcess; private bool _isClosed = false; public delegate void DevToolsEventHandler(object sender, string methodName, JToken eventData); public event DevToolsEventHandler DevToolsEvent; public AsyncChromeDriver BrowserDevTools { get; set; } public ChromeDriverConfig BrowserDevToolsConfig { get; set; } static Random _rnd = new Random(); public AsyncChromeDriver(bool openInTempDir = true) : this(11000 + _rnd.Next(2000)) { Config.SetIsTempProfile(openInTempDir); } public AsyncChromeDriver(string profileDir, int port) : this(port) { UserDir = profileDir; } public AsyncChromeDriver(string profileDir) : this(11000 + _rnd.Next(2000)) { UserDir = profileDir; } public AsyncChromeDriver(DriverConfig config) : this(config as ChromeDriverConfig ?? new ChromeDriverConfig(config)) { } public AsyncChromeDriver(ChromeDriverConfig config) { Config = config; if (Config.Port == 0) Config.Port = 11000 + _rnd.Next(2000); if (Config.DoOpenWSProxy || Config.DoOpenBrowserDevTools) { if (Config.DevToolsConnectionProxyPort == 0) Config.DevToolsConnectionProxyPort = 15000 + _rnd.Next(2000); DevTools = new BrowserDevTools.ChromeDevToolsConnectionProxy(Port, Config.DevToolsConnectionProxyPort, Config.WSProxyConfig); } else DevTools = new ChromeDevToolsConnection(Port); CreateDriverCore(); } public AsyncChromeDriver(int port) { Config = new ChromeDriverConfig(); Port = port; DevTools = new ChromeDevToolsConnection(Port); CreateDriverCore(); } public void CreateDriverCore() { Session = new Session(_sessionId++, this); FrameTracker = new FrameTracker(DevTools); DomTracker = new DomTracker(DevTools); WebView = new WebView(DevTools, FrameTracker, this); //Mouse = new ChromeDriverMouse(WebView, Session); //Keyboard = new ChromeDriverKeyboard(WebView); //Options = new BrowserOptions(); ElementUtils = new ElementUtils(WebView, Session); ElementCommands = new ElementCommands(this); WindowCommands = new WindowCommands(this); } public virtual async Task<string> Connect(CancellationToken cancellationToken = default(CancellationToken)) { IsConnected = true; UnsubscribeDevToolsSessionEvent(); DoConnectWhenCheckConnected = false; if (!Config.DoNotOpenChromeProfile) { ChromeProcess = await OpenChromeProfile(Config).ConfigureAwait(false); if (Config.IsTempProfile) await Task.Delay(Config.TempDirCreateDelay).ConfigureAwait(false); } int connectionAttempts = 0; int maxAttempts = 5; if (ChromeProfilesWorker.GetPlatformString() != "windows") { maxAttempts = 50; } while (true) { connectionAttempts++; try { await DevTools.Connect().ConfigureAwait(false); break; } catch (Exception ex) { //LiveLogger.WriteLine("Connection attempt {0} failed with: {1}", connection_attempts, ex); if (_isClosed || connectionAttempts >= maxAttempts) { throw; } else { await Task.Delay(200).ConfigureAwait(false); } } } SubscribeToDevToolsSessionEvent(); await FrameTracker.Enable().ConfigureAwait(false); await DomTracker.Enable().ConfigureAwait(false); if (Config.DoOpenBrowserDevTools) await OpenBrowserDevTools().ConfigureAwait(false); return $"Connected to Chrome port {Port}"; } public string GetBrowserDevToolsUrl() { var httpPort = Config?.WSProxyConfig?.DoProxyHttpTraffic == true ? Config.WSProxyConfig.HttpServerPort : Port; return "http://127.0.0.1:" + httpPort + "/devtools/inspector.html?ws=127.0.0.1:" + Config?.DevToolsConnectionProxyPort + "/WSProxy"; } public virtual async Task OpenBrowserDevTools() { if (BrowserDevToolsConfig == null) BrowserDevToolsConfig = new ChromeDriverConfig(); BrowserDevTools = new AsyncChromeDriver(BrowserDevToolsConfig); await BrowserDevTools.Navigation.GoToUrl(GetBrowserDevToolsUrl()).ConfigureAwait(false); } public async Task CheckConnected(CancellationToken cancellationToken = default(CancellationToken)) { if (!DoConnectWhenCheckConnected) return; DoConnectWhenCheckConnected = false; if (!IsConnected) { await Connect(cancellationToken).ConfigureAwait(false); } } public async Task<ChromeProcessInfo> OpenChromeProfile(ChromeDriverConfig config) { ChromeProcessInfo res = null; await Task.Run(() => res = ChromeProfilesWorker.OpenChromeProfile(config)).ConfigureAwait(false); // userDir, Port, isHeadless)); return res; } public void CloseSync() { BrowserDevTools?.CloseSync(); if (IsConnected) { DevTools.Disconnect(); IsConnected = false; } if (ChromeProcess?.Proc != null && !ChromeProcess.Proc.HasExited) { try { ChromeProcess.Proc.CloseMainWindow(); ChromeProcess.Proc.Close(); } catch { try { ChromeProcess.Proc.Kill(); } catch { // ignored } } try { while (!ChromeProcess.Proc.HasExited) { Thread.Sleep(250); } } catch { // ignored } } ChromeProcess?.Proc?.Dispose(); ChromeProcess?.ProcWithJobObject?.TerminateProc(); ChromeProcess = null; Thread.Sleep(1000); if (IsTempProfile && !string.IsNullOrWhiteSpace(UserDir)) { try { if (Directory.Exists(UserDir)) Directory.Delete(UserDir, true); } catch { Thread.Sleep(3000); try { if (Directory.Exists(UserDir)) Directory.Delete(UserDir, true); } catch { // ignored } } } } public async Task<string> Close(CancellationToken cancellationToken = default(CancellationToken)) { try { if (BrowserDevTools != null) await BrowserDevTools.Close(cancellationToken).ConfigureAwait(false); } catch { // ignored } if (IsConnected) await Disconnect().ConfigureAwait(false); if (ChromeProcess?.Proc != null && !ChromeProcess.Proc.HasExited) { try { ChromeProcess.Proc.CloseMainWindow(); ChromeProcess.Proc.Close(); } catch { try { ChromeProcess.Proc.Kill(); } catch { // ignored } } try { while (!ChromeProcess.Proc.HasExited) { await Task.Delay(250).ConfigureAwait(false); } } catch { // } } ChromeProcess?.Proc?.Dispose(); if (ChromeProcess?.ProcWithJobObject != null) { ChromeProcess.ProcWithJobObject.TerminateProc(); } ChromeProcess = null; await Task.Delay(1000).ConfigureAwait(false); if (IsTempProfile && !string.IsNullOrWhiteSpace(UserDir)) { try { if (Directory.Exists(UserDir)) Directory.Delete(UserDir, true); } catch { await Task.Delay(3000).ConfigureAwait(false); try { if (Directory.Exists(UserDir)) Directory.Delete(UserDir, true); } catch { // ignored } } } return "ok"; } public async Task<string> GetPageSource(CancellationToken cancellationToken = default(CancellationToken)) { var res = await WindowCommands.GetPageSource(null, cancellationToken).ConfigureAwait(false); return res; } public async Task<string> GetTitle(CancellationToken cancellationToken = default(CancellationToken)) { var res = await WindowCommands.GetTitle(null, cancellationToken).ConfigureAwait(false); return res; } protected void SubscribeToDevToolsSessionEvent() { DevTools.Session.DevToolsEvent += DevToolsSessionEvent; } protected void UnsubscribeDevToolsSessionEvent() { if (DevTools.Session != null) DevTools.Session.DevToolsEvent -= DevToolsSessionEvent; } private void DevToolsSessionEvent(object sender, string methodName, JToken eventData) { DevToolsEvent?.Invoke(sender, methodName, eventData); } public async Task Disconnect(CancellationToken cancellationToken = default(CancellationToken)) { await Task.Run(() => DevTools.Disconnect()).ConfigureAwait(false); IsConnected = false; //DoConnectWhenCheckConnected = true; } public async Task<DevToolsCommandResult> SendDevToolsCommand(DevToolsCommandData commandData, CancellationToken cancellationToken = default(CancellationToken)) { try { var res = await DevTools.Session.SendCommand(commandData.CommandName, commandData.Params, cancellationToken, commandData.MillisecondsTimeout).ConfigureAwait(false); return new DevToolsCommandResult { Id = commandData.Id, Result = res }; } catch (Exception ex) { return new DevToolsCommandResult { Id = commandData.Id, Error = ex.ToString() }; } } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonPlayer.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // Represents a player, identified by actorID (a.k.a. ActorNumber). // Caches properties of a player. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using ExitGames.Client.Photon; using UnityEngine; using Hashtable = ExitGames.Client.Photon.Hashtable; /// <summary> /// Summarizes a "player" within a room, identified (in that room) by actorID. /// </summary> /// <remarks> /// Each player has an actorId (or ID), valid for that room. It's -1 until it's assigned by server. /// Each client can set it's player's custom properties with SetCustomProperties, even before being in a room. /// They are synced when joining a room. /// </remarks> /// \ingroup publicApi public class PhotonPlayer : IComparable<PhotonPlayer>, IComparable<int>, IEquatable<PhotonPlayer>, IEquatable<int> { /// <summary>This player's actorID</summary> public int ID { get { return this.actorID; } } /// <summary>Identifier of this player in current room.</summary> private int actorID = -1; private string nameField = ""; /// <summary>Nickname of this player.</summary> /// <remarks>Set the PhotonNetwork.playerName to make the name synchronized in a room.</remarks> public string NickName { get { return this.nameField; } set { if (!IsLocal) { Debug.LogError("Error: Cannot change the name of a remote player!"); return; } if (string.IsNullOrEmpty(value) || value.Equals(this.nameField)) { return; } this.nameField = value; PhotonNetwork.playerName = value; // this will sync the local player's name in a room } } /// <summary>UserId of the player, available when the room got created with RoomOptions.PublishUserId = true.</summary> /// <remarks>Useful for PhotonNetwork.FindFriends and blocking slots in a room for expected players (e.g. in PhotonNetwork.CreateRoom).</remarks> public string UserId { get; internal set; } /// <summary>Only one player is controlled by each client. Others are not local.</summary> public readonly bool IsLocal = false; /// <summary> /// True if this player is the Master Client of the current room. /// </summary> /// <remarks> /// See also: PhotonNetwork.masterClient. /// </remarks> public bool IsMasterClient { get { return (PhotonNetwork.networkingPeer.mMasterClientId == this.ID); } } /// <summary>Players might be inactive in a room when PlayerTTL for a room is > 0. If true, the player is not getting events from this room (now) but can return later.</summary> public bool IsInactive { get; set; } // needed for rejoins /// <summary>Read-only cache for custom properties of player. Set via PhotonPlayer.SetCustomProperties.</summary> /// <remarks> /// Don't modify the content of this Hashtable. Use SetCustomProperties and the /// properties of this class to modify values. When you use those, the client will /// sync values with the server. /// </remarks> /// <see cref="SetCustomProperties"/> public Hashtable CustomProperties { get; internal set; } /// <summary>Creates a Hashtable with all properties (custom and "well known" ones).</summary> /// <remarks>If used more often, this should be cached.</remarks> public Hashtable AllProperties { get { Hashtable allProps = new Hashtable(); allProps.Merge(this.CustomProperties); allProps[ActorProperties.PlayerName] = this.NickName; return allProps; } } /// <summary>Can be used to store a reference that's useful to know "by player".</summary> /// <remarks>Example: Set a player's character as Tag by assigning the GameObject on Instantiate.</remarks> public object TagObject; /// <summary> /// Creates a PhotonPlayer instance. /// </summary> /// <param name="isLocal">If this is the local peer's player (or a remote one).</param> /// <param name="actorID">ID or ActorNumber of this player in the current room (a shortcut to identify each player in room)</param> /// <param name="name">Name of the player (a "well known property").</param> public PhotonPlayer(bool isLocal, int actorID, string name) { this.CustomProperties = new Hashtable(); this.IsLocal = isLocal; this.actorID = actorID; this.nameField = name; } /// <summary> /// Internally used to create players from event Join /// </summary> protected internal PhotonPlayer(bool isLocal, int actorID, Hashtable properties) { this.CustomProperties = new Hashtable(); this.IsLocal = isLocal; this.actorID = actorID; this.InternalCacheProperties(properties); } /// <summary> /// Makes PhotonPlayer comparable /// </summary> public override bool Equals(object p) { PhotonPlayer pp = p as PhotonPlayer; return (pp != null && this.GetHashCode() == pp.GetHashCode()); } public override int GetHashCode() { return this.ID; } /// <summary> /// Used internally, to update this client's playerID when assigned. /// </summary> internal void InternalChangeLocalID(int newID) { if (!this.IsLocal) { Debug.LogError("ERROR You should never change PhotonPlayer IDs!"); return; } this.actorID = newID; } /// <summary> /// Caches custom properties for this player. /// </summary> internal void InternalCacheProperties(Hashtable properties) { if (properties == null || properties.Count == 0 || this.CustomProperties.Equals(properties)) { return; } if (properties.ContainsKey(ActorProperties.PlayerName)) { this.nameField = (string)properties[ActorProperties.PlayerName]; } if (properties.ContainsKey(ActorProperties.UserId)) { this.UserId = (string)properties[ActorProperties.UserId]; } if (properties.ContainsKey(ActorProperties.IsInactive)) { this.IsInactive = (bool)properties[ActorProperties.IsInactive]; //TURNBASED new well-known propery for players } this.CustomProperties.MergeStringKeys(properties); this.CustomProperties.StripKeysWithNullValues(); } /// <summary> /// Updates the this player's Custom Properties with new/updated key-values. /// </summary> /// <remarks> /// Custom Properties are a key-value set (Hashtable) which is available to all players in a room. /// They can relate to the room or individual players and are useful when only the current value /// of something is of interest. For example: The map of a room. /// All keys must be strings. /// /// The Room and the PhotonPlayer class both have SetCustomProperties methods. /// Also, both classes offer access to current key-values by: customProperties. /// /// Always use SetCustomProperties to change values. /// To reduce network traffic, set only values that actually changed. /// New properties are added, existing values are updated. /// Other values will not be changed, so only provide values that changed or are new. /// /// To delete a named (custom) property of this room, use null as value. /// /// Locally, SetCustomProperties will update it's cache without delay. /// Other clients are updated through Photon (the server) with a fitting operation. /// /// <b>Check and Swap</b> /// /// SetCustomProperties have the option to do a server-side Check-And-Swap (CAS): /// Values only get updated if the expected values are correct. /// The expectedValues can be different key/values than the propertiesToSet. So you can /// check some key and set another key's value (if the check succeeds). /// /// If the client's knowledge of properties is wrong or outdated, it can't set values with CAS. /// This can be useful to keep players from concurrently setting values. For example: If all players /// try to pickup some card or item, only one should get it. With CAS, only the first SetProperties /// gets executed server-side and any other (sent at the same time) fails. /// /// The server will broadcast successfully changed values and the local "cache" of customProperties /// only gets updated after a roundtrip (if anything changed). /// /// You can do a "webForward": Photon will send the changed properties to a WebHook defined /// for your application. /// /// <b>OfflineMode</b> /// /// While PhotonNetwork.offlineMode is true, the expectedValues and webForward parameters are ignored. /// In OfflineMode, the local customProperties values are immediately updated (without the roundtrip). /// </remarks> /// <param name="propertiesToSet">The new properties to be set. </param> /// <param name="expectedValues">At least one property key/value set to check server-side. Key and value must be correct. Ignored in OfflineMode.</param> /// <param name="webForward">Set to true, to forward the set properties to a WebHook, defined for this app (in Dashboard). Ignored in OfflineMode.</param> public void SetCustomProperties(Hashtable propertiesToSet, Hashtable expectedValues = null, bool webForward = false) { if (propertiesToSet == null) { return; } Hashtable customProps = propertiesToSet.StripToStringKeys() as Hashtable; Hashtable customPropsToCheck = expectedValues.StripToStringKeys() as Hashtable; // no expected values -> set and callback bool noCas = customPropsToCheck == null || customPropsToCheck.Count == 0; bool inOnlineRoom = this.actorID > 0 && !PhotonNetwork.offlineMode; if (noCas) { this.CustomProperties.Merge(customProps); this.CustomProperties.StripKeysWithNullValues(); } if (inOnlineRoom) { PhotonNetwork.networkingPeer.OpSetPropertiesOfActor(this.actorID, customProps, customPropsToCheck, webForward); } if (!inOnlineRoom || noCas) { this.InternalCacheProperties(customProps); NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerPropertiesChanged, this, customProps); } } /// <summary> /// Try to get a specific player by id. /// </summary> /// <param name="ID">ActorID</param> /// <returns>The player with matching actorID or null, if the actorID is not in use.</returns> public static PhotonPlayer Find(int ID) { if (PhotonNetwork.networkingPeer != null) { return PhotonNetwork.networkingPeer.GetPlayerWithId(ID); } return null; } public PhotonPlayer Get(int id) { return PhotonPlayer.Find(id); } public PhotonPlayer GetNext() { return GetNextFor(this.ID); } public PhotonPlayer GetNextFor(PhotonPlayer currentPlayer) { if (currentPlayer == null) { return null; } return GetNextFor(currentPlayer.ID); } public PhotonPlayer GetNextFor(int currentPlayerId) { if (PhotonNetwork.networkingPeer == null || PhotonNetwork.networkingPeer.mActors == null || PhotonNetwork.networkingPeer.mActors.Count < 2) { return null; } Dictionary<int, PhotonPlayer> players = PhotonNetwork.networkingPeer.mActors; int nextHigherId = int.MaxValue; // we look for the next higher ID int lowestId = currentPlayerId; // if we are the player with the highest ID, there is no higher and we return to the lowest player's id foreach (int playerid in players.Keys) { if (playerid < lowestId) { lowestId = playerid; // less than any other ID (which must be at least less than this player's id). } else if (playerid > currentPlayerId && playerid < nextHigherId) { nextHigherId = playerid; // more than our ID and less than those found so far. } } //UnityEngine.Debug.LogWarning("Debug. " + currentPlayerId + " lower: " + lowestId + " higher: " + nextHigherId + " "); //UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(currentPlayerId)); //UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(lowestId)); //if (nextHigherId != int.MaxValue) UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(nextHigherId)); return (nextHigherId != int.MaxValue) ? players[nextHigherId] : players[lowestId]; } #region IComparable implementation public int CompareTo (PhotonPlayer other) { if ( other == null) { return 0; } return this.GetHashCode().CompareTo(other.GetHashCode()); } public int CompareTo (int other) { return this.GetHashCode().CompareTo(other); } #endregion #region IEquatable implementation public bool Equals (PhotonPlayer other) { if ( other == null) { return false; } return this.GetHashCode().Equals(other.GetHashCode()); } public bool Equals (int other) { return this.GetHashCode().Equals(other); } #endregion /// <summary> /// Brief summary string of the PhotonPlayer. Includes name or player.ID and if it's the Master Client. /// </summary> public override string ToString() { if (string.IsNullOrEmpty(this.NickName)) { return string.Format("#{0:00}{1}{2}", this.ID, this.IsInactive ? " (inactive)" : " ", this.IsMasterClient ? "(master)":""); } return string.Format("'{0}'{1}{2}", this.NickName, this.IsInactive ? " (inactive)" : " ", this.IsMasterClient ? "(master)" : ""); } /// <summary> /// String summary of the PhotonPlayer: player.ID, name and all custom properties of this user. /// </summary> /// <remarks> /// Use with care and not every frame! /// Converts the customProperties to a String on every single call. /// </remarks> public string ToStringFull() { return string.Format("#{0:00} '{1}'{2} {3}", this.ID, this.NickName, this.IsInactive ? " (inactive)" : "", this.CustomProperties.ToStringFull()); } #region Obsoleted variable names [Obsolete("Please use NickName (updated case for naming).")] public string name { get { return this.NickName; } set { this.NickName = value; } } [Obsolete("Please use UserId (updated case for naming).")] public string userId { get { return this.UserId; } internal set { this.UserId = value; } } [Obsolete("Please use IsLocal (updated case for naming).")] public bool isLocal { get { return this.IsLocal; } } [Obsolete("Please use IsMasterClient (updated case for naming).")] public bool isMasterClient { get { return this.IsMasterClient; } } [Obsolete("Please use IsInactive (updated case for naming).")] public bool isInactive { get { return this.IsInactive; } set { this.IsInactive = value; } } [Obsolete("Please use CustomProperties (updated case for naming).")] public Hashtable customProperties { get { return this.CustomProperties; } internal set { this.CustomProperties = value; } } [Obsolete("Please use AllProperties (updated case for naming).")] public Hashtable allProperties { get { return this.AllProperties; } } #endregion }
/* transpiled with BefunCompile v1.3.0 (c) 2017 */ public static class Program { private static readonly string _g = "Ah+LCAAAAAAABACT7+ZgAAEWhrc3HLNvG4gwPNj/aOnLpce6Y6x9BQ++2fS7z7rFLEe77aJh8LZ5nx6rt+v5ZlxeumHSpRr5Iye+FSct+a5ivf3mqYwptbt+/vz76vX6"+ "N4/fv149e82L7/tj4v+eeOXJtiHdnWGogwObUw+EnX1we8G5TZMj2vLm3FL/aFKirliyPPQF202FtlXaq9+V3X66kC/WY6FvcOu2M8lZy9Zn9adnGq/6VPahMkDmbtyy"+ "yaUZyTOvz36+W+BWSd48p21/jyTe3Ci+rF9+3x6LWdsXZjnPiLP5/+rshA235+4p9PV6sOr8na1zfH/XbntuqPo+p058hlHFjrVsmxw3VqRVlVeaZjlbWvvNjpiSu6Jc"+ "Ysvh0o0X4zfXPfL6+9WF12f2pk7FZS8z5qitj8jnK6yuEZ/mVvp3iuUr1qerrz26W3NtHX+G+KsZ310FlsdKfF/7cQV/gLD+iritsx5arL3/10ru3OU7Yslz57fmCe1a"+ "lfFIZcvRTQHnpk+O54pwCzv6+2H737t/pL8UmFWr/BV3lT4XtNbnv+TJ+u8FLW2r+7bf2qP13dl06609et9Xny1y9eQ+tS7fdU+D6y+RUulz1/tWtvzN/GcXaXq6faPn"+ "f75dN777yvYs/xe2s3zH14/sevJ84QmazAwAB/3uX5ICAAA="; private static readonly long[] g = System.Array.ConvertAll(zd(System.Convert.FromBase64String(_g)),b=>(long)b); private static byte[]zd(byte[]o){byte[]d=System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Skip(o, 1));for(int i=0;i<o[0];i++)d=zs(d);return d;} private static byte[]zs(byte[]o){using(var c=new System.IO.MemoryStream(o)) using(var z=new System.IO.Compression.GZipStream(c,System.IO.Compression.CompressionMode.Decompress)) using(var r=new System.IO.MemoryStream()){z.CopyTo(r);return r.ToArray();}} private static long gr(long x,long y){return(x>=0&&y>=0&&x<400&&y<518)?g[y*400+x]:0;} private static void gw(long x,long y,long v){if(x>=0&&y>=0&&x<400&&y<518)g[y*400+x]=v;} private static long td(long a,long b){ return (b==0)?0:(a/b); } private static long tm(long a,long b){ return (b==0)?0:(a%b); } private static System.Collections.Generic.Stack<long> s=new System.Collections.Generic.Stack<long>(); private static long sp(){ return (s.Count==0)?0:s.Pop(); } private static void sa(long v){ s.Push(v); } private static long sr(){ return (s.Count==0)?0:s.Peek(); } static void Main(string[]args) { long t0,t1; gw(1,0,400); gw(2,0,500); gw(0,0,200000); gw(3,0,2); gw(0,3,32); gw(1,3,32); _1: gw(tm(gr(3,0),gr(1,0)),(td(gr(3,0),gr(1,0)))+3,88); sa(gr(3,0)+gr(3,0)); sa((gr(3,0)+gr(3,0))<gr(0,0)?1:0); _2: if(sp()!=0)goto _32;else goto _3; _3: sp(); _4: sa(gr(3,0)+1); sa(gr(3,0)+1); gw(3,0,gr(3,0)+1); sa(tm(sp(),gr(1,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(1,0))); sa(sp()+3L); {long v0=sp();t0=gr(sp(),v0);} t0-=32; if((t0)!=0)goto _6;else goto _4; _6: if(gr(0,0)>gr(3,0))goto _1;else goto _7; _7: gw(4,0,0); gw(3,0,0); _8: sa(gr(3,0)+1); sa(gr(3,0)+1); gw(3,0,gr(3,0)+1); sa(tm(sp(),gr(1,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(1,0))); sa(sp()+3L); {long v0=sp();t0=gr(sp(),v0);} t0-=88; if((t0)!=0)goto _8;else goto _10; _10: sa(gr(3,0)); sa(gr(4,0)); sa(gr(4,0)); gw(4,0,gr(4,0)+1); sa(tm(sp(),gr(1,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(1,0))); sa(sp()+3L); {long v0=sp();long v1=sp();gw(v1,v0,sp());} if(gr(0,0)>gr(3,0))goto _8;else goto _11; _11: gw(tm(gr(4,0)-1,gr(1,0)),(td(gr(4,0)-1,gr(1,0)))+3,0); gw(4,0,0); gw(5,0,0); sa(1); sa(1); sa(tm(1,gr(tm(gr(4,0),gr(1,0)),(td(gr(4,0),gr(1,0)))+3))); _12: if(sp()!=0)goto _13;else goto _31; _13: sa(sr()); sa(gr(4,0)+1); sa(gr(4,0)+1); gw(4,0,gr(4,0)+1); sa(tm(sp(),gr(1,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(1,0))); sa(sp()+3L); {long v0=sp();t0=gr(sp(),v0);} sa((sp()<t0)?1:0); t1=sp(); if((t1)!=0)goto _14;else goto _30; _14: sp(); if(gr(5,0)!=4)goto _20;else goto _15; _15: gw(8,0,0); sa(sr()); sa(sr()); gw(6,0,sr()+4); gw(7,0,sp()); sa(sp()-3L); _16: if((sr()-gr(7,0))!=0)goto _22;else goto _17; _17: t0=gr(8,0)-3; gw(8,0,gr(8,0)+1); if((t0)!=0)goto _18;else goto _21; _18: sa(sp()+1L); if((sr()-gr(6,0))!=0)goto _16;else goto _19; _19: sp(); _20: gw(4,0,0); gw(5,0,0); sa(sp()+4L); sa(sr()); sa(tm(sr(),gr(tm(gr(4,0),gr(1,0)),(td(gr(4,0),gr(1,0)))+3))); goto _12; _21: sa(sp()-3L); System.Console.Out.Write("{0} ", (long)(sp())); sp(); return; _22: gw(4,0,0); gw(5,0,0); sa(sr()); _23: if((tm(sr(),gr(tm(gr(4,0),gr(1,0)),(td(gr(4,0),gr(1,0)))+3)))!=0)goto _24;else goto _29; _24: sa(sr()); sa(gr(4,0)+1); sa(gr(4,0)+1); gw(4,0,gr(4,0)+1); sa(tm(sp(),gr(1,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(1,0))); sa(sp()+3L); {long v0=sp();t0=gr(sp(),v0);} sa((sp()<t0)?1:0); t1=sp(); if((t1)!=0)goto _25;else goto _23; _25: sp(); if(gr(5,0)!=4)goto _26;else goto _28; _26: gw(8,0,0); if(sr()<gr(7,0))goto _27;else goto _19; _27: if(gr(8,0)!=4)goto _18;else goto _21; _28: gw(8,0,gr(8,0)+1); goto _27; _29: sa(td(sp(),gr(tm(gr(4,0),gr(1,0)),(td(gr(4,0),gr(1,0)))+3))); gw(5,0,gr(5,0)+1); goto _24; _30: sa(tm(sr(),gr(tm(gr(4,0),gr(1,0)),(td(gr(4,0),gr(1,0)))+3))); goto _12; _31: sa(td(sp(),gr(tm(gr(4,0),gr(1,0)),(td(gr(4,0),gr(1,0)))+3))); gw(5,0,gr(5,0)+1); goto _13; _32: sa(sr()); sa(32); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(tm(sr(),gr(1,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(1,0))); sa(sp()+3L); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sp()+gr(3,0)); sa(sr()<gr(0,0)?1:0); goto _2; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> public partial class FileStream : Stream { /// <summary>File mode.</summary> private FileMode _mode; /// <summary>Advanced options requested when opening the file.</summary> private FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private long _appendStart = -1; /// <summary> /// Extra state used by the file stream when _useAsyncIO is true. This includes /// the semaphore used to serialize all operation, the buffer/offset/count provided by the /// caller for ReadAsync/WriteAsync operations, and the last successful task returned /// synchronously from ReadAsync which can be reused if the count matches the next request. /// Only initialized when <see cref="_useAsyncIO"/> is true. /// </summary> private AsyncState _asyncState; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _mode = mode; _options = options; if (_useAsyncIO) _asyncState = new AsyncState(); // Translate the arguments into arguments for an open call. Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, share, options); // If the file gets created a new, we'll select the permissions for it. Most Unix utilities by default use 666 (read and // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the // actual permissions will typically be less than what we select here. const Interop.Sys.Permissions OpenPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; // Open the file and store the safe handle. return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions); } /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="mode">How the file should be opened.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> private void Init(FileMode mode, FileShare share) { _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH; if (Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB) < 0) { // The only error we care about is EWOULDBLOCK, which indicates that the file is currently locked by someone // else and we would block trying to access it. Other errors, such as ENOTSUP (locking isn't supported) or // EACCES (the file system doesn't allow us to lock), will only hamper FileStream's usage without providing value, // given again that this is only advisory / best-effort. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EWOULDBLOCK) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } // These provide hints around how the file will be accessed. Specifying both RandomAccess // and Sequential together doesn't make sense as they are two competing options on the same spectrum, // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided). Interop.Sys.FileAdvice fadv = (_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM : (_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL : 0; if (fadv != 0) { CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv), ignoreNotSupported: true); // just a hint. } if (_mode == FileMode.Append) { // Jump to the end of the file if opened as Append. _appendStart = SeekCore(_fileHandle, 0, SeekOrigin.End); } else if (mode == FileMode.Create || mode == FileMode.Truncate) { // Truncate the file now if the file mode requires it. This ensures that the file only will be truncated // if opened successfully. CheckFileCall(Interop.Sys.FTruncate(_fileHandle, 0)); } } /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> private void InitFromHandle(SafeFileHandle handle, FileAccess access, bool useAsyncIO) { if (useAsyncIO) _asyncState = new AsyncState(); if (CanSeekCore(handle)) // use non-virtual CanSeekCore rather than CanSeek to avoid making virtual call during ctor SeekCore(handle, 0, SeekOrigin.Current); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="share">The FileShare provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileShare share, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.Sys.OpenFlags flags = default(Interop.Sys.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. case FileMode.Truncate: // We truncate the file after getting the lock break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: case FileMode.Create: // We truncate the file after getting the lock flags |= Interop.Sys.OpenFlags.O_CREAT; break; case FileMode.CreateNew: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL); break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.Sys.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.Sys.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.Sys.OpenFlags.O_WRONLY; break; } // Handle Inheritable, other FileShare flags are handled by Init if ((share & FileShare.Inheritable) == 0) { flags |= Interop.Sys.OpenFlags.O_CLOEXEC; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. // - Asynchronous: Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true // - DeleteOnClose: Doesn't have a Unix equivalent, but we approximate it in Dispose // - Encrypted: No equivalent on Unix and is ignored // - RandomAccess: Implemented after open if posix_fadvise is available // - SequentialScan: Implemented after open if posix_fadvise is available // - WriteThrough: Handled here if ((options & FileOptions.WriteThrough) != 0) { flags |= Interop.Sys.OpenFlags.O_SYNC; } return flags; } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek => CanSeekCore(_fileHandle); /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> /// <remarks> /// Separated out of CanSeek to enable making non-virtual call to this logic. /// We also pass in the file handle to allow the constructor to use this before it stashes the handle. /// </remarks> private bool CanSeekCore(SafeFileHandle fileHandle) { if (fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = Interop.Sys.LSeek(fileHandle, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0; } return _canSeek.Value; } private long GetLengthInternal() { // Get the length of the file as reported by the OS Interop.Sys.FileStatus status; CheckFileCall(Interop.Sys.FStat(_fileHandle, out status)); long length = status.Size; // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { try { if (_fileHandle != null && !_fileHandle.IsClosed) { // Flush any remaining data in the file try { FlushWriteBuffer(); } catch (IOException) when (!disposing) { // On finalization, ignore failures from trying to flush the write buffer, // e.g. if this stream is wrapping a pipe and the pipe is now broken. } // If DeleteOnClose was requested when constructed, delete the file now. // (Unix doesn't directly support DeleteOnClose, so we mimic it here.) if (_path != null && (_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed, but the // name will be removed immediately. Interop.Sys.Unlink(_path); // ignore errors; it's valid that the path may no longer exist } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { if (Interop.Sys.FSync(_fileHandle) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EROFS: case Interop.Error.EINVAL: case Interop.Error.ENOTSUP: // Ignore failures due to the FileStream being bound to a special file that // doesn't support synchronization. In such cases there's nothing to flush. break; default: throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } } private void FlushWriteBufferForWriteByte() { _asyncState?.Wait(); try { FlushWriteBuffer(); } finally { _asyncState?.Release(); } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { AssertBufferInvariants(); if (_writePos > 0) { WriteNative(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos)); _writePos = 0; } } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> private Task FlushAsyncInternal(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (CanWrite) { return Task.Factory.StartNew( state => ((FileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> private void SetLengthInternal(long value) { FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(_fileHandle, value, SeekOrigin.Begin); } CheckFileCall(Interop.Sys.FTruncate(_fileHandle, value)); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(_fileHandle, origPos, SeekOrigin.Begin); } else { SeekCore(_fileHandle, 0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> private int ReadSpan(Span<byte> destination) { PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; bool readFromOS = false; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!CanSeek || (destination.Length >= _bufferLength)) { // Read directly into the user's buffer _readPos = _readLength = 0; return ReadNative(destination); } else { // Read into our buffer. _readLength = numBytesAvailable = ReadNative(GetBuffer()); _readPos = 0; if (numBytesAvailable == 0) { return 0; } // Note that we did an OS read as part of this Read, so that later // we don't try to do one again if what's in the buffer doesn't // meet the user's request. readFromOS = true; } } // Now that we know there's data in the buffer, read from it into the user's buffer. Debug.Assert(numBytesAvailable > 0, "Data must be in the buffer to be here"); int bytesRead = Math.Min(numBytesAvailable, destination.Length); new Span<byte>(GetBuffer(), _readPos, bytesRead).CopyTo(destination); _readPos += bytesRead; // We may not have had enough data in the buffer to completely satisfy the user's request. // While Read doesn't require that we return as much data as the user requested (any amount // up to the requested count is fine), FileStream on Windows tries to do so by doing a // subsequent read from the file if we tried to satisfy the request with what was in the // buffer but the buffer contained less than the requested count. To be consistent with that // behavior, we do the same thing here on Unix. Note that we may still get less the requested // amount, as the OS may give us back fewer than we request, either due to reaching the end of // file, or due to its own whims. if (!readFromOS && bytesRead < destination.Length) { Debug.Assert(_readPos == _readLength, "bytesToRead should only be < destination.Length if numBytesAvailable < destination.Length"); _readPos = _readLength = 0; // no data left in the read buffer bytesRead += ReadNative(destination.Slice(bytesRead)); } return bytesRead; } /// <summary>Unbuffered, reads a block of bytes from the file handle into the given buffer.</summary> /// <param name="buffer">The buffer into which data from the file is read.</param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadNative(Span<byte> buffer) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer)) { bytesRead = CheckFileCall(Interop.Sys.Read(_fileHandle, bufPtr, buffer.Length)); Debug.Assert(bytesRead <= buffer.Length); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="destination">The buffer to write the data into.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="synchronousResult">If the operation completes synchronously, the number of bytes read.</param> /// <returns>A task that represents the asynchronous read operation.</returns> private Task<int> ReadAsyncInternal(Memory<byte> destination, CancellationToken cancellationToken, out int synchronousResult) { Debug.Assert(_useAsyncIO); if (!CanRead) // match Windows behavior; this gets thrown synchronously { throw Error.GetReadNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough data in our buffer // to satisfy the full request of the caller, hand back the buffered data. // While it would be a legal implementation of the Read contract, we don't // hand back here less than the amount requested so as to match the behavior // in ReadCore that will make a native call to try to fulfill the remainder // of the request. if (waitTask.Status == TaskStatus.RanToCompletion) { int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable >= destination.Length) { try { PrepareForReading(); new Span<byte>(GetBuffer(), _readPos, destination.Length).CopyTo(destination.Span); _readPos += destination.Length; synchronousResult = destination.Length; return null; } catch (Exception exc) { synchronousResult = 0; return Task.FromException<int>(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. synchronousResult = 0; _asyncState.Memory = destination; return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position /length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { Memory<byte> memory = thisRef._asyncState.Memory; thisRef._asyncState.Memory = default(Memory<byte>); return thisRef.ReadSpan(memory.Span); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary>Reads from the file handle into the buffer, overwriting anything in it.</summary> private int FillReadBufferForReadByte() { _asyncState?.Wait(); try { return ReadNative(_buffer); } finally { _asyncState?.Release(); } } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private void WriteSpan(ReadOnlySpan<byte> source) { PrepareForWriting(); // If no data is being written, nothing more to do. if (source.Length == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= source.Length) { source.CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos)); _writePos += source.Length; return; } else if (spaceRemaining > 0) { source.Slice(0, spaceRemaining).CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos)); _writePos += spaceRemaining; source = source.Slice(spaceRemaining); } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (source.Length >= _bufferLength) { WriteNative(source); } else { source.CopyTo(new Span<byte>(GetBuffer())); _writePos = source.Length; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private unsafe void WriteNative(ReadOnlySpan<byte> source) { VerifyOSHandlePosition(); fixed (byte* bufPtr = &MemoryMarshal.GetReference(source)) { int offset = 0; int count = source.Length; while (count > 0) { int bytesWritten = CheckFileCall(Interop.Sys.Write(_fileHandle, bufPtr + offset, count)); _filePosition += bytesWritten; offset += bytesWritten; count -= bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="source">The buffer to write data from.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> private Task WriteAsyncInternal(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { Debug.Assert(_useAsyncIO); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanWrite) // match Windows behavior; this gets thrown synchronously { throw Error.GetWriteNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough space in our buffer // to buffer the entire write request, then do so and we're done. if (waitTask.Status == TaskStatus.RanToCompletion) { int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= source.Length) { try { PrepareForWriting(); source.Span.CopyTo(new Span<byte>(GetBuffer(), _writePos, source.Length)); _writePos += source.Length; return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. _asyncState.ReadOnlyMemory = source; return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position/length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { ReadOnlyMemory<byte> readOnlyMemory = thisRef._asyncState.ReadOnlyMemory; thisRef._asyncState.ReadOnlyMemory = default(ReadOnlyMemory<byte>); thisRef.WriteSpan(readOnlyMemory.Span); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } if (!CanSeek) { throw Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(_fileHandle, 0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(_fileHandle, offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(_fileHandle, oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(SafeFileHandle fileHandle, long offset, SeekOrigin origin) { Debug.Assert(!fileHandle.IsClosed && (GetType() != typeof(FileStream) || CanSeekCore(fileHandle))); // verify that we can seek, but only if CanSeek won't be a virtual call (which could happen in the ctor) Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = CheckFileCall(Interop.Sys.LSeek(fileHandle, offset, (Interop.Sys.SeekWhence)(int)origin)); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } private long CheckFileCall(long result, bool ignoreNotSupported = false) { if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (!(ignoreNotSupported && errorInfo.Error == Interop.Error.ENOTSUP)) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } return result; } private int CheckFileCall(int result, bool ignoreNotSupported = false) { CheckFileCall((long)result, ignoreNotSupported); return result; } /// <summary>State used when the stream is in async mode.</summary> private sealed class AsyncState : SemaphoreSlim { internal ReadOnlyMemory<byte> ReadOnlyMemory; internal Memory<byte> Memory; /// <summary>Initialize the AsyncState.</summary> internal AsyncState() : base(initialCount: 1, maxCount: 1) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Diagnostics; using System.IO; using System.Text; using System.Collections; namespace System.Xml.Xsl.XsltOld { internal sealed class ReaderOutput : XmlReader, IRecordOutput { private Processor _processor; private readonly XmlNameTable _nameTable; // Main node + Fields Collection private RecordBuilder _builder; private BuilderInfo _mainNode; private ArrayList _attributeList; private int _attributeCount; private BuilderInfo _attributeValue; // OutputScopeManager private OutputScopeManager _manager; // Current position in the list private int _currentIndex; private BuilderInfo _currentInfo; // Reader state private ReadState _state = ReadState.Initial; private bool _haveRecord; // Static default record private static readonly BuilderInfo s_DefaultInfo = new BuilderInfo(); private readonly XmlEncoder _encoder = new XmlEncoder(); private XmlCharType _xmlCharType = XmlCharType.Instance; internal ReaderOutput(Processor processor) { Debug.Assert(processor != null); Debug.Assert(processor.NameTable != null); _processor = processor; _nameTable = processor.NameTable; Reset(); } // XmlReader abstract methods implementation public override XmlNodeType NodeType { get { CheckCurrentInfo(); return _currentInfo.NodeType; } } public override string Name { get { CheckCurrentInfo(); string prefix = Prefix; string localName = LocalName; if (prefix != null && prefix.Length > 0) { if (localName.Length > 0) { return _nameTable.Add(prefix + ":" + localName); } else { return prefix; } } else { return localName; } } } public override string LocalName { get { CheckCurrentInfo(); return _currentInfo.LocalName; } } public override string NamespaceURI { get { CheckCurrentInfo(); return _currentInfo.NamespaceURI; } } public override string Prefix { get { CheckCurrentInfo(); return _currentInfo.Prefix; } } public override bool HasValue { get { return XmlReader.HasValueInternal(NodeType); } } public override string Value { get { CheckCurrentInfo(); return _currentInfo.Value; } } public override int Depth { get { CheckCurrentInfo(); return _currentInfo.Depth; } } public override string BaseURI { get { return string.Empty; } } public override bool IsEmptyElement { get { CheckCurrentInfo(); return _currentInfo.IsEmptyTag; } } public override char QuoteChar { get { return _encoder.QuoteChar; } } public override bool IsDefault { get { return false; } } public override XmlSpace XmlSpace { get { return _manager != null ? _manager.XmlSpace : XmlSpace.None; } } public override string XmlLang { get { return _manager != null ? _manager.XmlLang : string.Empty; } } // Attribute Accessors public override int AttributeCount { get { return _attributeCount; } } public override string GetAttribute(string name) { int ordinal; if (FindAttribute(name, out ordinal)) { Debug.Assert(ordinal >= 0); return ((BuilderInfo)_attributeList[ordinal]).Value; } else { Debug.Assert(ordinal == -1); return null; } } public override string GetAttribute(string localName, string namespaceURI) { int ordinal; if (FindAttribute(localName, namespaceURI, out ordinal)) { Debug.Assert(ordinal >= 0); return ((BuilderInfo)_attributeList[ordinal]).Value; } else { Debug.Assert(ordinal == -1); return null; } } public override string GetAttribute(int i) { BuilderInfo attribute = GetBuilderInfo(i); return attribute.Value; } public override string this[int i] { get { return GetAttribute(i); } } public override string this[string name, string namespaceURI] { get { return GetAttribute(name, namespaceURI); } } public override bool MoveToAttribute(string name) { int ordinal; if (FindAttribute(name, out ordinal)) { Debug.Assert(ordinal >= 0); SetAttribute(ordinal); return true; } else { Debug.Assert(ordinal == -1); return false; } } public override bool MoveToAttribute(string localName, string namespaceURI) { int ordinal; if (FindAttribute(localName, namespaceURI, out ordinal)) { Debug.Assert(ordinal >= 0); SetAttribute(ordinal); return true; } else { Debug.Assert(ordinal == -1); return false; } } public override void MoveToAttribute(int i) { if (i < 0 || _attributeCount <= i) { throw new ArgumentOutOfRangeException(nameof(i)); } SetAttribute(i); } public override bool MoveToFirstAttribute() { if (_attributeCount <= 0) { Debug.Assert(_attributeCount == 0); return false; } else { SetAttribute(0); return true; } } public override bool MoveToNextAttribute() { if (_currentIndex + 1 < _attributeCount) { SetAttribute(_currentIndex + 1); return true; } return false; } public override bool MoveToElement() { if (NodeType == XmlNodeType.Attribute || _currentInfo == _attributeValue) { SetMainNode(); return true; } return false; } // Moving through the Stream public override bool Read() { Debug.Assert(_processor != null || _state == ReadState.Closed); if (_state != ReadState.Interactive) { if (_state == ReadState.Initial) { _state = ReadState.Interactive; } else { return false; } } while (true) { // while -- to ignor empty whitespace nodes. if (_haveRecord) { _processor.ResetOutput(); _haveRecord = false; } _processor.Execute(); if (_haveRecord) { CheckCurrentInfo(); // check text nodes on whitespace; switch (this.NodeType) { case XmlNodeType.Text: if (_xmlCharType.IsOnlyWhitespace(this.Value)) { _currentInfo.NodeType = XmlNodeType.Whitespace; goto case XmlNodeType.Whitespace; } Debug.Assert(this.Value.Length != 0, "It whould be Whitespace in this case"); break; case XmlNodeType.Whitespace: if (this.Value.Length == 0) { continue; // ignoring emty text nodes } if (this.XmlSpace == XmlSpace.Preserve) { _currentInfo.NodeType = XmlNodeType.SignificantWhitespace; } break; } } else { Debug.Assert(_processor.ExecutionDone); _state = ReadState.EndOfFile; Reset(); } return _haveRecord; } } public override bool EOF { get { return _state == ReadState.EndOfFile; } } public override void Close() { _processor = null; _state = ReadState.Closed; Reset(); } public override ReadState ReadState { get { return _state; } } // Whole Content Read Methods public override string ReadString() { string result = string.Empty; if (NodeType == XmlNodeType.Element || NodeType == XmlNodeType.Attribute || _currentInfo == _attributeValue) { if (_mainNode.IsEmptyTag) { return result; } if (!Read()) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } } StringBuilder sb = null; bool first = true; while (true) { switch (NodeType) { case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: // case XmlNodeType.CharacterEntity: if (first) { result = this.Value; first = false; } else { if (sb == null) { sb = new StringBuilder(result); } sb.Append(this.Value); } if (!Read()) throw new InvalidOperationException(SR.Xml_InvalidOperation); break; default: return (sb == null) ? result : sb.ToString(); } } } public override string ReadInnerXml() { if (ReadState == ReadState.Interactive) { if (NodeType == XmlNodeType.Element && !IsEmptyElement) { StringOutput output = new StringOutput(_processor); output.OmitXmlDecl(); int depth = Depth; Read(); // skeep begin Element while (depth < Depth) { // process content Debug.Assert(_builder != null); output.RecordDone(_builder); Read(); } Debug.Assert(NodeType == XmlNodeType.EndElement); Read(); // skeep end element output.TheEnd(); return output.Result; } else if (NodeType == XmlNodeType.Attribute) { return _encoder.AttributeInnerXml(Value); } else { Read(); } } return string.Empty; } public override string ReadOuterXml() { if (ReadState == ReadState.Interactive) { if (NodeType == XmlNodeType.Element) { StringOutput output = new StringOutput(_processor); output.OmitXmlDecl(); bool emptyElement = IsEmptyElement; int depth = Depth; // process current record output.RecordDone(_builder); Read(); // process internal elements & text nodes while (depth < Depth) { Debug.Assert(_builder != null); output.RecordDone(_builder); Read(); } // process end element if (!emptyElement) { output.RecordDone(_builder); Read(); } output.TheEnd(); return output.Result; } else if (NodeType == XmlNodeType.Attribute) { return _encoder.AttributeOuterXml(Name, Value); } else { Read(); } } return string.Empty; } // // Nametable and Namespace Helpers // public override XmlNameTable NameTable { get { Debug.Assert(_nameTable != null); return _nameTable; } } public override string LookupNamespace(string prefix) { prefix = _nameTable.Get(prefix); if (_manager != null && prefix != null) { return _manager.ResolveNamespace(prefix); } return null; } public override void ResolveEntity() { Debug.Assert(NodeType != XmlNodeType.EntityReference); if (NodeType != XmlNodeType.EntityReference) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } } public override bool ReadAttributeValue() { if (ReadState != ReadState.Interactive || NodeType != XmlNodeType.Attribute) { return false; } if (_attributeValue == null) { _attributeValue = new BuilderInfo(); _attributeValue.NodeType = XmlNodeType.Text; } if (_currentInfo == _attributeValue) { return false; } _attributeValue.Value = _currentInfo.Value; _attributeValue.Depth = _currentInfo.Depth + 1; _currentInfo = _attributeValue; return true; } // // RecordOutput interface method implementation // public Processor.OutputResult RecordDone(RecordBuilder record) { _builder = record; _mainNode = record.MainNode; _attributeList = record.AttributeList; _attributeCount = record.AttributeCount; _manager = record.Manager; _haveRecord = true; SetMainNode(); return Processor.OutputResult.Interrupt; } public void TheEnd() { // nothing here, was taken care of by RecordBuilder } // // Implementation internals // private void SetMainNode() { _currentIndex = -1; _currentInfo = _mainNode; } private void SetAttribute(int attrib) { Debug.Assert(0 <= attrib && attrib < _attributeCount); Debug.Assert(0 <= attrib && attrib < _attributeList.Count); Debug.Assert(_attributeList[attrib] is BuilderInfo); _currentIndex = attrib; _currentInfo = (BuilderInfo)_attributeList[attrib]; } private BuilderInfo GetBuilderInfo(int attrib) { if (attrib < 0 || _attributeCount <= attrib) { throw new ArgumentOutOfRangeException(nameof(attrib)); } Debug.Assert(_attributeList[attrib] is BuilderInfo); return (BuilderInfo)_attributeList[attrib]; } private bool FindAttribute(string localName, string namespaceURI, out int attrIndex) { if (namespaceURI == null) { namespaceURI = string.Empty; } if (localName == null) { localName = string.Empty; } for (int index = 0; index < _attributeCount; index++) { Debug.Assert(_attributeList[index] is BuilderInfo); BuilderInfo attribute = (BuilderInfo)_attributeList[index]; if (attribute.NamespaceURI == namespaceURI && attribute.LocalName == localName) { attrIndex = index; return true; } } attrIndex = -1; return false; } private bool FindAttribute(string name, out int attrIndex) { if (name == null) { name = string.Empty; } for (int index = 0; index < _attributeCount; index++) { Debug.Assert(_attributeList[index] is BuilderInfo); BuilderInfo attribute = (BuilderInfo)_attributeList[index]; if (attribute.Name == name) { attrIndex = index; return true; } } attrIndex = -1; return false; } private void Reset() { _currentIndex = -1; _currentInfo = s_DefaultInfo; _mainNode = s_DefaultInfo; _manager = null; } [System.Diagnostics.Conditional("DEBUG")] private void CheckCurrentInfo() { Debug.Assert(_currentInfo != null); Debug.Assert(_attributeCount == 0 || _attributeList != null); Debug.Assert((_currentIndex == -1) == (_currentInfo == _mainNode)); Debug.Assert((_currentIndex == -1) || (_currentInfo == _attributeValue || _attributeList[_currentIndex] is BuilderInfo && _attributeList[_currentIndex] == _currentInfo)); } private class XmlEncoder { private StringBuilder _buffer = null; private XmlTextEncoder _encoder = null; private void Init() { _buffer = new StringBuilder(); _encoder = new XmlTextEncoder(new StringWriter(_buffer, CultureInfo.InvariantCulture)); } public string AttributeInnerXml(string value) { if (_encoder == null) Init(); _buffer.Length = 0; // clean buffer _encoder.StartAttribute(/*save:*/false); _encoder.Write(value); _encoder.EndAttribute(); return _buffer.ToString(); } public string AttributeOuterXml(string name, string value) { if (_encoder == null) Init(); _buffer.Length = 0; // clean buffer _buffer.Append(name); _buffer.Append('='); _buffer.Append(QuoteChar); _encoder.StartAttribute(/*save:*/false); _encoder.Write(value); _encoder.EndAttribute(); _buffer.Append(QuoteChar); return _buffer.ToString(); } public char QuoteChar { get { return '"'; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.CalendarTests { // GregorianCalendar.IsLeapDay(Int32, Int32, Int32, Int32) public class GregorianCalendarIsLeapDay { private const int c_DAYS_IN_LEAP_YEAR = 366; private const int c_DAYS_IN_COMMON_YEAR = 365; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); private static readonly int[] s_daysInMonth365 = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private static readonly int[] s_daysInMonth366 = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; #region Positive tests // PosTest1: February 29 in leap year [Fact] public void PosTest1() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; bool expectedValue; bool actualValue; year = GetALeapYear(myCalendar); month = 2; day = 29; expectedValue = true; actualValue = myCalendar.IsLeapDay(year, month, day, 1); Assert.Equal(expectedValue, actualValue); } // PosTest2: February 28 in common year [Fact] public void PosTest2() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; bool expectedValue; bool actualValue; year = GetACommonYear(myCalendar); month = 2; day = 28; expectedValue = false; actualValue = myCalendar.IsLeapDay(year, month, day, 1); Assert.Equal(expectedValue, actualValue); } // PosTest3: any year, any month, any day [Fact] public void PosTest3() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; bool expectedValue; bool actualValue; year = GetAYear(myCalendar); month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; expectedValue = this.IsLeapYear(year) && 2 == month && 29 == day; actualValue = myCalendar.IsLeapDay(year, month, day, 1); Assert.Equal(expectedValue, actualValue); } // PosTest4: any day and month in maximum supported year [Fact] public void PosTest4() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; bool expectedValue; bool actualValue; year = myCalendar.MaxSupportedDateTime.Year; month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; expectedValue = this.IsLeapYear(year) && 2 == month && 29 == day; actualValue = myCalendar.IsLeapDay(year, month, day, 1); Assert.Equal(expectedValue, actualValue); } // PosTest5: any day and month in minimum supported year [Fact] public void PosTest5() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; bool expectedValue; bool actualValue; year = myCalendar.MinSupportedDateTime.Year; month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; expectedValue = this.IsLeapYear(year) && 2 == month && 29 == day; actualValue = myCalendar.IsLeapDay(year, month, day, 1); Assert.Equal(expectedValue, actualValue); } #endregion #region Negtive Tests // NegTest1: year is greater than maximum supported value [Fact] public void NegTest1() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; year = myCalendar.MaxSupportedDateTime.Year + 100; month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, 1); }); } // NegTest2: year is less than minimum supported value [Fact] public void NegTest2() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; year = myCalendar.MinSupportedDateTime.Year - 100; month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, 1); }); } // NegTest3: era is outside the range supported by the calendar [Fact] public void NegTest3() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; int era; year = this.GetAYear(myCalendar); month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; era = 2 + _generator.GetInt32(-55) % (int.MaxValue - 1); Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, era); }); } // NegTest4: month is outside the range supported by the calendar [Fact] public void NegTest4() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; int era; year = this.GetAYear(myCalendar); month = -1 * _generator.GetInt32(-55); day = 1; era = _generator.GetInt32(-55) & 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, era); }); } // NegTest5: month is outside the range supported by the calendar [Fact] public void NegTest5() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; int era; year = this.GetAYear(myCalendar); month = 13 + _generator.GetInt32(-55) % (int.MaxValue - 12); day = 1; era = _generator.GetInt32(-55) & 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, era); }); } // NegTest6: day is outside the range supported by the calendar [Fact] public void NegTest6() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; int era; year = this.GetAYear(myCalendar); month = _generator.GetInt32(-55) % 12 + 1; day = -1 * _generator.GetInt32(-55); era = _generator.GetInt32(-55) & 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, era); }); } #endregion #region Helper methods for all the tests //Indicate whether the specified year is leap year or not private bool IsLeapYear(int year) { if (0 == year % 400 || (0 != year % 100 && 0 == (year & 0x3))) { return true; } return false; } //Get a random year beween minmum supported year and maximum supported year of the specified calendar private int GetAYear(Calendar calendar) { int retVal; int maxYear, minYear; maxYear = calendar.MaxSupportedDateTime.Year; minYear = calendar.MinSupportedDateTime.Year; retVal = minYear + _generator.GetInt32(-55) % (maxYear + 1 - minYear); return retVal; } //Get a leap year of the specified calendar private int GetALeapYear(Calendar calendar) { int retVal; // A leap year is any year divisible by 4 except for centennial years(those ending in 00) // which are only leap years if they are divisible by 400. retVal = ~(~GetAYear(calendar) | 0x3); // retVal will be divisible by 4 since the 2 least significant bits will be 0 retVal = (0 != retVal % 100) ? retVal : (retVal - retVal % 400); // if retVal is divisible by 100 subtract years from it to make it divisible by 400 // if retVal was 100, 200, or 300 the above logic will result in 0 if (0 == retVal) { retVal = 400; } return retVal; } //Get a common year of the specified calendar private int GetACommonYear(Calendar calendar) { int retVal; do { retVal = GetAYear(calendar); } while ((0 == (retVal & 0x3) && 0 != retVal % 100) || 0 == retVal % 400); return retVal; } #endregion } }
using ICSharpCode.TextEditor.Undo; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace ICSharpCode.TextEditor.Document { internal sealed class DefaultDocument : IDocument { private bool readOnly; private LineManager lineTrackingStrategy; private BookmarkManager bookmarkManager; private ITextBufferStrategy textBufferStrategy; private IFormattingStrategy formattingStrategy; private FoldingManager foldingManager; private UndoStack undoStack = new UndoStack(); private ITextEditorProperties textEditorProperties = new DefaultTextEditorProperties(); private MarkerStrategy markerStrategy; private List<TextAreaUpdate> updateQueue = new List<TextAreaUpdate>(); public event EventHandler<LineLengthChangeEventArgs> LineLengthChanged { add { this.lineTrackingStrategy.LineLengthChanged += value; } remove { this.lineTrackingStrategy.LineLengthChanged -= value; } } public event EventHandler<LineCountChangeEventArgs> LineCountChanged { add { this.lineTrackingStrategy.LineCountChanged += value; } remove { this.lineTrackingStrategy.LineCountChanged -= value; } } public event EventHandler<LineEventArgs> LineDeleted { add { this.lineTrackingStrategy.LineDeleted += value; } remove { this.lineTrackingStrategy.LineDeleted -= value; } } public event DocumentEventHandler DocumentAboutToBeChanged; public event DocumentEventHandler DocumentChanged; public event EventHandler UpdateCommited; public event EventHandler TextContentChanged; public LineManager LineManager { get { return this.lineTrackingStrategy; } set { this.lineTrackingStrategy = value; } } public MarkerStrategy MarkerStrategy { get { return this.markerStrategy; } set { this.markerStrategy = value; } } public ITextEditorProperties TextEditorProperties { get { return this.textEditorProperties; } set { this.textEditorProperties = value; } } public UndoStack UndoStack { get { return this.undoStack; } } public IList<LineSegment> LineSegmentCollection { get { return this.lineTrackingStrategy.LineSegmentCollection; } } public bool ReadOnly { get { return this.readOnly; } set { this.readOnly = value; } } public ITextBufferStrategy TextBufferStrategy { get { return this.textBufferStrategy; } set { this.textBufferStrategy = value; } } public IFormattingStrategy FormattingStrategy { get { return this.formattingStrategy; } set { this.formattingStrategy = value; } } public FoldingManager FoldingManager { get { return this.foldingManager; } set { this.foldingManager = value; } } public IHighlightingStrategy HighlightingStrategy { get { return this.lineTrackingStrategy.HighlightingStrategy; } set { this.lineTrackingStrategy.HighlightingStrategy = value; } } public int TextLength { get { return this.textBufferStrategy.Length; } } public BookmarkManager BookmarkManager { get { return this.bookmarkManager; } set { this.bookmarkManager = value; } } public string TextContent { get { return this.GetText(0, this.textBufferStrategy.Length); } set { this.OnDocumentAboutToBeChanged(new DocumentEventArgs(this, 0, 0, value)); this.textBufferStrategy.SetContent(value); this.lineTrackingStrategy.SetContent(value); this.undoStack.ClearAll(); this.OnDocumentChanged(new DocumentEventArgs(this, 0, 0, value)); this.OnTextContentChanged(EventArgs.Empty); } } public int TotalNumberOfLines { get { return this.lineTrackingStrategy.TotalNumberOfLines; } } public List<TextAreaUpdate> UpdateQueue { get { return this.updateQueue; } } public void Insert(int offset, string text) { if (this.readOnly) { return; } this.OnDocumentAboutToBeChanged(new DocumentEventArgs(this, offset, -1, text)); this.textBufferStrategy.Insert(offset, text); this.lineTrackingStrategy.Insert(offset, text); this.undoStack.Push(new UndoableInsert(this, offset, text)); this.OnDocumentChanged(new DocumentEventArgs(this, offset, -1, text)); } public void Remove(int offset, int length) { if (this.readOnly) { return; } this.OnDocumentAboutToBeChanged(new DocumentEventArgs(this, offset, length)); this.undoStack.Push(new UndoableDelete(this, offset, this.GetText(offset, length))); this.textBufferStrategy.Remove(offset, length); this.lineTrackingStrategy.Remove(offset, length); this.OnDocumentChanged(new DocumentEventArgs(this, offset, length)); } public void Replace(int offset, int length, string text) { if (this.readOnly) { return; } this.OnDocumentAboutToBeChanged(new DocumentEventArgs(this, offset, length, text)); this.undoStack.Push(new UndoableReplace(this, offset, this.GetText(offset, length), text)); this.textBufferStrategy.Replace(offset, length, text); this.lineTrackingStrategy.Replace(offset, length, text); this.OnDocumentChanged(new DocumentEventArgs(this, offset, length, text)); } public char GetCharAt(int offset) { return this.textBufferStrategy.GetCharAt(offset); } public string GetText(int offset, int length) { return this.textBufferStrategy.GetText(offset, length); } public string GetText(ISegment segment) { return this.GetText(segment.Offset, segment.Length); } public int GetLineNumberForOffset(int offset) { return this.lineTrackingStrategy.GetLineNumberForOffset(offset); } public LineSegment GetLineSegmentForOffset(int offset) { return this.lineTrackingStrategy.GetLineSegmentForOffset(offset); } public LineSegment GetLineSegment(int line) { return this.lineTrackingStrategy.GetLineSegment(line); } public int GetFirstLogicalLine(int lineNumber) { return this.lineTrackingStrategy.GetFirstLogicalLine(lineNumber); } public int GetLastLogicalLine(int lineNumber) { return this.lineTrackingStrategy.GetLastLogicalLine(lineNumber); } public int GetVisibleLine(int lineNumber) { return this.lineTrackingStrategy.GetVisibleLine(lineNumber); } public int GetNextVisibleLineAbove(int lineNumber, int lineCount) { return this.lineTrackingStrategy.GetNextVisibleLineAbove(lineNumber, lineCount); } public int GetNextVisibleLineBelow(int lineNumber, int lineCount) { return this.lineTrackingStrategy.GetNextVisibleLineBelow(lineNumber, lineCount); } public TextLocation OffsetToPosition(int offset) { int lineNumberForOffset = this.GetLineNumberForOffset(offset); LineSegment lineSegment = this.GetLineSegment(lineNumberForOffset); return new TextLocation(offset - lineSegment.Offset, lineNumberForOffset); } public int PositionToOffset(TextLocation p) { if (p.Y >= this.TotalNumberOfLines) { return 0; } LineSegment lineSegment = this.GetLineSegment(p.Y); return Math.Min(this.TextLength, lineSegment.Offset + Math.Min(lineSegment.Length, p.X)); } public void UpdateSegmentListOnDocumentChange<T>(List<T> list, DocumentEventArgs e) where T : ISegment { int num = (e.Length > 0) ? e.Length : 0; int num2 = (e.Text != null) ? e.Text.Length : 0; for (int i = 0; i < list.Count; i++) { ISegment segment = list[i]; int num3 = segment.Offset; int num4 = segment.Offset + segment.Length; if (e.Offset <= num3) { num3 -= num; if (num3 < e.Offset) { num3 = e.Offset; } } if (e.Offset < num4) { num4 -= num; if (num4 < e.Offset) { num4 = e.Offset; } } if (num3 == num4) { list.RemoveAt(i); i--; } else { if (e.Offset <= num3) { num3 += num2; } if (e.Offset < num4) { num4 += num2; } segment.Offset = num3; segment.Length = num4 - num3; } } } private void OnDocumentAboutToBeChanged(DocumentEventArgs e) { if (this.DocumentAboutToBeChanged != null) { this.DocumentAboutToBeChanged(this, e); } } private void OnDocumentChanged(DocumentEventArgs e) { if (this.DocumentChanged != null) { this.DocumentChanged(this, e); } } public void RequestUpdate(TextAreaUpdate update) { if (this.updateQueue.Count == 1 && this.updateQueue[0].TextAreaUpdateType == TextAreaUpdateType.WholeTextArea) { return; } if (update.TextAreaUpdateType == TextAreaUpdateType.WholeTextArea) { this.updateQueue.Clear(); } this.updateQueue.Add(update); } public void CommitUpdate() { if (this.UpdateCommited != null) { this.UpdateCommited(this, EventArgs.Empty); } } private void OnTextContentChanged(EventArgs e) { if (this.TextContentChanged != null) { this.TextContentChanged(this, e); } } [Conditional("DEBUG")] internal static void ValidatePosition(IDocument document, TextLocation position) { document.GetLineSegment(position.Line); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; namespace Cvv.WebUtility { class Util { public static Type[] FindCompatibleTypes(Assembly assembly, Type baseType) { List<Type> types = new List<Type>(); foreach (Type type in assembly.GetTypes()) { if (type != baseType && baseType.IsAssignableFrom(type)) { types.Add(type); } } return types.ToArray(); } public static T ConvertString<T>(string stringValue) { object o = ConvertString(stringValue, typeof(T)); if (o == null) return default(T); else return (T)o; } public static object ConvertString(string stringValue, Type targetType) { if (stringValue == null) return null; if (targetType == typeof(string)) return stringValue; object value = stringValue; if (IsNullable(targetType)) { if (stringValue.Trim().Length == 0) return null; targetType = GetRealType(targetType); } if (targetType != typeof(string)) { if (targetType == typeof(double) || targetType == typeof(float)) { double doubleValue; if (!double.TryParse(stringValue.Replace(',', '.'), NumberStyles.Any, NumberFormatInfo.InvariantInfo, out doubleValue)) value = null; else value = doubleValue; } else if (targetType == typeof(decimal)) { decimal decimalValue; if (!decimal.TryParse(stringValue.Replace(',', '.'), NumberStyles.Any, NumberFormatInfo.InvariantInfo, out decimalValue)) value = null; else value = decimalValue; } else if (targetType == typeof(Int32) || targetType == typeof(Int16) || targetType == typeof(Int64) || targetType == typeof(SByte) || targetType.IsEnum) { long longValue; if (!long.TryParse(stringValue, out longValue)) value = null; else value = longValue; } else if (targetType == typeof(UInt32) || targetType == typeof(UInt16) || targetType == typeof(UInt64) || targetType == typeof(Byte)) { ulong longValue; if (!ulong.TryParse(stringValue, out longValue)) value = null; else value = longValue; } else if (targetType == typeof(DateTime)) { DateTime dateTime; if (!DateTime.TryParseExact(stringValue, new string[] { "yyyyMMdd", "yyyy-MM-dd", "yyyy.MM.dd", "yyyy/MM/dd" }, null, DateTimeStyles.NoCurrentDateDefault, out dateTime)) value = null; else value = dateTime; } else if (targetType == typeof(bool)) { value = (stringValue == "1" || stringValue.ToUpper() == "Y" || stringValue.ToUpper() == "YES" || stringValue.ToUpper() == "T" || stringValue.ToUpper() == "TRUE"); } else { value = null; } } if (value == null) return null; if (targetType.IsValueType) { if (!targetType.IsGenericType) { if (targetType.IsEnum) return Enum.ToObject(targetType, value); else return Convert.ChangeType(value, targetType); } if (targetType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type sourceType = value.GetType(); Type underlyingType = targetType.GetGenericArguments()[0]; if (sourceType == underlyingType) return value; if (underlyingType.IsEnum) { return Enum.ToObject(underlyingType, value); } else { return Convert.ChangeType(value, underlyingType); } } } return value; } public static object ConvertType(object value, Type targetType) { if (value == null) return null; if (value.GetType() == targetType) return value; if (targetType.IsValueType) { if (!targetType.IsGenericType) { if (targetType.IsEnum) return Enum.ToObject(targetType, value); else return Convert.ChangeType(value, targetType); } if (targetType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type underlyingType = targetType.GetGenericArguments()[0]; return ConvertType(value, underlyingType); } } if (targetType.IsAssignableFrom(value.GetType())) return value; else return Convert.ChangeType(value, targetType); } public static bool IsNullable(Type type) { return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static Type GetRealType(Type type) { if (IsNullable(type)) return type.GetGenericArguments()[0]; return type; } public static bool ToBool(object value) { if (value == null) { return false; } else if (value is bool) { return (bool)value; } else if (IsInteger(value)) { return (Convert.ToInt64(value) != 0); } else if (value is string) { return ((string)value).Trim().Length > 0; } else if (value is decimal) { return ((decimal)value) != 0m; } else if (IsDouble(value)) { return (Convert.ToDouble(value) != 0.0); } else if (value is DateTime) { return ((DateTime)value) != DateTime.MinValue; } else if (value is ICollection) { return ((ICollection)value).Count > 0; } else { return true; } } public static double ToDouble(object obj) { if (obj is double) return (double)obj; else return Convert.ToDouble(obj); } public static bool IsInteger(object value) { return (value is Int32 || value is Int16 || value is Int64 || value is UInt16 || value is UInt32 || value is Byte || value is SByte); } public static bool IsDouble(object value) { return (value is double || value is float); } public static bool IsNumber(object value) { return (value is double || value is float || value is decimal || IsInteger(value)); } public static bool IsString(object value) { return (value is string || value is char) ; } } }
using System.Collections.Generic; using strange.extensions.mediation.impl; using strange.extensions.signal.impl; using UnityEngine; using VisualiseR.Common; using VisualiseR.Util; namespace VisualiseR.Presentation { /// <summary> /// View of the main screen. /// </summary> public class PresentationScreenView : View { private JCsLogger Logger; internal Signal<IPlayer, ISlideMedium> NextSlideSignal = new Signal<IPlayer, ISlideMedium>(); internal Signal<IPlayer, ISlideMedium> PrevSlideSignal = new Signal<IPlayer, ISlideMedium>(); internal Signal<IPlayer, ISlideMedium> ShowSceneMenuSignal = new Signal<IPlayer, ISlideMedium>(); internal Signal<bool, string> ShowLoadingAnimationSignal = new Signal<bool, string>(); private List<byte[]> _images = new List<byte[]>(); private int _currentPos; private bool _isLoading; internal bool _isSceneMenuShown = false; private int _imageCount; internal ISlideMedium _medium { get; set; } internal IPlayer _player { get; set; } protected override void Awake() { base.Awake(); Logger = new JCsLogger(typeof(PresentationScreenView)); } public void Init(ISlideMedium slideMedium, List<byte[]> images) { _medium = slideMedium; _images = images; SetupMedium(); } private void SetupMedium() { if (_player == null) { return; } if (_player.Type == PlayerType.Host) { LoadCurrentSlide(); ShowLoadingAnimationSignal.Dispatch(false, ""); } } internal void RequestDataFromMaster() { RequestDataFromMaster(PhotonNetwork.player.ID, 0); _isLoading = true; } internal void RequestDataFromMaster(int playerId, int pos) { photonView.RPC("OnDataRequest", PhotonTargets.MasterClient, playerId, pos); Logger.DebugFormat("Player (id '{0}'): Reqested data (pos '{1}') from master", playerId, pos); } [PunRPC] void OnDataRequest(int playerId, int pos) { int Pos = -1; byte[] Image = null; if (pos == 0) { photonView.RPC("OnSyncing", PhotonPlayer.Find(playerId), _images.Count); } if (pos <= _images.Count - 1) { Pos = pos; Image = _images[Pos]; } photonView.RPC("OnDataReceived", PhotonPlayer.Find(playerId), Pos, Image); Logger.DebugFormat("Master: Send data (pos '{1}') to player (id '{0}')", playerId, pos); } [PunRPC] void OnSyncing(int imageCount) { _imageCount = imageCount; } [PunRPC] void OnDataReceived(int pos, byte[] image) { if (pos >= 0) { _images.Insert(pos, image); Logger.DebugFormat("(id '{0}'): Received images from master (image: {1}, pos: {2})", PhotonNetwork.player.ID, image.Length, pos); RequestDataFromMaster(PhotonNetwork.player.ID, ++pos); DisplayProgress(pos); return; } _isLoading = false; Logger.DebugFormat("Player (id '{0}'): Received all images from master", PhotonNetwork.player.ID); RequestSlidePositionFromMaster(); } private void RequestSlidePositionFromMaster() { photonView.RPC("OnSlidePositionRequest", PhotonTargets.MasterClient, PhotonNetwork.player.ID); Logger.DebugFormat("Player (id '{0}'): Reqested slide position from master", PhotonNetwork.player.ID); } [PunRPC] void OnSlidePositionRequest(int playerId) { photonView.RPC("OnSlidePositionReceived", PhotonPlayer.Find(playerId), _medium.CurrentPos); } [PunRPC] void OnSlidePositionReceived(int pos) { _currentPos = pos; LoadImageIntoTexture(_images[_currentPos]); ShowLoadingAnimationSignal.Dispatch(false, ""); } private void DisplayProgress(int pos) { string text = string.Format("Syncing ... ({0}/{1})", pos, _imageCount); ShowLoadingAnimationSignal.Dispatch(true, text); } private void NextSlide() { if (_player != null && _medium != null) { NextSlideSignal.Dispatch(_player, _medium); } } private void PrevSlide() { if (_player != null && _medium != null) { PrevSlideSignal.Dispatch(_player, _medium); } } internal void LoadCurrentSlide() { var currentPos = _medium.CurrentPos; LoadImageIntoTexture(_images[currentPos]); photonView.RPC("OnSlidePosChanged", PhotonTargets.Others, currentPos); } [PunRPC] void OnSlidePosChanged(int pos) { if (_images == null) { Logger.Error("Image is null"); return; } if (_isLoading) { Logger.Error("User is still loading"); return; } _currentPos = pos; LoadImageIntoTexture(_images[pos]); } void LoadImageIntoTexture(byte[] bytes) { Texture2D tex = new Texture2D(4, 4, TextureFormat.RGBA32, false); tex.LoadImage(bytes); GetComponent<Renderer>().material.mainTexture = tex; } void Update() { if (_player == null || !_player.IsHost()) { return; } if (_isSceneMenuShown) { return; } if (ButtonUtil.IsSubmitButtonPressed()) { NextSlide(); return; } if (ButtonUtil.IsCancelButtonPressed()) { ShowSceneMenu(); } } private void ShowSceneMenu() { if (_player != null && !_player.IsEmpty() && _medium != null) { ShowSceneMenuSignal.Dispatch(_player, _medium); } } void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using Tools; using Xunit; namespace System.Numerics.Tests { public static class Driver { public static BigInteger b1; public static BigInteger b2; public static BigInteger b3; public static BigInteger[][] results; private static Random s_random = new Random(100); [Fact] [OuterLoop] public static void RunTests() { int cycles = 1; //Get the BigIntegers to be testing; b1 = new BigInteger(GetRandomByteArray(s_random)); b2 = new BigInteger(GetRandomByteArray(s_random)); b3 = new BigInteger(GetRandomByteArray(s_random)); results = new BigInteger[32][]; // ...Sign results[0] = new BigInteger[3]; results[0][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uSign"); results[0][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uSign"); results[0][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uSign"); // ...Op ~ results[1] = new BigInteger[3]; results[1][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u~"); results[1][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u~"); results[1][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u~"); // ...Log10 results[2] = new BigInteger[3]; results[2][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uLog10"); results[2][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uLog10"); results[2][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uLog10"); // ...Log results[3] = new BigInteger[3]; results[3][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uLog"); results[3][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uLog"); results[3][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uLog"); // ...Abs results[4] = new BigInteger[3]; results[4][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uAbs"); results[4][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uAbs"); results[4][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uAbs"); // ...Op -- results[5] = new BigInteger[3]; results[5][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u--"); results[5][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u--"); results[5][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u--"); // ...Op ++ results[6] = new BigInteger[3]; results[6][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u++"); results[6][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u++"); results[6][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u++"); // ...Negate results[7] = new BigInteger[3]; results[7][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uNegate"); results[7][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uNegate"); results[7][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uNegate"); // ...Op - results[8] = new BigInteger[3]; results[8][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u-"); results[8][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u-"); results[8][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u-"); // ...Op + results[9] = new BigInteger[3]; results[9][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u+"); results[9][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u+"); results[9][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u+"); // ...Min results[10] = new BigInteger[9]; results[10][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bMin"); results[10][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bMin"); results[10][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bMin"); results[10][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bMin"); results[10][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bMin"); results[10][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bMin"); results[10][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bMin"); results[10][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bMin"); results[10][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bMin"); // ...Max results[11] = new BigInteger[9]; results[11][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bMax"); results[11][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bMax"); results[11][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bMax"); results[11][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bMax"); results[11][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bMax"); results[11][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bMax"); results[11][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bMax"); results[11][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bMax"); results[11][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bMax"); // ...Op >> results[12] = new BigInteger[9]; results[12][0] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b1), "b>>"); results[12][1] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b2), "b>>"); results[12][2] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b3), "b>>"); results[12][3] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b1), "b>>"); results[12][4] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b2), "b>>"); results[12][5] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b3), "b>>"); results[12][6] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b1), "b>>"); results[12][7] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b2), "b>>"); results[12][8] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b3), "b>>"); // ...Op << results[13] = new BigInteger[9]; results[13][0] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b1), "b<<"); results[13][1] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b2), "b<<"); results[13][2] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b3), "b<<"); results[13][3] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b1), "b<<"); results[13][4] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b2), "b<<"); results[13][5] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b3), "b<<"); results[13][6] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b1), "b<<"); results[13][7] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b2), "b<<"); results[13][8] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b3), "b<<"); // ...Op ^ results[14] = new BigInteger[9]; results[14][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b^"); results[14][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b^"); results[14][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b^"); results[14][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b^"); results[14][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b^"); results[14][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b^"); results[14][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b^"); results[14][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b^"); results[14][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b^"); // ...Op | results[15] = new BigInteger[9]; results[15][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b|"); results[15][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b|"); results[15][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b|"); results[15][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b|"); results[15][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b|"); results[15][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b|"); results[15][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b|"); results[15][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b|"); results[15][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b|"); // ...Op & results[16] = new BigInteger[9]; results[16][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b&"); results[16][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b&"); results[16][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b&"); results[16][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b&"); results[16][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b&"); results[16][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b&"); results[16][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b&"); results[16][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b&"); results[16][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b&"); // ...Log results[17] = new BigInteger[9]; results[17][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bLog"); results[17][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bLog"); results[17][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bLog"); results[17][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bLog"); results[17][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bLog"); results[17][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bLog"); results[17][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bLog"); results[17][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bLog"); results[17][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bLog"); // ...GCD results[18] = new BigInteger[9]; results[18][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bGCD"); results[18][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bGCD"); results[18][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bGCD"); results[18][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bGCD"); results[18][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bGCD"); results[18][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bGCD"); results[18][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bGCD"); results[18][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bGCD"); results[18][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bGCD"); // ...DivRem results[20] = new BigInteger[9]; results[20][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bDivRem"); results[20][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bDivRem"); results[20][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bDivRem"); results[20][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bDivRem"); results[20][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bDivRem"); results[20][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bDivRem"); results[20][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bDivRem"); results[20][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bDivRem"); results[20][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bDivRem"); // ...Remainder results[21] = new BigInteger[9]; results[21][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bRemainder"); results[21][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bRemainder"); results[21][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bRemainder"); results[21][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bRemainder"); results[21][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bRemainder"); results[21][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bRemainder"); results[21][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bRemainder"); results[21][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bRemainder"); results[21][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bRemainder"); // ...Op % results[22] = new BigInteger[9]; results[22][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b%"); results[22][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b%"); results[22][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b%"); results[22][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b%"); results[22][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b%"); results[22][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b%"); results[22][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b%"); results[22][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b%"); results[22][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b%"); // ...Divide results[23] = new BigInteger[9]; results[23][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bDivide"); results[23][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bDivide"); results[23][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bDivide"); results[23][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bDivide"); results[23][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bDivide"); results[23][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bDivide"); results[23][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bDivide"); results[23][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bDivide"); results[23][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bDivide"); // ...Op / results[24] = new BigInteger[9]; results[24][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b/"); results[24][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b/"); results[24][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b/"); results[24][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b/"); results[24][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b/"); results[24][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b/"); results[24][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b/"); results[24][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b/"); results[24][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b/"); // ...Multiply results[25] = new BigInteger[9]; results[25][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bMultiply"); results[25][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bMultiply"); results[25][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bMultiply"); results[25][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bMultiply"); results[25][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bMultiply"); results[25][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bMultiply"); results[25][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bMultiply"); results[25][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bMultiply"); results[25][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bMultiply"); // ...Op * results[26] = new BigInteger[9]; results[26][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b*"); results[26][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b*"); results[26][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b*"); results[26][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b*"); results[26][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b*"); results[26][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b*"); results[26][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b*"); results[26][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b*"); results[26][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b*"); // ...Subtract results[27] = new BigInteger[9]; results[27][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bSubtract"); results[27][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bSubtract"); results[27][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bSubtract"); results[27][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bSubtract"); results[27][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bSubtract"); results[27][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bSubtract"); results[27][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bSubtract"); results[27][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bSubtract"); results[27][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bSubtract"); // ...Op - results[28] = new BigInteger[9]; results[28][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b-"); results[28][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b-"); results[28][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b-"); results[28][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b-"); results[28][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b-"); results[28][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b-"); results[28][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b-"); results[28][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b-"); results[28][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b-"); // ...Add results[29] = new BigInteger[9]; results[29][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bAdd"); results[29][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bAdd"); results[29][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bAdd"); results[29][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bAdd"); results[29][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bAdd"); results[29][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bAdd"); results[29][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bAdd"); results[29][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bAdd"); results[29][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bAdd"); // ...Op + results[30] = new BigInteger[9]; results[30][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b+"); results[30][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b+"); results[30][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b+"); results[30][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b+"); results[30][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b+"); results[30][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b+"); results[30][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b+"); results[30][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b+"); results[30][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b+"); // ...ModPow results[31] = new BigInteger[27]; results[31][0] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b1 < 0 ? -b1 : b1), b1, "tModPow"); results[31][1] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b1 < 0 ? -b1 : b1), b2, "tModPow"); results[31][2] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b1 < 0 ? -b1 : b1), b3, "tModPow"); results[31][3] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b2 < 0 ? -b2 : b2), b1, "tModPow"); results[31][4] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b2 < 0 ? -b2 : b2), b2, "tModPow"); results[31][5] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b2 < 0 ? -b2 : b2), b3, "tModPow"); results[31][6] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b3 < 0 ? -b3 : b3), b1, "tModPow"); results[31][7] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b3 < 0 ? -b3 : b3), b2, "tModPow"); results[31][8] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b3 < 0 ? -b3 : b3), b3, "tModPow"); results[31][9] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b1 < 0 ? -b1 : b1), b1, "tModPow"); results[31][10] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b1 < 0 ? -b1 : b1), b2, "tModPow"); results[31][11] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b1 < 0 ? -b1 : b1), b3, "tModPow"); results[31][12] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b2 < 0 ? -b2 : b2), b1, "tModPow"); results[31][13] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b2 < 0 ? -b2 : b2), b2, "tModPow"); results[31][14] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b2 < 0 ? -b2 : b2), b3, "tModPow"); results[31][15] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b3 < 0 ? -b3 : b3), b1, "tModPow"); results[31][16] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b3 < 0 ? -b3 : b3), b2, "tModPow"); results[31][17] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b3 < 0 ? -b3 : b3), b3, "tModPow"); results[31][18] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b1 < 0 ? -b1 : b1), b1, "tModPow"); results[31][19] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b1 < 0 ? -b1 : b1), b2, "tModPow"); results[31][20] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b1 < 0 ? -b1 : b1), b3, "tModPow"); results[31][21] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b2 < 0 ? -b2 : b2), b1, "tModPow"); results[31][22] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b2 < 0 ? -b2 : b2), b2, "tModPow"); results[31][23] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b2 < 0 ? -b2 : b2), b3, "tModPow"); results[31][24] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b3 < 0 ? -b3 : b3), b1, "tModPow"); results[31][25] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b3 < 0 ? -b3 : b3), b2, "tModPow"); results[31][26] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b3 < 0 ? -b3 : b3), b3, "tModPow"); for (int i = 0; i < cycles; i++) { Worker worker = new Worker(new Random(s_random.Next()), i); worker.DoWork(); Assert.True(worker.Valid, "Verification Failed"); } } private static byte[] GetRandomByteArray(Random random) { return MyBigIntImp.GetNonZeroRandomByteArray(random, random.Next(1, 18)); } private static int Makeint(BigInteger input) { int output; if (input < 0) { input = -input; } input = input + int.MaxValue; byte[] temp = input.ToByteArray(); temp[1] = 0; temp[2] = 0; temp[3] = 0; output = BitConverter.ToInt32(temp, 0); if (output == 0) { output = 1; } return output; } } public class Worker { private Random random; private int id; public bool Valid { get; set; } public Worker(Random r, int i) { random = r; id = i; } public void DoWork() { Valid = true; BigInteger b1 = Driver.b1; BigInteger b2 = Driver.b2; BigInteger b3 = Driver.b3; BigInteger[][] results = Driver.results; var threeOrderOperations = new Action<BigInteger, BigInteger>[] { new Action<BigInteger, BigInteger>((a, expected) => { Sign(a, expected); }), new Action<BigInteger, BigInteger>((a, expected) => { Op_Not(a, expected); }), new Action<BigInteger, BigInteger>((a, expected) => { Log10(a, expected); }), new Action<BigInteger, BigInteger>((a, expected) => { Log(a, expected); }), new Action<BigInteger, BigInteger>((a, expected) => { Abs(a, expected); }), new Action<BigInteger, BigInteger>((a, expected) => { Op_Decrement(a, expected); }), new Action<BigInteger, BigInteger>((a, expected) => { Op_Increment(a, expected); }), new Action<BigInteger, BigInteger>((a, expected) => { Negate(a, expected); }), new Action<BigInteger, BigInteger>((a, expected) => { Op_Negate(a, expected); }), new Action<BigInteger, BigInteger>((a, expected) => { Op_Plus(a, expected); }) }; var nineOrderOperations = new Action<BigInteger, BigInteger, BigInteger>[] { new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Min(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Max(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_RightShift(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_LeftShift(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Xor(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Or(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_And(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Log(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { GCD(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Pow(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { DivRem(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Remainder(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Modulus(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Divide(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Divide(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Multiply(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Multiply(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Subtract(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Subtract(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Add(a, b, expected); }), new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Add(a, b, expected); }) }; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); while (stopWatch.ElapsedMilliseconds < 10000) { // Remove the Pow operation for performance reasons int op; do { op = random.Next(0, 32); } while (op == 19); int order = random.Next(0, 27); switch (op) { case 0: // Sign case 1: // Op_Not case 2: // Log10 case 3: // Log case 4: // Abs case 5: // Op_Decrement case 6: // Op_Increment case 7: // Negate case 8: // Op_Negate case 9: // Op_Plus switch (order % 3) { case 0: threeOrderOperations[op](b1, results[op][0]); break; case 1: threeOrderOperations[op](b2, results[op][1]); break; case 2: threeOrderOperations[op](b3, results[op][2]); break; default: Valid = false; break; } break; case 10: // Min case 11: // Max case 12: // Op_RightShift case 13: // Op_LeftShift case 14: // Op_Xor case 15: // Op_Or case 16: // Op_And case 17: // Log case 18: // GCD case 19: // Pow case 20: // DivRem case 21: // Remainder case 22: // Op_Modulus case 23: // Divide case 24: // Op_Divide case 25: // Multiply case 26: // Op_Multiply case 27: // Subtract case 28: // Op_Subtract case 29: // Add case 30: // Op_Add switch (order % 9) { case 0: nineOrderOperations[op-10](b1, b1, results[op][0]); break; case 1: nineOrderOperations[op-10](b1, b2, results[op][1]); break; case 2: nineOrderOperations[op-10](b1, b3, results[op][2]); break; case 3: nineOrderOperations[op-10](b2, b1, results[op][3]); break; case 4: nineOrderOperations[op-10](b2, b2, results[op][4]); break; case 5: nineOrderOperations[op-10](b2, b3, results[op][5]); break; case 6: nineOrderOperations[op-10](b3, b1, results[op][6]); break; case 7: nineOrderOperations[op-10](b3, b2, results[op][7]); break; case 8: nineOrderOperations[op-10](b3, b3, results[op][8]); break; default: Valid = false; break; } break; case 31: switch (order % 27) { case 0: ModPow(b1, b1, b1, results[31][0]); break; case 1: ModPow(b1, b1, b2, results[31][1]); break; case 2: ModPow(b1, b1, b3, results[31][2]); break; case 3: ModPow(b1, b2, b1, results[31][3]); break; case 4: ModPow(b1, b2, b2, results[31][4]); break; case 5: ModPow(b1, b2, b3, results[31][5]); break; case 6: ModPow(b1, b3, b1, results[31][6]); break; case 7: ModPow(b1, b3, b2, results[31][7]); break; case 8: ModPow(b1, b3, b3, results[31][8]); break; case 9: ModPow(b2, b1, b1, results[31][9]); break; case 10: ModPow(b2, b1, b2, results[31][10]); break; case 11: ModPow(b2, b1, b3, results[31][11]); break; case 12: ModPow(b2, b2, b1, results[31][12]); break; case 13: ModPow(b2, b2, b2, results[31][13]); break; case 14: ModPow(b2, b2, b3, results[31][14]); break; case 15: ModPow(b2, b3, b1, results[31][15]); break; case 16: ModPow(b2, b3, b2, results[31][16]); break; case 17: ModPow(b2, b3, b3, results[31][17]); break; case 18: ModPow(b3, b1, b1, results[31][18]); break; case 19: ModPow(b3, b1, b2, results[31][19]); break; case 20: ModPow(b3, b1, b3, results[31][20]); break; case 21: ModPow(b3, b2, b1, results[31][21]); break; case 22: ModPow(b3, b2, b2, results[31][22]); break; case 23: ModPow(b3, b2, b3, results[31][23]); break; case 24: ModPow(b3, b3, b1, results[31][24]); break; case 25: ModPow(b3, b3, b2, results[31][25]); break; case 26: ModPow(b3, b3, b3, results[31][26]); break; default: Valid = false; break; } break; default: Valid = false; break; } Assert.True(Valid, String.Format("Cycle {0} corrupted with operation {1} on order {2}", id, op, order)); } } private void Sign(BigInteger a, BigInteger expected) { Assert.Equal(a.Sign, expected); } private void Op_Not(BigInteger a, BigInteger expected) { Assert.Equal(~a, expected); } private void Log10(BigInteger a, BigInteger expected) { Assert.Equal(MyBigIntImp.ApproximateBigInteger(BigInteger.Log10(a)), expected); } private void Log(BigInteger a, BigInteger expected) { Assert.Equal(MyBigIntImp.ApproximateBigInteger(BigInteger.Log(a)), expected); } private void Abs(BigInteger a, BigInteger expected) { Assert.Equal(BigInteger.Abs(a), expected); } private void Op_Decrement(BigInteger a, BigInteger expected) { Assert.Equal(--a, expected); } private void Op_Increment(BigInteger a, BigInteger expected) { Assert.Equal(++a, expected); } private void Negate(BigInteger a, BigInteger expected) { Assert.Equal(BigInteger.Negate(a), expected); } private void Op_Negate(BigInteger a, BigInteger expected) { Assert.Equal(-a, expected); } private void Op_Plus(BigInteger a, BigInteger expected) { Assert.Equal(+a, expected); } private void Min(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal(BigInteger.Min(a, b), expected); } private void Max(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal(BigInteger.Max(a, b), expected); } private void Op_RightShift(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal((a >> MakeInt32(b)), expected); } private void Op_LeftShift(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal((a << MakeInt32(b)), expected); } private void Op_Xor(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal((a ^ b), expected); } private void Op_Or(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal((a | b), expected); } private void Op_And(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal((a & b), expected); } private void Log(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal(MyBigIntImp.ApproximateBigInteger(BigInteger.Log(a, (double)b)), expected); } private void GCD(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal(BigInteger.GreatestCommonDivisor(a, b), expected); } public bool Pow(BigInteger a, BigInteger b, BigInteger expected) { b = MakeInt32(b); if (b < 0) { b = -b; } return (BigInteger.Pow(a, (int)b) == expected); } public bool DivRem(BigInteger a, BigInteger b, BigInteger expected) { BigInteger c = 0; return (BigInteger.DivRem(a, b, out c) == expected); } private void Remainder(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal(BigInteger.Remainder(a, b), expected); } private void Op_Modulus(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal((a % b), expected); } private void Divide(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal(BigInteger.Divide(a, b), expected); } private void Op_Divide(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal((a / b), expected); } private void Multiply(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal(BigInteger.Multiply(a, b), expected); } private void Op_Multiply(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal((a * b), expected); } private void Subtract(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal(BigInteger.Subtract(a, b), expected); } private void Op_Subtract(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal((a - b), expected); } private void Add(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal(BigInteger.Add(a, b), expected); } private void Op_Add(BigInteger a, BigInteger b, BigInteger expected) { Assert.Equal((a + b), expected); } public bool ModPow(BigInteger a, BigInteger b, BigInteger c, BigInteger expected) { if (b < 0) { b = -b; } return (BigInteger.ModPow(a, b, c) == expected); } private int MakeInt32(BigInteger input) { int output; if (input < 0) { input = -input; } input = input + int.MaxValue; byte[] temp = input.ToByteArray(); temp[1] = 0; temp[2] = 0; temp[3] = 0; output = BitConverter.ToInt32(temp, 0); if (output == 0) { output = 1; } return output; } } }
#if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms. ////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012 Audiokinetic Inc. / All Rights Reserved // ////////////////////////////////////////////////////////////////////// using UnityEngine; using System.IO; #if UNITY_EDITOR using UnityEditor; #endif #pragma warning disable 0219, 0414 [AddComponentMenu("Wwise/AkInitializer")] /// This script deals with initialization, and frame updates of the Wwise audio engine. /// It is marked as \c DontDestroyOnLoad so it stays active for the life of the game, /// not only one scene. You can, and probably should, modify this script to change the /// initialization parameters for the sound engine. A few are already exposed in the property inspector. /// It must be present on one Game Object at the beginning of the game to initialize the audio properly. /// It must be executed BEFORE any other MonoBehaviors that use AkSoundEngine. /// \sa /// - <a href="https://www.audiokinetic.com/library/edge/?source=SDK&id=workingwithsdks__initialization.html" target="_blank">Initialize the Different Modules of the Sound Engine</a> (Note: This is described in the Wwise SDK documentation.) /// - <a href="https://www.audiokinetic.com/library/edge/?source=SDK&id=namespace_a_k_1_1_sound_engine_a27257629833b9481dcfdf5e793d9d037.html#a27257629833b9481dcfdf5e793d9d037" target="_blank">AK::SoundEngine::Init()</a> (Note: This is described in the Wwise SDK documentation.) /// - <a href="https://www.audiokinetic.com/library/edge/?source=SDK&id=namespace_a_k_1_1_sound_engine_a9176602bbe972da4acc1f8ebdb37f2bf.html#a9176602bbe972da4acc1f8ebdb37f2bf" target="_blank">AK::SoundEngine::Term()</a> (Note: This is described in the Wwise SDK documentation.) /// - AkCallbackManager [RequireComponent(typeof(AkTerminator))] public class AkInitializer : MonoBehaviour { public readonly static string c_DefaultBasePath = Path.Combine("Audio", "GeneratedSoundBanks"); ///Path for the soundbanks. This must contain one sub folder per platform, with the same as in the Wwise project. public string basePath = c_DefaultBasePath; public const string c_Language = "English(US)"; /// Language sub-folder. public string language = c_Language; public const int c_DefaultPoolSize = 4096; ///Default Pool size. This contains the meta data for your audio project. Default size is 4 MB, but you should adjust for your needs. public int defaultPoolSize = c_DefaultPoolSize; public const int c_LowerPoolSize = 2048; ///Lower Pool size. This contains the audio processing buffers and DSP data. Default size is 2 MB, but you should adjust for your needs. public int lowerPoolSize = c_LowerPoolSize; public const int c_StreamingPoolSize = 1024; ///Streaming Pool size. This contains the streaming buffers. Default size is 1 MB, but you should adjust for your needs. public int streamingPoolSize = c_StreamingPoolSize; public const int c_PreparePoolSize = 0; ///Prepare Pool size. This contains the banks loaded using PrepareBank (Banks decoded on load use this). Default size is 0 MB, but you should adjust for your needs. public int preparePoolSize = c_PreparePoolSize; public const float c_MemoryCutoffThreshold = 0.95f; ///This setting will trigger the killing of sounds when the memory is reaching 95% of capacity. Lowest priority sounds are killed. public float memoryCutoffThreshold = c_MemoryCutoffThreshold; public const int c_MonitorPoolSize = 128; ///Monitor Pool size. Size of the monitoring pool, in bytes. This parameter is not used in Release build. public int monitorPoolSize = c_MonitorPoolSize; public const int c_MonitorQueuePoolSize = 64; ///Monitor Queue Pool size. Size of the monitoring queue pool, in bytes. This parameter is not used in Release build. public int monitorQueuePoolSize = c_MonitorQueuePoolSize; public const int c_CallbackManagerBufferSize = 4; ///CallbackManager buffer size. The size of the buffer used per-frame to transfer callback data. Default size is 4 KB, but you should increase this, if required. public int callbackManagerBufferSize = c_CallbackManagerBufferSize; public const bool c_EngineLogging = true; ///Enable Wwise engine logging. Option to turn on/off the logging of the Wwise engine. public bool engineLogging = c_EngineLogging; public static string GetBasePath() { #if UNITY_EDITOR return WwiseSettings.LoadSettings().SoundbankPath; #else return ms_Instance.basePath; #endif } public static string GetDecodedBankFolder() { return "DecodedBanks"; } public static string GetDecodedBankFullPath() { #if (UNITY_ANDROID || UNITY_IOS || UNITY_SWITCH) && !UNITY_EDITOR // This is for platforms that only have a specific file location for persistent data. return Path.Combine(Application.persistentDataPath, GetDecodedBankFolder()); #else return Path.Combine(AkBasePathGetter.GetPlatformBasePath(), GetDecodedBankFolder()); #endif } public static string GetCurrentLanguage() { return ms_Instance.language; } void Awake() { Initialize(); } public void Initialize() { if (ms_Instance != null) { //Don't init twice //Check if there are 2 objects with this script. If yes, remove this component. if (ms_Instance != this) UnityEngine.Object.DestroyImmediate(this.gameObject); return; } Debug.Log("WwiseUnity: Initialize sound engine ..."); //Use default properties for most SoundEngine subsystem. //The game programmer should modify these when needed. See the Wwise SDK documentation for the initialization. //These settings may very well change for each target platform. AkMemSettings memSettings = new AkMemSettings(); memSettings.uMaxNumPools = 20; AkDeviceSettings deviceSettings = new AkDeviceSettings(); AkSoundEngine.GetDefaultDeviceSettings(deviceSettings); AkStreamMgrSettings streamingSettings = new AkStreamMgrSettings(); streamingSettings.uMemorySize = (uint)streamingPoolSize * 1024; AkInitSettings initSettings = new AkInitSettings(); AkSoundEngine.GetDefaultInitSettings(initSettings); initSettings.uDefaultPoolSize = (uint)defaultPoolSize * 1024; initSettings.uMonitorPoolSize = (uint)monitorPoolSize * 1024; initSettings.uMonitorQueuePoolSize = (uint)monitorQueuePoolSize * 1024; #if (!UNITY_ANDROID && !UNITY_WSA) || UNITY_EDITOR // Exclude WSA. It only needs the name of the DLL, and no path. initSettings.szPluginDLLPath = Path.Combine(Application.dataPath, "Plugins" + Path.DirectorySeparatorChar); #endif AkPlatformInitSettings platformSettings = new AkPlatformInitSettings(); AkSoundEngine.GetDefaultPlatformInitSettings(platformSettings); platformSettings.uLEngineDefaultPoolSize = (uint)lowerPoolSize * 1024; platformSettings.fLEngineDefaultPoolRatioThreshold = memoryCutoffThreshold; AkMusicSettings musicSettings = new AkMusicSettings(); AkSoundEngine.GetDefaultMusicSettings(musicSettings); #if UNITY_EDITOR AkSoundEngine.SetGameName(Application.productName + " (Editor)"); #else AkSoundEngine.SetGameName(Application.productName); #endif AKRESULT result = AkSoundEngine.Init(memSettings, streamingSettings, deviceSettings, initSettings, platformSettings, musicSettings, (uint)preparePoolSize * 1024); if (result != AKRESULT.AK_Success) { Debug.LogError("WwiseUnity: Failed to initialize the sound engine. Abort."); return; //AkSoundEngine.Init should have logged more details. } ms_Instance = this; string basePathToSet = AkBasePathGetter.GetSoundbankBasePath(); if (string.IsNullOrEmpty(basePathToSet)) { return; } result = AkSoundEngine.SetBasePath(basePathToSet); if (result != AKRESULT.AK_Success) { return; } #if !UNITY_SWITCH // Calling Application.persistentDataPath crashes Switch string decodedBankFullPath = GetDecodedBankFullPath(); // AkSoundEngine.SetDecodedBankPath creates the folders for writing to (if they don't exist) AkSoundEngine.SetDecodedBankPath(decodedBankFullPath); #endif AkSoundEngine.SetCurrentLanguage(language); #if !UNITY_SWITCH // Calling Application.persistentDataPath crashes Switch // AkSoundEngine.AddBasePath is currently only implemented for iOS and Android; No-op for all other platforms. AkSoundEngine.AddBasePath(Application.persistentDataPath + Path.DirectorySeparatorChar); // Adding decoded bank path last to ensure that it is the first one used when writing decoded banks. AkSoundEngine.AddBasePath(decodedBankFullPath); #endif result = AkCallbackManager.Init(callbackManagerBufferSize * 1024); if (result != AKRESULT.AK_Success) { Debug.LogError("WwiseUnity: Failed to initialize Callback Manager. Terminate sound engine."); AkSoundEngine.Term(); ms_Instance = null; return; } AkBankManager.Reset(); Debug.Log("WwiseUnity: Sound engine initialized."); //The sound engine should not be destroyed once it is initialized. DontDestroyOnLoad(this); #if UNITY_EDITOR //Redirect Wwise error messages into Unity console. AkCallbackManager.SetMonitoringCallback(ErrorLevel.ErrorLevel_All, CopyMonitoringInConsole); #endif //Load the init bank right away. Errors will be logged automatically. uint BankID; result = AkSoundEngine.LoadBank("Init.bnk", AkSoundEngine.AK_DEFAULT_POOL_ID, out BankID); if (result != AKRESULT.AK_Success) { Debug.LogError("WwiseUnity: Failed load Init.bnk with result: " + result.ToString()); } #if UNITY_EDITOR #if UNITY_2017_2_OR_NEWER EditorApplication.playModeStateChanged += OnPlayModeStateChanged; EditorApplication.pauseStateChanged += OnPauseStateChanged; #else EditorApplication.playmodeStateChanged += OnEditorPlaymodeStateChanged; #endif #endif } void OnDestroy() { if (ms_Instance == this) { #if UNITY_EDITOR #if UNITY_2017_2_OR_NEWER EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; EditorApplication.pauseStateChanged -= OnPauseStateChanged; #else EditorApplication.playmodeStateChanged -= OnEditorPlaymodeStateChanged; #endif #endif AkCallbackManager.SetMonitoringCallback(0, null); ms_Instance = null; } // Do nothing. AkTerminator handles sound engine termination. } void OnEnable() { //The sound engine was not terminated normally. Make this instance the one that will manage //the updates and termination. //This happen when Unity resets everything when a script changes. if (ms_Instance == null && AkSoundEngine.IsInitialized()) { ms_Instance = this; #if UNITY_EDITOR //Redirect Wwise error messages into Unity console. AkCallbackManager.SetMonitoringCallback(ErrorLevel.ErrorLevel_All, CopyMonitoringInConsole); #endif } } //Use LateUpdate instead of Update() to ensure all gameobjects positions, listener positions, environements, RTPC, etc are set before finishing the audio frame. void LateUpdate() { //Execute callbacks that occurred in last frame (not the current update) if (ms_Instance != null) { AkCallbackManager.PostCallbacks(); AkBankManager.DoUnloadBanks(); AkAudioListener.DefaultListeners.Refresh(); AkSoundEngine.RenderAudio(); } } #if UNITY_EDITOR void OnDisable() { // Unregister the callback that redirects the output to the Unity console. If not done early enough (meaning, later than Disable), AkInitializer will leak. if (ms_Instance != null && AkSoundEngine.IsInitialized()) AkCallbackManager.SetMonitoringCallback(0, null); } void CopyMonitoringInConsole(ErrorCode in_errorCode, ErrorLevel in_errorLevel, uint in_playingID, ulong in_gameObjID, string in_msg) { // Only log when logging from the engine is enabled. The callback remains active when the flag is disabled to ensure // it can be toggled on and off in a lively manner in Unity. if (engineLogging) { string msg = "Wwise: " + in_msg; if (in_gameObjID != AkSoundEngine.AK_INVALID_GAME_OBJECT) { GameObject obj = EditorUtility.InstanceIDToObject((int)in_gameObjID) as GameObject; string name = obj != null ? obj.ToString() : in_gameObjID.ToString(); msg += "(Object: " + name + ")"; } if (in_errorLevel == ErrorLevel.ErrorLevel_Error) Debug.LogError(msg); else Debug.Log(msg); } } #endif // // Private members // private static AkInitializer ms_Instance; #if !UNITY_EDITOR && !UNITY_IOS //Keep out of UNITY_EDITOR because the sound needs to keep playing when switching windows (remote debugging in Wwise, for example). //On iOS, application interruptions are handled in the sound engine already. void OnApplicationPause(bool pauseStatus) { ActivateAudio(!pauseStatus); } void OnApplicationFocus(bool focus) { ActivateAudio(focus); } #endif #if UNITY_EDITOR // Enable/Disable the audio when pressing play/pause in the editor. #if UNITY_2017_2_OR_NEWER private static void OnPlayModeStateChanged(PlayModeStateChange playMode) { if (playMode == PlayModeStateChange.EnteredPlayMode) ActivateAudio(true); else if (playMode == PlayModeStateChange.ExitingPlayMode) ActivateAudio(false); } private static void OnPauseStateChanged(PauseState pauseState) { ActivateAudio(pauseState != PauseState.Paused); } #else private static void OnEditorPlaymodeStateChanged() { ActivateAudio(!EditorApplication.isPaused); } #endif #endif private static void ActivateAudio(bool activate) { if (ms_Instance != null) { if (activate) AkSoundEngine.WakeupFromSuspend(); else AkSoundEngine.Suspend(); AkSoundEngine.RenderAudio(); } } } #endif // #if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms.
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Diagnostics { using System.Text; using System; using System.IO; using System.Reflection; using System.Security.Permissions; using System.Diagnostics.Contracts; // There is no good reason for the methods of this class to be virtual. // In order to ensure trusted code can trust the data it gets from a // StackTrace, we use an InheritanceDemand to prevent partially-trusted // subclasses. #if !FEATURE_CORECLR [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] #endif [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class StackFrame { private MethodBase method; private int offset; private int ILOffset; private String strFileName; private int iLineNumber; private int iColumnNumber; #if FEATURE_EXCEPTIONDISPATCHINFO [System.Runtime.Serialization.OptionalField] private bool fIsLastFrameFromForeignExceptionStackTrace; #endif // FEATURE_EXCEPTIONDISPATCHINFO internal void InitMembers() { method = null; offset = OFFSET_UNKNOWN; ILOffset = OFFSET_UNKNOWN; strFileName = null; iLineNumber = 0; iColumnNumber = 0; #if FEATURE_EXCEPTIONDISPATCHINFO fIsLastFrameFromForeignExceptionStackTrace = false; #endif // FEATURE_EXCEPTIONDISPATCHINFO } // Constructs a StackFrame corresponding to the active stack frame. #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif public StackFrame() { InitMembers(); BuildStackFrame (0 + StackTrace.METHODS_TO_SKIP, false);// iSkipFrames=0 } // Constructs a StackFrame corresponding to the active stack frame. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackFrame(bool fNeedFileInfo) { InitMembers(); BuildStackFrame (0 + StackTrace.METHODS_TO_SKIP, fNeedFileInfo);// iSkipFrames=0 } // Constructs a StackFrame corresponding to a calling stack frame. // public StackFrame(int skipFrames) { InitMembers(); BuildStackFrame (skipFrames + StackTrace.METHODS_TO_SKIP, false); } // Constructs a StackFrame corresponding to a calling stack frame. // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackFrame(int skipFrames, bool fNeedFileInfo) { InitMembers(); BuildStackFrame (skipFrames + StackTrace.METHODS_TO_SKIP, fNeedFileInfo); } // Called from the class "StackTrace" // internal StackFrame(bool DummyFlag1, bool DummyFlag2) { InitMembers(); } // Constructs a "fake" stack frame, just containing the given file // name and line number. Use when you don't want to use the // debugger's line mapping logic. // public StackFrame(String fileName, int lineNumber) { InitMembers(); BuildStackFrame (StackTrace.METHODS_TO_SKIP, false); strFileName = fileName; iLineNumber = lineNumber; iColumnNumber = 0; } // Constructs a "fake" stack frame, just containing the given file // name, line number and column number. Use when you don't want to // use the debugger's line mapping logic. // public StackFrame(String fileName, int lineNumber, int colNumber) { InitMembers(); BuildStackFrame (StackTrace.METHODS_TO_SKIP, false); strFileName = fileName; iLineNumber = lineNumber; iColumnNumber = colNumber; } // Constant returned when the native or IL offset is unknown public const int OFFSET_UNKNOWN = -1; internal virtual void SetMethodBase (MethodBase mb) { method = mb; } internal virtual void SetOffset (int iOffset) { offset = iOffset; } internal virtual void SetILOffset (int iOffset) { ILOffset = iOffset; } internal virtual void SetFileName (String strFName) { strFileName = strFName; } internal virtual void SetLineNumber (int iLine) { iLineNumber = iLine; } internal virtual void SetColumnNumber (int iCol) { iColumnNumber = iCol; } #if FEATURE_EXCEPTIONDISPATCHINFO internal virtual void SetIsLastFrameFromForeignExceptionStackTrace (bool fIsLastFrame) { fIsLastFrameFromForeignExceptionStackTrace = fIsLastFrame; } internal virtual bool GetIsLastFrameFromForeignExceptionStackTrace() { return fIsLastFrameFromForeignExceptionStackTrace; } #endif // FEATURE_EXCEPTIONDISPATCHINFO // Returns the method the frame is executing // public virtual MethodBase GetMethod () { Contract.Ensures(Contract.Result<MethodBase>() != null); return method; } // Returns the offset from the start of the native (jitted) code for the // method being executed // public virtual int GetNativeOffset () { return offset; } // Returns the offset from the start of the IL code for the // method being executed. This offset may be approximate depending // on whether the jitter is generating debuggable code or not. // public virtual int GetILOffset() { return ILOffset; } // Returns the file name containing the code being executed. This // information is normally extracted from the debugging symbols // for the executable. // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif public virtual String GetFileName() { if (strFileName != null) { // This isn't really correct, but we don't have // a permission that protects discovery of potentially // local urls so we'll use this. FileIOPermission perm = new FileIOPermission( PermissionState.None ); perm.AllFiles = FileIOPermissionAccess.PathDiscovery; perm.Demand(); } return strFileName; } // Returns the line number in the file containing the code being executed. // This information is normally extracted from the debugging symbols // for the executable. // public virtual int GetFileLineNumber() { return iLineNumber; } // Returns the column number in the line containing the code being executed. // This information is normally extracted from the debugging symbols // for the executable. // public virtual int GetFileColumnNumber() { return iColumnNumber; } // Builds a readable representation of the stack frame // [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { StringBuilder sb = new StringBuilder(255); if (method != null) { sb.Append(method.Name); // deal with the generic portion of the method if (method is MethodInfo && ((MethodInfo)method).IsGenericMethod) { Type[] typars = ((MethodInfo)method).GetGenericArguments(); sb.Append("<"); int k = 0; bool fFirstTyParam = true; while (k < typars.Length) { if (fFirstTyParam == false) sb.Append(","); else fFirstTyParam = false; sb.Append(typars[k].Name); k++; } sb.Append(">"); } sb.Append(" at offset "); if (offset == OFFSET_UNKNOWN) sb.Append("<offset unknown>"); else sb.Append(offset); sb.Append(" in file:line:column "); bool useFileName = (strFileName != null); if (useFileName) { try { // This isn't really correct, but we don't have // a permission that protects discovery of potentially // local urls so we'll use this. FileIOPermission perm = new FileIOPermission(PermissionState.None); perm.AllFiles = FileIOPermissionAccess.PathDiscovery; perm.Demand(); } catch (System.Security.SecurityException) { useFileName = false; } } if (!useFileName) sb.Append("<filename unknown>"); else sb.Append(strFileName); sb.Append(":"); sb.Append(iLineNumber); sb.Append(":"); sb.Append(iColumnNumber); } else { sb.Append("<null>"); } sb.Append(Environment.NewLine); return sb.ToString(); } private void BuildStackFrame(int skipFrames, bool fNeedFileInfo) { StackFrameHelper StackF = new StackFrameHelper(fNeedFileInfo, null); StackTrace.GetStackFramesInternal (StackF, 0, null); int iNumOfFrames = StackF.GetNumberOfFrames(); skipFrames += StackTrace.CalculateFramesToSkip (StackF, iNumOfFrames); if ((iNumOfFrames - skipFrames) > 0) { method = StackF.GetMethodBase (skipFrames); offset = StackF.GetOffset (skipFrames); ILOffset = StackF.GetILOffset (skipFrames); if (fNeedFileInfo) { strFileName = StackF.GetFilename (skipFrames); iLineNumber = StackF.GetLineNumber (skipFrames); iColumnNumber = StackF.GetColumnNumber (skipFrames); } } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.Build.Construction; using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.Tools; using Microsoft.DotNet.Tools.Test.Utilities; using System; using System.IO; using System.Linq; using System.Text; using Xunit; using Xunit.Abstractions; namespace Microsoft.DotNet.Cli.Sln.Add.Tests { public class GivenDotnetSlnAdd : TestBase { private string HelpText = @"Usage: dotnet sln <SLN_FILE> add [options] <PROJECT_PATH> Arguments: <SLN_FILE> The solution file to operate on. If not specified, the command will search the current directory for one. <PROJECT_PATH> The paths to the projects to add to the solution. Options: -h, --help Show command line help."; private const string SlnCommandHelpText = @"Usage: dotnet sln [options] <SLN_FILE> [command] Arguments: <SLN_FILE> The solution file to operate on. If not specified, the command will search the current directory for one. Options: -h, --help Show command line help. Commands: add <PROJECT_PATH> Add one or more projects to a solution file. list List all projects in a solution file. remove <PROJECT_PATH> Remove one or more projects from a solution file."; private ITestOutputHelper _output; public GivenDotnetSlnAdd(ITestOutputHelper output) { _output = output; } private const string ExpectedSlnFileAfterAddingLibProj = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}"" EndProject Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""Lib"", ""Lib\Lib.csproj"", ""__LIB_PROJECT_GUID__"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86 __LIB_PROJECT_GUID__.Debug|Any CPU.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|Any CPU.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x86.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x86.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x86.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal "; private const string ExpectedSlnFileAfterAddingLibProjToEmptySln = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""Lib"", ""Lib\Lib.csproj"", ""__LIB_PROJECT_GUID__"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution __LIB_PROJECT_GUID__.Debug|Any CPU.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|Any CPU.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x86.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x86.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x86.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|x86.Build.0 = Release|Any CPU EndGlobalSection EndGlobal "; private const string ExpectedSlnFileAfterAddingNestedProj = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}"" EndProject Project(""{2150E333-8FDC-42A3-9474-1A3956D46DE8}"") = ""src"", ""src"", ""__SRC_FOLDER_GUID__"" EndProject Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""Lib"", ""src\Lib\Lib.csproj"", ""__LIB_PROJECT_GUID__"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86 __LIB_PROJECT_GUID__.Debug|Any CPU.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|Any CPU.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x86.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x86.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x86.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution __LIB_PROJECT_GUID__ = __SRC_FOLDER_GUID__ EndGlobalSection EndGlobal "; private const string ExpectedSlnFileAfterAddingProjectWithoutMatchingConfigs = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""ProjectWithoutMatchingConfigs"", ""ProjectWithoutMatchingConfigs\ProjectWithoutMatchingConfigs.csproj"", ""{C49B64DE-4401-4825-8A88-10DCB5950E57}"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 Foo Bar|Any CPU = Foo Bar|Any CPU Foo Bar|x64 = Foo Bar|x64 Foo Bar|x86 = Foo Bar|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {C49B64DE-4401-4825-8A88-10DCB5950E57}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Debug|Any CPU.Build.0 = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Debug|x64.ActiveCfg = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Debug|x64.Build.0 = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Debug|x86.ActiveCfg = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Debug|x86.Build.0 = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Release|Any CPU.ActiveCfg = Release|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Release|Any CPU.Build.0 = Release|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Release|x64.ActiveCfg = Release|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Release|x64.Build.0 = Release|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Release|x86.ActiveCfg = Release|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Release|x86.Build.0 = Release|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Foo Bar|Any CPU.ActiveCfg = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Foo Bar|Any CPU.Build.0 = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Foo Bar|x64.ActiveCfg = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Foo Bar|x64.Build.0 = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Foo Bar|x86.ActiveCfg = Debug|Any CPU {C49B64DE-4401-4825-8A88-10DCB5950E57}.Foo Bar|x86.Build.0 = Debug|Any CPU EndGlobalSection EndGlobal "; private const string ExpectedSlnFileAfterAddingProjectWithMatchingConfigs = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""ProjectWithMatchingConfigs"", ""ProjectWithMatchingConfigs\ProjectWithMatchingConfigs.csproj"", ""{C9601CA2-DB64-4FB6-B463-368C7764BF0D}"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 Foo Bar|Any CPU = Foo Bar|Any CPU Foo Bar|x64 = Foo Bar|x64 Foo Bar|x86 = Foo Bar|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Debug|Any CPU.Build.0 = Debug|Any CPU {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Debug|x64.ActiveCfg = Debug|x64 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Debug|x64.Build.0 = Debug|x64 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Debug|x86.ActiveCfg = Debug|x86 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Debug|x86.Build.0 = Debug|x86 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Release|Any CPU.ActiveCfg = Release|Any CPU {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Release|Any CPU.Build.0 = Release|Any CPU {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Release|x64.ActiveCfg = Release|x64 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Release|x64.Build.0 = Release|x64 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Release|x86.ActiveCfg = Release|x86 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Release|x86.Build.0 = Release|x86 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Foo Bar|Any CPU.ActiveCfg = FooBar|Any CPU {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Foo Bar|Any CPU.Build.0 = FooBar|Any CPU {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Foo Bar|x64.ActiveCfg = FooBar|x64 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Foo Bar|x64.Build.0 = FooBar|x64 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Foo Bar|x86.ActiveCfg = FooBar|x86 {C9601CA2-DB64-4FB6-B463-368C7764BF0D}.Foo Bar|x86.Build.0 = FooBar|x86 EndGlobalSection EndGlobal "; private const string ExpectedSlnFileAfterAddingProjectWithAdditionalConfigs = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""ProjectWithAdditionalConfigs"", ""ProjectWithAdditionalConfigs\ProjectWithAdditionalConfigs.csproj"", ""{A302325B-D680-4C0E-8680-7AE283981624}"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 Foo Bar|Any CPU = Foo Bar|Any CPU Foo Bar|x64 = Foo Bar|x64 Foo Bar|x86 = Foo Bar|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A302325B-D680-4C0E-8680-7AE283981624}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A302325B-D680-4C0E-8680-7AE283981624}.Debug|Any CPU.Build.0 = Debug|Any CPU {A302325B-D680-4C0E-8680-7AE283981624}.Debug|x64.ActiveCfg = Debug|x64 {A302325B-D680-4C0E-8680-7AE283981624}.Debug|x64.Build.0 = Debug|x64 {A302325B-D680-4C0E-8680-7AE283981624}.Debug|x86.ActiveCfg = Debug|x86 {A302325B-D680-4C0E-8680-7AE283981624}.Debug|x86.Build.0 = Debug|x86 {A302325B-D680-4C0E-8680-7AE283981624}.Release|Any CPU.ActiveCfg = Release|Any CPU {A302325B-D680-4C0E-8680-7AE283981624}.Release|Any CPU.Build.0 = Release|Any CPU {A302325B-D680-4C0E-8680-7AE283981624}.Release|x64.ActiveCfg = Release|x64 {A302325B-D680-4C0E-8680-7AE283981624}.Release|x64.Build.0 = Release|x64 {A302325B-D680-4C0E-8680-7AE283981624}.Release|x86.ActiveCfg = Release|x86 {A302325B-D680-4C0E-8680-7AE283981624}.Release|x86.Build.0 = Release|x86 {A302325B-D680-4C0E-8680-7AE283981624}.Foo Bar|Any CPU.ActiveCfg = FooBar|Any CPU {A302325B-D680-4C0E-8680-7AE283981624}.Foo Bar|Any CPU.Build.0 = FooBar|Any CPU {A302325B-D680-4C0E-8680-7AE283981624}.Foo Bar|x64.ActiveCfg = FooBar|x64 {A302325B-D680-4C0E-8680-7AE283981624}.Foo Bar|x64.Build.0 = FooBar|x64 {A302325B-D680-4C0E-8680-7AE283981624}.Foo Bar|x86.ActiveCfg = FooBar|x86 {A302325B-D680-4C0E-8680-7AE283981624}.Foo Bar|x86.Build.0 = FooBar|x86 EndGlobalSection EndGlobal "; [Theory] [InlineData("--help")] [InlineData("-h")] [InlineData("-?")] [InlineData("/?")] public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln add {helpArg}"); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Theory] [InlineData("")] [InlineData("unknownCommandName")] public void WhenNoCommandIsPassedItPrintsError(string commandName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln {commandName}"); cmd.Should().Fail(); cmd.StdErr.Should().Be(CommonLocalizableStrings.RequiredCommandNotPassed); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(SlnCommandHelpText); } [Fact] public void WhenTooManyArgumentsArePassedItPrintsError() { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput("sln one.sln two.sln three.sln add"); cmd.Should().Fail(); cmd.StdErr.Should().BeVisuallyEquivalentTo($@"{string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "two.sln")} {string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "three.sln")} {CommonLocalizableStrings.SpecifyAtLeastOneProjectToAdd}"); } [Theory] [InlineData("idontexist.sln")] [InlineData("ihave?invalidcharacters")] [InlineData("ihaveinv@lidcharacters")] [InlineData("ihaveinvalid/characters")] [InlineData("ihaveinvalidchar\\acters")] public void WhenNonExistingSolutionIsPassedItPrintsErrorAndUsage(string solutionName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln {solutionName} add p.csproj"); cmd.Should().Fail(); cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindSolutionOrDirectory, solutionName)); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Fact] public void WhenInvalidSolutionIsPassedItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("InvalidSolution") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln InvalidSolution.sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.InvalidSolutionFormatString, "InvalidSolution.sln", LocalizableStrings.FileHeaderMissingError)); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Fact] public void WhenInvalidSolutionIsFoundItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("InvalidSolution") .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionPath = Path.Combine(projectDirectory, "InvalidSolution.sln"); var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.InvalidSolutionFormatString, solutionPath, LocalizableStrings.FileHeaderMissingError)); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Fact] public void WhenNoProjectIsPassedItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput(@"sln App.sln add"); cmd.Should().Fail(); cmd.StdErr.Should().Be(CommonLocalizableStrings.SpecifyAtLeastOneProjectToAdd); _output.WriteLine("[STD OUT]"); _output.WriteLine(cmd.StdOut); _output.WriteLine("[HelpText]"); _output.WriteLine(HelpText); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Fact] public void WhenNoSolutionExistsInTheDirectoryItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionPath = Path.Combine(projectDirectory, "App"); var cmd = new DotnetCommand() .WithWorkingDirectory(solutionPath) .ExecuteWithCapturedOutput(@"sln add App.csproj"); cmd.Should().Fail(); cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.SolutionDoesNotExist, solutionPath + Path.DirectorySeparatorChar)); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Fact] public void WhenMoreThanOneSolutionExistsInTheDirectoryItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithMultipleSlnFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.MoreThanOneSolutionInDirectory, projectDirectory + Path.DirectorySeparatorChar)); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Fact] public void WhenNestedProjectIsAddedSolutionFoldersAreCreated() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojInSubDir") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("src", "Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnPath = Path.Combine(projectDirectory, "App.sln"); var expectedSlnContents = GetExpectedSlnContents(slnPath, ExpectedSlnFileAfterAddingNestedProj); File.ReadAllText(slnPath) .Should().BeVisuallyEquivalentTo(expectedSlnContents); } [Fact] public void WhenDirectoryContainingProjectIsGivenProjectIsAdded() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput("sln add Lib"); cmd.Should().Pass(); var slnPath = Path.Combine(projectDirectory, "App.sln"); var expectedSlnContents = GetExpectedSlnContents(slnPath, ExpectedSlnFileAfterAddingLibProj); File.ReadAllText(slnPath) .Should().BeVisuallyEquivalentTo(expectedSlnContents); } [Fact] public void WhenDirectoryContainsNoProjectsItCancelsWholeOperation() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(projectDirectory, "App.sln"); var contentBefore = File.ReadAllText(slnFullPath); var directoryToAdd = "Empty"; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln add {directoryToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be( string.Format( CommonLocalizableStrings.CouldNotFindAnyProjectInDirectory, Path.Combine(projectDirectory, directoryToAdd))); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(contentBefore); } [Fact] public void WhenDirectoryContainsMultipleProjectsItCancelsWholeOperation() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(projectDirectory, "App.sln"); var contentBefore = File.ReadAllText(slnFullPath); var directoryToAdd = "Multiple"; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln add {directoryToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be( string.Format( CommonLocalizableStrings.MoreThanOneProjectInDirectory, Path.Combine(projectDirectory, directoryToAdd))); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(contentBefore); } [Fact] public void WhenProjectDirectoryIsAddedSolutionFoldersAreNotCreated() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var solutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid); solutionFolderProjects.Count().Should().Be(0); slnFile.Sections.GetSection("NestedProjects").Should().BeNull(); } [Theory] [InlineData(".")] [InlineData("")] public void WhenSolutionFolderExistsItDoesNotGetAdded(string firstComponent) { var projectDirectory = TestAssets .Get("TestAppWithSlnAndSolutionFolders") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine($"{firstComponent}", "src", "src", "Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); slnFile.Projects.Count().Should().Be(4); var solutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid); solutionFolderProjects.Count().Should().Be(2); var solutionFolders = slnFile.Sections.GetSection("NestedProjects").Properties; solutionFolders.Count.Should().Be(3); solutionFolders["{DDF3765C-59FB-4AA6-BE83-779ED13AA64A}"] .Should().Be("{72BFCA87-B033-4721-8712-4D12166B4A39}"); var newlyAddedSrcFolder = solutionFolderProjects.Where( p => p.Id != "{72BFCA87-B033-4721-8712-4D12166B4A39}").Single(); solutionFolders[newlyAddedSrcFolder.Id] .Should().Be("{72BFCA87-B033-4721-8712-4D12166B4A39}"); var libProject = slnFile.Projects.Where(p => p.Name == "Lib").Single(); solutionFolders[libProject.Id] .Should().Be(newlyAddedSrcFolder.Id); } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles", ExpectedSlnFileAfterAddingLibProj, "")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles", ExpectedSlnFileAfterAddingLibProj, "{84A45D44-B677-492D-A6DA-B3A71135AB8E}")] [InlineData("TestAppWithEmptySln", ExpectedSlnFileAfterAddingLibProjToEmptySln, "")] public void WhenValidProjectIsPassedBuildConfigsAreAdded( string testAsset, string expectedSlnContentsTemplate, string expectedProjectGuid) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = "Lib/Lib.csproj"; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnPath = Path.Combine(projectDirectory, "App.sln"); var expectedSlnContents = GetExpectedSlnContents( slnPath, expectedSlnContentsTemplate, expectedProjectGuid); File.ReadAllText(slnPath) .Should().BeVisuallyEquivalentTo(expectedSlnContents); } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles")] [InlineData("TestAppWithEmptySln")] public void WhenValidProjectIsPassedItGetsAdded(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = "Lib/Lib.csproj"; var projectPath = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectAddedToTheSolution, projectPath)); cmd.StdErr.Should().BeEmpty(); } [Fact] public void WhenProjectIsAddedSolutionHasUTF8BOM() { var projectDirectory = TestAssets .Get("TestAppWithEmptySln") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = "Lib/Lib.csproj"; var projectPath = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var preamble = Encoding.UTF8.GetPreamble(); preamble.Length.Should().Be(3); using (var stream = new FileStream(Path.Combine(projectDirectory, "App.sln"), FileMode.Open)) { var bytes = new byte[preamble.Length]; stream.Read(bytes, 0, bytes.Length); bytes.Should().BeEquivalentTo(preamble); } } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles")] [InlineData("TestAppWithEmptySln")] public void WhenInvalidProjectIsPassedItDoesNotGetAdded(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = "Lib/Library.cs"; var projectPath = Path.Combine("Lib", "Library.cs"); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var expectedNumberOfProjects = slnFile.Projects.Count(); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdOut.Should().BeEmpty(); cmd.StdErr.Should().Match(string.Format(CommonLocalizableStrings.InvalidProjectWithExceptionMessage, '*', '*')); slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); slnFile.Projects.Count().Should().Be(expectedNumberOfProjects); } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles")] [InlineData("TestAppWithEmptySln")] public void WhenValidProjectIsPassedTheSlnBuilds(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput(@"sln App.sln add App/App.csproj Lib/Lib.csproj"); cmd.Should().Pass(); var slnPath = Path.Combine(projectDirectory, "App.sln"); new DotnetCommand() .WithWorkingDirectory(projectDirectory) .Execute($"restore App.sln") .Should().Pass(); new DotnetCommand() .WithWorkingDirectory(projectDirectory) .Execute("build App.sln --configuration Release") .Should().Pass(); var reasonString = "should be built in release mode, otherwise it means build configurations are missing from the sln file"; var appReleaseDirectory = Directory.EnumerateDirectories( Path.Combine(projectDirectory, "App", "bin"), "Release", SearchOption.AllDirectories); appReleaseDirectory.Count().Should().Be(1, $"App {reasonString}"); Directory.EnumerateFiles(appReleaseDirectory.Single(), "App.dll", SearchOption.AllDirectories) .Count().Should().Be(1, $"App {reasonString}"); var libReleaseDirectory = Directory.EnumerateDirectories( Path.Combine(projectDirectory, "Lib", "bin"), "Release", SearchOption.AllDirectories); libReleaseDirectory.Count().Should().Be(1, $"Lib {reasonString}"); Directory.EnumerateFiles(libReleaseDirectory.Single(), "Lib.dll", SearchOption.AllDirectories) .Count().Should().Be(1, $"Lib {reasonString}"); } [Theory] [InlineData("TestAppWithSlnAndExistingCsprojReferences")] [InlineData("TestAppWithSlnAndExistingCsprojReferencesWithEscapedDirSep")] public void WhenSolutionAlreadyContainsProjectItDoesntDuplicate(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionPath = Path.Combine(projectDirectory, "App.sln"); var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.SolutionAlreadyContainsProject, solutionPath, projectToAdd)); cmd.StdErr.Should().BeEmpty(); } [Fact] public void WhenPassedMultipleProjectsAndOneOfthemDoesNotExistItCancelsWholeOperation() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(projectDirectory, "App.sln"); var contentBefore = File.ReadAllText(slnFullPath); var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd} idonotexist.csproj"); cmd.Should().Fail(); cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindProjectOrDirectory, "idonotexist.csproj")); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(contentBefore); } //ISSUE: https://github.com/dotnet/sdk/issues/522 //[Fact] public void WhenPassedAnUnknownProjectTypeItFails() { var projectDirectory = TestAssets .Get("SlnFileWithNoProjectReferencesAndUnknownProject") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(projectDirectory, "App.sln"); var contentBefore = File.ReadAllText(slnFullPath); var projectToAdd = Path.Combine("UnknownProject", "UnknownProject.unknownproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().BeVisuallyEquivalentTo("Unsupported project type. Please check with your sdk provider."); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(contentBefore); } [Theory] [InlineData("SlnFileWithNoProjectReferencesAndCSharpProject", "CSharpProject", "CSharpProject.csproj", ProjectTypeGuids.CSharpProjectTypeGuid)] [InlineData("SlnFileWithNoProjectReferencesAndFSharpProject", "FSharpProject", "FSharpProject.fsproj", ProjectTypeGuids.FSharpProjectTypeGuid)] [InlineData("SlnFileWithNoProjectReferencesAndVBProject", "VBProject", "VBProject.vbproj", ProjectTypeGuids.VBProjectTypeGuid)] [InlineData("SlnFileWithNoProjectReferencesAndUnknownProjectWithSingleProjectTypeGuid", "UnknownProject", "UnknownProject.unknownproj", "{130159A9-F047-44B3-88CF-0CF7F02ED50F}")] [InlineData("SlnFileWithNoProjectReferencesAndUnknownProjectWithMultipleProjectTypeGuids", "UnknownProject", "UnknownProject.unknownproj", "{130159A9-F047-44B3-88CF-0CF7F02ED50F}")] public void WhenPassedAProjectItAddsCorrectProjectTypeGuid( string testAsset, string projectDir, string projectName, string expectedTypeGuid) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine(projectDir, projectName); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdErr.Should().BeEmpty(); cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectAddedToTheSolution, projectToAdd)); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var nonSolutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid != ProjectTypeGuids.SolutionFolderGuid); nonSolutionFolderProjects.Count().Should().Be(1); nonSolutionFolderProjects.Single().TypeGuid.Should().Be(expectedTypeGuid); } [Fact] public void WhenPassedAProjectWithoutATypeGuidItErrors() { var solutionDirectory = TestAssets .Get("SlnFileWithNoProjectReferencesAndUnknownProjectType") .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionPath = Path.Combine(solutionDirectory, "App.sln"); var contentBefore = File.ReadAllText(solutionPath); var projectToAdd = Path.Combine("UnknownProject", "UnknownProject.unknownproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(solutionDirectory) .ExecuteWithCapturedOutput($"sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdErr.Should().Be( string.Format( CommonLocalizableStrings.UnsupportedProjectType, Path.Combine(solutionDirectory, projectToAdd))); cmd.StdOut.Should().BeEmpty(); File.ReadAllText(solutionPath) .Should() .BeVisuallyEquivalentTo(contentBefore); } [Fact] private void WhenSlnContainsSolutionFolderWithDifferentCasingItDoesNotCreateDuplicate() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCaseSensitiveSolutionFolders") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("src", "Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .Execute($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var solutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid); solutionFolderProjects.Count().Should().Be(1); } [Fact] public void WhenProjectWithoutMatchingConfigurationsIsAddedSolutionMapsToFirstAvailable() { var slnDirectory = TestAssets .Get("TestAppWithSlnAndProjectConfigs") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(slnDirectory, "App.sln"); var result = new DotnetCommand() .WithWorkingDirectory(slnDirectory) .ExecuteWithCapturedOutput($"sln add ProjectWithoutMatchingConfigs"); result.Should().Pass(); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(ExpectedSlnFileAfterAddingProjectWithoutMatchingConfigs); } [Fact] public void WhenProjectWithMatchingConfigurationsIsAddedSolutionMapsAll() { var slnDirectory = TestAssets .Get("TestAppWithSlnAndProjectConfigs") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(slnDirectory, "App.sln"); var result = new DotnetCommand() .WithWorkingDirectory(slnDirectory) .ExecuteWithCapturedOutput($"sln add ProjectWithMatchingConfigs"); result.Should().Pass(); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(ExpectedSlnFileAfterAddingProjectWithMatchingConfigs); } [Fact] public void WhenProjectWithAdditionalConfigurationsIsAddedSolutionDoesNotMapThem() { var slnDirectory = TestAssets .Get("TestAppWithSlnAndProjectConfigs") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(slnDirectory, "App.sln"); var result = new DotnetCommand() .WithWorkingDirectory(slnDirectory) .ExecuteWithCapturedOutput($"sln add ProjectWithAdditionalConfigs"); result.Should().Pass(); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(ExpectedSlnFileAfterAddingProjectWithAdditionalConfigs); } [Fact] public void ItAddsACSharpProjectThatIsMultitargeted() { var solutionDirectory = TestAssets .Get("TestAppsWithSlnAndMultitargetedProjects") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(solutionDirectory, "App.sln"); var projectToAdd = Path.Combine("MultitargetedCS", "MultitargetedCS.csproj"); new DotnetCommand() .WithWorkingDirectory(solutionDirectory) .ExecuteWithCapturedOutput($"sln add {projectToAdd}") .Should() .Pass() .And .HaveStdOutContaining(string.Format(CommonLocalizableStrings.ProjectAddedToTheSolution, projectToAdd)); } [Fact] public void ItAddsAVisualBasicProjectThatIsMultitargeted() { var solutionDirectory = TestAssets .Get("TestAppsWithSlnAndMultitargetedProjects") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(solutionDirectory, "App.sln"); var projectToAdd = Path.Combine("MultitargetedVB", "MultitargetedVB.vbproj"); new DotnetCommand() .WithWorkingDirectory(solutionDirectory) .ExecuteWithCapturedOutput($"sln add {projectToAdd}") .Should() .Pass() .And .HaveStdOutContaining(string.Format(CommonLocalizableStrings.ProjectAddedToTheSolution, projectToAdd)); } [Fact] public void ItAddsAnFSharpProjectThatIsMultitargeted() { var solutionDirectory = TestAssets .Get("TestAppsWithSlnAndMultitargetedProjects") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(solutionDirectory, "App.sln"); var projectToAdd = Path.Combine("MultitargetedFS", "MultitargetedFS.fsproj"); new DotnetCommand() .WithWorkingDirectory(solutionDirectory) .ExecuteWithCapturedOutput($"sln add {projectToAdd}") .Should() .Pass() .And .HaveStdOutContaining(string.Format(CommonLocalizableStrings.ProjectAddedToTheSolution, projectToAdd)); } private string GetExpectedSlnContents( string slnPath, string slnTemplate, string expectedLibProjectGuid = null) { var slnFile = SlnFile.Read(slnPath); if (string.IsNullOrEmpty(expectedLibProjectGuid)) { var matchingProjects = slnFile.Projects .Where((p) => p.FilePath.EndsWith("Lib.csproj")) .ToList(); matchingProjects.Count.Should().Be(1); var slnProject = matchingProjects[0]; expectedLibProjectGuid = slnProject.Id; } var slnContents = slnTemplate.Replace("__LIB_PROJECT_GUID__", expectedLibProjectGuid); var matchingSrcFolder = slnFile.Projects .Where((p) => p.FilePath == "src") .ToList(); if (matchingSrcFolder.Count == 1) { slnContents = slnContents.Replace("__SRC_FOLDER_GUID__", matchingSrcFolder[0].Id); } return slnContents; } } }
// // (C) Copyright 2003-2012 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Mechanical; using Autodesk.Revit.UI.Plumbing; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Mechanical; using Autodesk.Revit.DB.Plumbing; using Autodesk.Revit.DB.ExtensibleStorage; using Autodesk.Revit.DB.ExternalService; namespace UserFittingAndAccessoryCalculationUIServers { // Helper class for calculation. public static class CalculationUtility { // The maximum items in the history in the settings dialog. public static readonly int MAX_ITEMS_IN_HISTORY = 8; public static readonly double tol = 1e-9; public static bool IsNumeric(string strInput) { if (string.IsNullOrEmpty(strInput)) return false; try { double dOutput = Convert.ToDouble(strInput); } catch (System.Exception /*ex*/) { return false; } return true; } /// <summary> /// Gets initial items for ComboBox in settings dialog. /// </summary> /// <param name="history"> /// The list containing the settings history. /// </param> /// <param name="initialValue"> /// The initial value to be add to ComboBox. /// </param> /// <returns> /// Initial items for ComboBox. /// </returns> public static string[] GetInitialItemsForComboBox(List<string> history, string initialValue) { List<string> copyHistory = new List<string>(history.ToArray()); if (copyHistory.Contains(initialValue)) copyHistory.Remove(initialValue); copyHistory.Insert(0, initialValue); return copyHistory.ToArray(); } /// <summary> /// Gets initial items for ComboBox in settings dialog. /// </summary> /// <param name="history"> /// The list containing the settings history. /// </param> /// <param name="initialValue"> /// The initial value to be add to ComboBox. /// </param> /// <returns> /// Initial numeric items for ComboBox. /// </returns> public static string[] GetInitialItemsForComboBox(List<double> history, double initialValue, Units unit, UnitType unitType) { UpdateHistory(history, initialValue); List<string> strCopyHistory = new List<string>(); foreach (double item in history) { if (double.IsNaN(item)) continue; strCopyHistory.Add(UnitFormatUtils.FormatValueToString(unit, unitType, item, false, false)); } return strCopyHistory.ToArray(); } /// <summary> /// Updates the setting history in settings dialog. /// </summary> /// <param name="history"> /// The list containing the setting history. /// </param> /// <param name="newValue"> /// The new value to be added to the history. /// </param> public static void UpdateHistory(List<string> history, string newValue) { if (!string.IsNullOrEmpty(newValue)) { int index = history.IndexOf(newValue); if (index != -1) // The new value is already in the history, just move it to the first location in the history. { history.RemoveAt(index); history.Insert(0, newValue); } else // The new value is not in the history, insert it at the first location. { history.Insert(0, newValue); if (history.Count > MAX_ITEMS_IN_HISTORY) // If the items in the history exceeds the maximum count, just remove the oldest item. history.RemoveAt(history.Count - 1); } } } /// <summary> /// Updates the setting history in settings dialog. /// </summary> /// <param name="history"> /// The list containing the setting history. /// </param> /// <param name="newValue"> /// The new value to be added to the history. /// </param> public static void UpdateHistory(List<double> history, double newValue) { if (!double.IsNaN(newValue)) { int index = -1; foreach (double item in history) { if (Math.Abs(item - newValue) < tol) { index = history.IndexOf(item); break; } } if (index != -1) // The new value is already in the history, just move it to the first location in the history. { history.RemoveAt(index); history.Insert(0, newValue); } else // The new value is not in the history, insert it at the first location. { history.Insert(0, newValue); if (history.Count > MAX_ITEMS_IN_HISTORY) // If the items in the history exceeds the maximum count, just remove the oldest item. history.RemoveAt(history.Count - 1); } } } /// <summary> /// Shows a task dialog with warning message. /// </summary> /// <param name="title"> /// The title of the task dialog. /// </param> /// <param name="instruction"> /// The large primary text that appears at the top of the task dialog. /// </param> /// <param name="content"> /// The smaller text that appears just below the main instructions. /// </param> public static TaskDialogResult PostWarning(string title, string instruction, string content = null) { if (title == null || instruction == null) return TaskDialogResult.None; TaskDialog tDlg = new TaskDialog(title); tDlg.MainInstruction = instruction; tDlg.MainContent = content; tDlg.AllowCancellation = true; tDlg.CommonButtons = TaskDialogCommonButtons.Close; tDlg.DefaultButton = TaskDialogResult.Close; tDlg.TitleAutoPrefix = false; return tDlg.Show(); } /// <summary> /// Gets the initial value for the duct settings dialog /// </summary> /// <param name="data"> /// The duct fitting and accessory pressure drop UI data. /// </param> /// <param name="schemaField"> /// The schema field which is used to get the initial value. /// </param> /// <returns> /// The initial value which will be shown in the settings dialog. /// </returns> public static string GetInitialValue(DuctFittingAndAccessoryPressureDropUIData data, string schemaField) { string initialValue = String.Empty; IList<DuctFittingAndAccessoryPressureDropUIDataItem> uiDataItems = data.GetUIDataItems(); foreach (DuctFittingAndAccessoryPressureDropUIDataItem uiDataItem in uiDataItems) { string tmpValue = String.Empty; Entity entity = uiDataItem.GetEntity(); if (entity != null && entity.IsValid()) { tmpValue = entity.Get<string>(schemaField); } else // If only one entity is null or invalid, the initial value should be empty. { return String.Empty; } if (uiDataItems.IndexOf(uiDataItem) == 0) // The first element initialValue = tmpValue; else { if (tmpValue != initialValue) // If all elements don't have the same old values, the settings dialog will show empty initial value. { initialValue = String.Empty; break; } } } return initialValue; } /// <summary> /// Gets the initial value for the settings dialog /// </summary> /// <param name="data"> /// The pipe fitting and accessory pressure drop UI data. /// </param> /// <param name="dbServerId"> /// The corresponding DB server Id of the UI server. /// </param> /// <param name="schemaField"> /// The schema field which is used to get the initial value. /// </param> /// <returns> /// The initial value which will be shown in the settings dialog. /// </returns> public static string GetInitialValue(PipeFittingAndAccessoryPressureDropUIData data, string schemaField) { string initialValue = String.Empty; IList<PipeFittingAndAccessoryPressureDropUIDataItem> uiDataItems = data.GetUIDataItems(); foreach (PipeFittingAndAccessoryPressureDropUIDataItem uiDataItem in uiDataItems) { string tableName = String.Empty; Entity entity = uiDataItem.GetEntity(); if (entity != null && entity.IsValid()) { tableName = entity.Get<string>(schemaField); } else // If only one entity is null or invalid, the initial value should be empty. { return String.Empty; } if (uiDataItems.IndexOf(uiDataItem) == 0) // The first element initialValue = tableName; else { if (tableName != initialValue) // If all elements don't have the same old values, the settings dialog will show empty initial value. { initialValue = String.Empty; break; } } } return initialValue; } /// <summary> /// Gets the initial value for the settings dialog /// </summary> /// <param name="data"> /// The duct fitting and accessory pressure drop UI data. /// </param> /// <param name="dbServerId"> /// The corresponding DB server Id of the UI server. /// </param> /// <param name="schemaField"> /// The schema field which is used to get the initial value. /// </param> /// <returns> /// The initial numeric value which will be shown in the settings dialog. /// </returns> public static double GetInitialNumericValue(DuctFittingAndAccessoryPressureDropUIData data, string schemaField) { double initialValue = 0.0; IList<DuctFittingAndAccessoryPressureDropUIDataItem> uiDataItems = data.GetUIDataItems(); foreach (DuctFittingAndAccessoryPressureDropUIDataItem uiDataItem in uiDataItems) { string value = String.Empty; Entity entity = uiDataItem.GetEntity(); if (entity != null && entity.IsValid()) { value = entity.Get<string>(schemaField); } else { return double.NaN; } if (CalculationUtility.IsNumeric(value)) { double dValue = Convert.ToDouble(value); if (uiDataItems.IndexOf(uiDataItem) == 0) // The first element { initialValue = dValue; } else { if (!dValue.Equals(initialValue)) // If all elements don't have the same old values, the settings dialog will show empty initial value. { initialValue = double.NaN; break; } } } } return initialValue; } /// <summary> /// Gets the initial value for the settings dialog /// </summary> /// <param name="data"> /// The duct fitting and accessory pressure drop UI data. /// </param> /// <param name="dbServerId"> /// The corresponding DB server Id of the UI server. /// </param> /// <param name="schemaField"> /// The schema field which is used to get the initial value. /// </param> /// <returns> /// The initial numeric value which will be shown in the settings dialog. /// </returns> public static double GetInitialNumericValue(PipeFittingAndAccessoryPressureDropUIData data, string schemaField) { double initialValue = 0.0; IList<PipeFittingAndAccessoryPressureDropUIDataItem> uiDataItems = data.GetUIDataItems(); foreach (PipeFittingAndAccessoryPressureDropUIDataItem uiDataItem in uiDataItems) { string value = String.Empty; Entity entity = uiDataItem.GetEntity(); if (entity != null && entity.IsValid()) { value = entity.Get<string>(schemaField); } else { return double.NaN; } if (CalculationUtility.IsNumeric(value)) { double dValue = Convert.ToDouble(value); if (uiDataItems.IndexOf(uiDataItem) == 0) // The first element { initialValue = dValue; } else { if (!dValue.Equals(initialValue)) // If all elements don't have the same old values, the settings dialog will show empty initial value. { initialValue = double.NaN; break; } } } } return initialValue; } /// <summary> /// Updates the entity in the duct fitting and accessory pressure drop UI data. /// </summary> /// <param name="data"> /// The duct fitting and accessory pressure drop UI data. /// </param> /// <param name="dbServerId"> /// The corresponding DB server Id of the UI server. /// </param> /// <param name="schemaField"> /// The schema field to be updated. /// </param> /// <param name="newValue"> /// The new value to be set to the schema field. /// </param> /// <returns> /// True if the entity in the UI data is updated, false otherwise. /// </returns> public static bool UpdateEntities(DuctFittingAndAccessoryPressureDropUIData data, Guid dbServerId, string schemaField, string newValue) { bool isUpdated = false; ExternalService service = ExternalServiceRegistry.GetService(ExternalServices.BuiltInExternalServices.DuctFittingAndAccessoryPressureDropService) ; if (service == null) return isUpdated; IDuctFittingAndAccessoryPressureDropServer dbServer = service.GetServer(dbServerId) as IDuctFittingAndAccessoryPressureDropServer; if (dbServer == null) { return isUpdated; } Schema schema = dbServer.GetDataSchema(); if (schema == null) return isUpdated; Field field = schema.GetField(schemaField); if (field == null) return isUpdated; Entity entity = new Entity(schema); entity.Set<string>(field, newValue); IList<DuctFittingAndAccessoryPressureDropUIDataItem> uiDataItems = data.GetUIDataItems(); foreach (DuctFittingAndAccessoryPressureDropUIDataItem uiDataItem in uiDataItems) { Entity oldEntity = uiDataItem.GetEntity(); if (oldEntity == null && entity == null) { continue; } if (oldEntity == null || entity == null) { uiDataItem.SetEntity(entity); isUpdated = true; continue; } if ((!oldEntity.IsValid()) && (!entity.IsValid())) { continue; } if ((!oldEntity.IsValid()) || (!entity.IsValid())) { uiDataItem.SetEntity(entity); isUpdated = true; continue; } string oldValue = oldEntity.Get<string>(schemaField); if (oldValue != newValue) { uiDataItem.SetEntity(entity); isUpdated = true; continue; } } return isUpdated; } /// <summary> /// Updates the entity in the pipe fitting and accessory pressure drop UI data. /// </summary> /// <param name="data"> /// The pipe fitting and accessory pressure drop UI data. /// </param> /// <param name="dbServerId"> /// The corresponding DB server Id of the UI server. /// </param> /// <param name="schemaField"> /// The schema field to be updated. /// </param> /// <param name="newValue"> /// The new value to be set to the schema field. /// </param> /// <returns> /// True if the entity in the UI data is updated, false otherwise. /// </returns> public static bool UpdateEntities(PipeFittingAndAccessoryPressureDropUIData data, Guid dbServerId, string schemaField, string newValue) { bool isUpdated = false; ExternalService service = ExternalServiceRegistry.GetService(ExternalServices.BuiltInExternalServices.PipeFittingAndAccessoryPressureDropService); if (service == null) return isUpdated; IPipeFittingAndAccessoryPressureDropServer dbServer = service.GetServer(dbServerId) as IPipeFittingAndAccessoryPressureDropServer; if (dbServer == null) { return isUpdated; } Schema schema = dbServer.GetDataSchema(); if (schema == null) return isUpdated; Field field = schema.GetField(schemaField); if (field == null) return isUpdated; Entity entity = new Entity(schema); entity.Set<string>(field, newValue); IList<PipeFittingAndAccessoryPressureDropUIDataItem> uiDataItems = data.GetUIDataItems(); foreach (PipeFittingAndAccessoryPressureDropUIDataItem uiDataItem in uiDataItems) { Entity oldEntity = uiDataItem.GetEntity(); if (oldEntity == null && entity == null) { continue; } if (oldEntity == null || entity == null) { uiDataItem.SetEntity(entity); isUpdated = true; continue; } if ((!oldEntity.IsValid()) && (!entity.IsValid())) { continue; } if ((!oldEntity.IsValid()) || (!entity.IsValid())) { uiDataItem.SetEntity(entity); isUpdated = true; continue; } string oldValue = oldEntity.Get<string>(schemaField); if (oldValue != newValue) { uiDataItem.SetEntity(entity); isUpdated = true; continue; } } return isUpdated; } /// <summary> /// Checks if all pipe fittings or pipe accessories selected have the same PipeKFactorPartType. /// See FittingAndAccessoryCalculationManaged.PipeKFactorPartType /// </summary> /// <param name="uiDataItems"> /// The pipe fitting and accessory pressure drop UI data items. /// </param> /// <returns> /// True if all pipe fittings or pipe accessories selected have the same PipeKFactorPartType, false otherwise. /// </returns> public static bool HasSamePipeKFactorPartType(IList<PipeFittingAndAccessoryPressureDropUIDataItem> uiDataItems) { /* int count = 0; FittingAndAccessoryCalculationManaged.PipeKFactorPartType pipeKFactorPartType = FittingAndAccessoryCalculationManaged.PipeKFactorPartType.kUndefinedPipePartType; foreach (PipeFittingAndAccessoryPressureDropUIDataItem uiDataItem in uiDataItems) { PipeFittingAndAccessoryData fittingData = uiDataItem.GetPipeFittingAndAccessoryData(); if (fittingData == null) return false; FittingAndAccessoryCalculationManaged.PipeKFactorPartType iterPipeKFactorPartType = FittingAndAccessoryCalculationManaged.KFactorTablePipePressureDropCalculator.getKFactorPartType(fittingData.PartType, fittingData.BehaviorType); if (pipeKFactorPartType != iterPipeKFactorPartType) { pipeKFactorPartType = iterPipeKFactorPartType; count++; if (count > 1) return false; } } */ return true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace System.CommandLine { internal static class HelpTextGenerator { public static string Generate(ArgumentSyntax argumentSyntax, int maxWidth) { var forCommandList = argumentSyntax.ActiveCommand == null && argumentSyntax.Commands.Any(); var page = forCommandList ? GetCommandListHelp(argumentSyntax) : GetCommandHelp(argumentSyntax, argumentSyntax.ActiveCommand); var sb = new StringBuilder(); sb.WriteHelpPage(page, maxWidth); return sb.ToString(); } private struct HelpPage { public string ApplicationName; public IEnumerable<string> SyntaxElements; public IReadOnlyList<HelpRow> Rows; } private struct HelpRow { public string Header; public string Text; } private static void WriteHelpPage(this StringBuilder sb, HelpPage page, int maxWidth) { sb.WriteUsage(page.ApplicationName, page.SyntaxElements, maxWidth); if (!page.Rows.Any()) return; sb.AppendLine(); sb.WriteRows(page.Rows, maxWidth); sb.AppendLine(); } private static void WriteUsage(this StringBuilder sb, string applicationName, IEnumerable<string> syntaxElements, int maxWidth) { var usageHeader = string.Format(Strings.HelpUsageOfApplicationFmt, applicationName); sb.Append(usageHeader); if (syntaxElements.Any()) sb.Append(@" "); var syntaxIndent = usageHeader.Length + 1; var syntaxMaxWidth = maxWidth - syntaxIndent; sb.WriteWordWrapped(syntaxElements, syntaxIndent, syntaxMaxWidth); } private static void WriteRows(this StringBuilder sb, IReadOnlyList<HelpRow> rows, int maxWidth) { const int indent = 4; var maxColumnWidth = rows.Select(r => r.Header.Length).Max(); var helpStartColumn = maxColumnWidth + 2 * indent; var maxHelpWidth = maxWidth - helpStartColumn; if (maxHelpWidth < 0) maxHelpWidth = maxWidth; foreach (var row in rows) { var headerStart = sb.Length; sb.Append(' ', indent); sb.Append(row.Header); var headerLength = sb.Length - headerStart; var requiredSpaces = helpStartColumn - headerLength; sb.Append(' ', requiredSpaces); var words = SplitWords(row.Text); sb.WriteWordWrapped(words, helpStartColumn, maxHelpWidth); } } private static void WriteWordWrapped(this StringBuilder sb, IEnumerable<string> words, int indent, int maxidth) { var helpLines = WordWrapLines(words, maxidth); var isFirstHelpLine = true; foreach (var helpLine in helpLines) { if (isFirstHelpLine) isFirstHelpLine = false; else sb.Append(' ', indent); sb.AppendLine(helpLine); } if (isFirstHelpLine) sb.AppendLine(); } private static HelpPage GetCommandListHelp(ArgumentSyntax argumentSyntax) { return new HelpPage { ApplicationName = argumentSyntax.ApplicationName, SyntaxElements = GetGlobalSyntax(), Rows = GetCommandRows(argumentSyntax).ToArray() }; } private static HelpPage GetCommandHelp(ArgumentSyntax argumentSyntax, ArgumentCommand command) { return new HelpPage { ApplicationName = argumentSyntax.ApplicationName, SyntaxElements = GetCommandSyntax(argumentSyntax, command), Rows = GetArgumentRows(argumentSyntax, command).ToArray() }; } private static IEnumerable<string> GetGlobalSyntax() { yield return @"<command>"; yield return @"[<args>]"; } private static IEnumerable<string> GetCommandSyntax(ArgumentSyntax argumentSyntax, ArgumentCommand command) { if (command != null) yield return command.Name; foreach (var option in argumentSyntax.GetOptions(command).Where(o => !o.IsHidden)) yield return GetOptionSyntax(option); if (argumentSyntax.GetParameters(command).All(p => p.IsHidden)) yield break; if (argumentSyntax.GetOptions(command).Any(o => !o.IsHidden)) yield return @"[--]"; foreach (var parameter in argumentSyntax.GetParameters(command).Where(o => !o.IsHidden)) yield return GetParameterSyntax(parameter); } private static string GetOptionSyntax(Argument option) { var sb = new StringBuilder(); sb.Append(@"["); sb.Append(option.GetDisplayName()); if (!option.IsFlag) sb.Append(@" <arg>"); if (option.IsList) sb.Append(@"..."); sb.Append(@"]"); return sb.ToString(); } private static string GetParameterSyntax(Argument parameter) { var sb = new StringBuilder(); sb.Append(parameter.GetDisplayName()); if (parameter.IsList) sb.Append(@"..."); return sb.ToString(); } private static IEnumerable<HelpRow> GetCommandRows(ArgumentSyntax argumentSyntax) { return argumentSyntax.Commands .Where(c => !c.IsHidden) .Select(c => new HelpRow { Header = c.Name, Text = c.Help }); } private static IEnumerable<HelpRow> GetArgumentRows(ArgumentSyntax argumentSyntax, ArgumentCommand command) { return argumentSyntax.GetArguments(command) .Where(a => !a.IsHidden) .Select(a => new HelpRow { Header = GetArgumentRowHeader(a), Text = a.Help }); } private static string GetArgumentRowHeader(Argument argument) { var sb = new StringBuilder(); foreach (var displayName in argument.GetDisplayNames()) { if (sb.Length > 0) sb.Append(@", "); sb.Append(displayName); } if (argument.IsOption && !argument.IsFlag) sb.Append(@" <arg>"); if (argument.IsList) sb.Append(@"..."); return sb.ToString(); } private static IEnumerable<string> WordWrapLines(IEnumerable<string> tokens, int maxWidth) { var sb = new StringBuilder(); foreach (var token in tokens) { var newLength = sb.Length == 0 ? token.Length : sb.Length + 1 + token.Length; if (newLength > maxWidth) { if (sb.Length == 0) { yield return token; continue; } yield return sb.ToString(); sb.Clear(); } if (sb.Length > 0) sb.Append(@" "); sb.Append(token); } if (sb.Length > 0) yield return sb.ToString(); } private static IEnumerable<string> SplitWords(string text) { return string.IsNullOrEmpty(text) ? Enumerable.Empty<string>() : text.Split(' '); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; namespace OpenSim.Services.Connectors { public class AssetServicesConnector : IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; private IImprovedAssetCache m_Cache = null; public AssetServicesConnector() { } public AssetServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public AssetServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpanSim.ini"); throw new Exception("Asset connector init error"); } string serviceURI = assetConfig.GetString("AssetServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[ASSET CONNECTOR]: No Server URI named in section AssetService"); throw new Exception("Asset connector init error"); } m_ServerURI = serviceURI; } protected void SetCache(IImprovedAssetCache cache) { m_Cache = cache; } public AssetBase Get(string id) { string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { asset = SynchronousRestObjectRequester. MakeRequest<int, AssetBase>("GET", uri, 0); if (m_Cache != null) m_Cache.Cache(asset); } return asset; } public AssetMetadata GetMetadata(string id) { if (m_Cache != null) { AssetBase fullAsset = m_Cache.Get(id); if (fullAsset != null) return fullAsset.Metadata; } string uri = m_ServerURI + "/assets/" + id + "/metadata"; AssetMetadata asset = SynchronousRestObjectRequester. MakeRequest<int, AssetMetadata>("GET", uri, 0); return asset; } public byte[] GetData(string id) { if (m_Cache != null) { AssetBase fullAsset = m_Cache.Get(id); if (fullAsset != null) return fullAsset.Data; } RestClient rc = new RestClient(m_ServerURI); rc.AddResourcePath("assets"); rc.AddResourcePath(id); rc.AddResourcePath("data"); rc.RequestMethod = "GET"; Stream s = rc.Request(); if (s == null) return null; if (s.Length > 0) { byte[] ret = new byte[s.Length]; s.Read(ret, 0, (int)s.Length); return ret; } return null; } public bool Get(string id, Object sender, AssetRetrieved handler) { string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { AsynchronousRestObjectRequester. MakeRequest<int, AssetBase>("GET", uri, 0, delegate(AssetBase a) { if (m_Cache != null) m_Cache.Cache(a); handler(id, sender, a); }); } else { handler.BeginInvoke(id, sender, asset, null, null); } return true; } public string Store(AssetBase asset) { if (asset.Temporary || asset.Local) { if (m_Cache != null) m_Cache.Cache(asset); return asset.ID; } string uri = m_ServerURI + "/assets/"; string newID = string.Empty; try { newID = SynchronousRestObjectRequester. MakeRequest<AssetBase, string>("POST", uri, asset); } catch (Exception e) { m_log.WarnFormat("[ASSET CONNECTOR]: Unable to send asset {0} to asset server. Reason: {1}", asset.ID, e.Message); } if (newID != String.Empty) { // Placing this here, so that this work with old asset servers that don't send any reply back // SynchronousRestObjectRequester returns somethins that is not an empty string if (newID != null) asset.ID = newID; if (m_Cache != null) m_Cache.Cache(asset); } return newID; } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { AssetMetadata metadata = GetMetadata(id); if (metadata == null) return false; asset = new AssetBase(); asset.Metadata = metadata; } asset.Data = data; string uri = m_ServerURI + "/assets/" + id; if (SynchronousRestObjectRequester. MakeRequest<AssetBase, bool>("POST", uri, asset)) { if (m_Cache != null) m_Cache.Cache(asset); return true; } return false; } public bool Delete(string id) { string uri = m_ServerURI + "/assets/" + id; if (SynchronousRestObjectRequester. MakeRequest<int, bool>("DELETE", uri, 0)) { if (m_Cache != null) m_Cache.Expire(id); return true; } return false; } } }
/// Copyright (C) 2012-2014 Soomla Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using Soomla; using Soomla.Store; using Soomla.Levelup; using Soomla.Profile; namespace Soomla.Store.Example { /// <summary> /// This class contains functions that initialize the game and that display the different screens of the game. /// </summary> public class ExampleWindow : MonoBehaviour { private static ExampleWindow instance = null; private GUIState guiState = GUIState.WELCOME; private Vector2 goodsScrollPosition = Vector2.zero; private Vector2 productScrollPosition = Vector2.zero; private bool isDragging = false; private Vector2 startTouch = Vector2.zero; private static ExampleEventHandler handler; public string fontSuffix = ""; private enum GUIState{ WELCOME, PRODUCTS, GOODS } private static bool isVisible = false; /// <summary> /// Initializes the game state before the game starts. /// </summary> void Awake(){ if(instance == null){ //making sure we only initialize one instance. instance = this; GameObject.DontDestroyOnLoad(this.gameObject); } else { //Destroying unused instances. GameObject.Destroy(this); } //FONT //using max to be certain we have the longest side of the screen, even if we are in portrait. if(Mathf.Max(Screen.width, Screen.height) > 640){ fontSuffix = "_2X"; //a nice suffix to show the fonts are twice as big as the original } } private Texture2D tImgDirect; private Texture2D tLogoNew; private Font fgoodDog; private Font fgoodDogSmall; private Font fTitle; private Texture2D tWhitePixel; private Texture2D tMuffins; private Font fName; private Font fDesc; private Font fBuy; private Texture2D tBack; private Texture2D tGetMore; private Font tTitle; private Dictionary<string, Texture2D> itemsTextures; /// <summary> /// Starts this instance. /// Use this for initialization. /// </summary> void Start () { handler = new ExampleEventHandler(); SoomlaStore.Initialize(new MuffinRushAssets()); SoomlaProfile.Initialize (); //levelup World mainWorld = WorldGenerator.GenerateCustomWorld (); SoomlaLevelUp.Initialize (mainWorld); // WorldGenerator.Play (mainWorld); tImgDirect = (Texture2D)Resources.Load("SoomlaStore/images/img_direct"); fgoodDog = (Font)Resources.Load("SoomlaStore/GoodDog" + fontSuffix); fgoodDogSmall = (Font)Resources.Load("SoomlaStore/GoodDog_small" + fontSuffix); tLogoNew = (Texture2D)Resources.Load("SoomlaStore/images/soomla_logo_new"); tWhitePixel = (Texture2D)Resources.Load("SoomlaStore/images/white_pixel"); fTitle = (Font)Resources.Load("SoomlaStore/Title" + fontSuffix); tMuffins = (Texture2D)Resources.Load("SoomlaStore/images/Muffins"); fName = (Font)Resources.Load("SoomlaStore/Name" + fontSuffix); fDesc = (Font)Resources.Load("SoomlaStore/Description" + fontSuffix); fBuy = (Font)Resources.Load("SoomlaStore/Buy" + fontSuffix); tBack = (Texture2D)Resources.Load("SoomlaStore/images/back"); tGetMore = (Texture2D)Resources.Load("SoomlaStore/images/GetMore"); tTitle = (Font)Resources.Load("SoomlaStore/Title" + fontSuffix); } public static ExampleWindow GetInstance() { return instance; } public void setupItemsTextures() { itemsTextures = new Dictionary<string, Texture2D>(); foreach(VirtualGood vg in StoreInfo.Goods){ itemsTextures[vg.ItemId] = (Texture2D)Resources.Load("SoomlaStore/images/" + vg.Name); } foreach(VirtualCurrencyPack vcp in StoreInfo.CurrencyPacks){ itemsTextures[vcp.ItemId] = (Texture2D)Resources.Load("SoomlaStore/images/" + vcp.Name); } } /// <summary> /// Sets the window to open, and sets the GUI state to welcome. /// </summary> public static void OpenWindow(){ instance.guiState = GUIState.WELCOME; isVisible = true; } /// <summary> /// Sets the window to closed. /// </summary> public static void CloseWindow(){ isVisible = false; } /// <summary> /// Implements the game behavior of MuffinRush. /// Overrides the superclass function in order to provide functionality for our game. /// </summary> void Update () { if(isVisible){ //code to be able to scroll without the scrollbars. if(Input.GetMouseButtonDown(0)){ startTouch = Input.mousePosition; }else if(Input.GetMouseButtonUp(0)){ isDragging = false; }else if(Input.GetMouseButton(0)){ if(!isDragging){ if( Mathf.Abs(startTouch.y-Input.mousePosition.y) > 10f){ isDragging = true; } }else{ if(guiState == GUIState.GOODS){ goodsScrollPosition.y -= startTouch.y - Input.mousePosition.y; startTouch = Input.mousePosition; }else if(guiState == GUIState.PRODUCTS){ productScrollPosition.y -= startTouch.y - Input.mousePosition.y; startTouch = Input.mousePosition; } } } } if (Application.platform == RuntimePlatform.Android) { if (Input.GetKeyUp(KeyCode.Escape)) { //quit application on back button Application.Quit(); return; } } } /// <summary> /// Calls the relevant function to display the correct screen of the game. /// </summary> void OnGUI(){ if(!isVisible){ return; } //GUI.skin.verticalScrollbar.fixedWidth = 0; //GUI.skin.verticalScrollbar.fixedHeight = 0; //GUI.skin.horizontalScrollbar.fixedWidth = 0; //GUI.skin.horizontalScrollbar.fixedHeight = 0; GUI.skin.horizontalScrollbar = GUIStyle.none; GUI.skin.verticalScrollbar = GUIStyle.none; //disabling warnings because we use GUIStyle.none which result in warnings if(guiState == GUIState.WELCOME){ welcomeScreen(); }else if(guiState == GUIState.GOODS){ goodsScreen(); }else if(guiState == GUIState.PRODUCTS){ currencyScreen(); } } /// <summary> /// Displays the welcome screen of the game. /// </summary> void welcomeScreen() { //drawing background, just using a white pixel here GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),tImgDirect); //changing the font and alignment the label, and making a backup so we can put it back. Font backupFont = GUI.skin.label.font; TextAnchor backupAlignment = GUI.skin.label.alignment; GUI.skin.label.font = fgoodDog; GUI.skin.label.alignment = TextAnchor.MiddleCenter; //writing the text. GUI.Label(new Rect(Screen.width/8,Screen.height/8f,Screen.width*6f/8f,Screen.height*0.3f),"Soomla Store\nExample"); //select the small font GUI.skin.label.font = fgoodDogSmall; GUI.Label(new Rect(Screen.width/8,Screen.height*7f/8f,Screen.width*6f/8f,Screen.height/8f),"Press the SOOMLA-bot to open store"); //set font back to original GUI.skin.label.font = backupFont; GUI.Label(new Rect(Screen.width*0.25f,Screen.height/2-50,Screen.width*0.5f,100),"[ Your game here ]"); //drawing button and testing if it has been clicked if(GUI.Button(new Rect(Screen.width*2/6,Screen.height*5f/8f,Screen.width*2/6,Screen.width*2/6),tLogoNew)){ guiState = GUIState.GOODS; #if UNITY_ANDROID && !UNITY_EDITOR SoomlaStore.StartIabServiceInBg(); #endif } //set alignment to backup GUI.skin.label.alignment = backupAlignment; } /// <summary> /// Display the goods screen of the game's store. /// </summary> void goodsScreen() { //white background GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height), tWhitePixel); Color backupColor = GUI.color; TextAnchor backupAlignment = GUI.skin.label.alignment; Font backupFont = GUI.skin.label.font; GUI.color = Color.red; GUI.skin.label.alignment = TextAnchor.UpperLeft; GUI.Label(new Rect(10,10,Screen.width-10,Screen.height-10),"SOOMLA Example Store"); GUI.color = Color.black; GUI.skin.label.alignment = TextAnchor.UpperRight; GUI.Label(new Rect(10,10,Screen.width-40,Screen.height),""+ StoreInventory.GetItemBalance(StoreInfo.Currencies[0].ItemId)); GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.skin.label.font = fTitle; GUI.Label(new Rect(0,Screen.height/8f,Screen.width,Screen.height/8f),"Virtual Goods"); if(GUI.Button(new Rect(10,30,Screen.width-40,20), "Login")){ SoomlaProfile.Login(Provider.GOOGLE, "", null); } GUI.color = backupColor; GUI.DrawTexture(new Rect(Screen.width-30,10,30,30), tMuffins); float productSize = Screen.width*0.30f; float totalHeight = StoreInfo.Goods.Count*productSize; //Here we start a scrollView, the first rectangle is the position of the scrollView on the screen, //the second rectangle is the size of the panel inside the scrollView. //All rectangles after this point are relative to the position of the scrollView. goodsScrollPosition = GUI.BeginScrollView(new Rect(0,Screen.height*2f/8f,Screen.width,Screen.height*5f/8f),goodsScrollPosition,new Rect(0,0,Screen.width,totalHeight)); float y = 0; foreach(VirtualGood vg in StoreInfo.Goods){ GUI.color = backupColor; if(GUI.Button(new Rect(0,y,Screen.width,productSize),"") && !isDragging){ Debug.Log("SOOMLA/UNITY wants to buy: " + vg.Name); try { StoreInventory.BuyItem(vg.ItemId); } catch (Exception e) { Debug.Log ("SOOMLA/UNITY " + e.Message); } } GUI.DrawTexture(new Rect(0,y,Screen.width,productSize),tWhitePixel); //We draw a button so we can detect a touch and then draw an image on top of it. //TODO //Resources.Load(path) The path is the relative path starting from the Resources folder. //Make sure the images used for UI, have the textureType GUI. You can change this in the Unity editor. GUI.color = backupColor; GUI.DrawTexture(new Rect(0+productSize/8f, y+productSize/8f,productSize*6f/8f,productSize*6f/8f), itemsTextures[vg.ItemId]); GUI.color = Color.black; GUI.skin.label.font = fName; GUI.skin.label.alignment = TextAnchor.UpperLeft; GUI.Label(new Rect(productSize,y,Screen.width,productSize/3f),vg.Name); GUI.skin.label.font = fDesc; GUI.Label(new Rect(productSize + 10f,y+productSize/3f,Screen.width-productSize-15f,productSize/3f),vg.Description); //set price if (vg.PurchaseType is PurchaseWithVirtualItem) GUI.Label(new Rect(Screen.width/2f,y+productSize*2/3f,Screen.width,productSize/3f),"price:" + ((PurchaseWithVirtualItem)vg.PurchaseType).Amount); else GUI.Label(new Rect(Screen.width/2f,y+productSize*2/3f,Screen.width,productSize/3f),"price:$ " + ((PurchaseWithMarket)vg.PurchaseType).MarketItem.Price.ToString("0.00")); GUI.Label(new Rect(Screen.width*3/4f,y+productSize*2/3f,Screen.width,productSize/3f), "Balance:" + StoreInventory.GetItemBalance(vg.ItemId)); GUI.skin.label.alignment = TextAnchor.UpperRight; GUI.skin.label.font = fBuy; GUI.Label(new Rect(0,y,Screen.width-10,productSize),"Click to buy"); GUI.color = Color.grey; GUI.DrawTexture(new Rect(0,y+productSize-1,Screen.width,1),tWhitePixel); y+= productSize; } GUI.EndScrollView(); //We have just ended the scroll view this means that all the positions are relative top-left corner again. GUI.skin.label.alignment = backupAlignment; GUI.color = backupColor; GUI.skin.label.font = backupFont; float height = Screen.height/8f; float borderSize = height/8f; float buttonHeight = height-2*borderSize; float width = buttonHeight*180/95; if(GUI.Button(new Rect(Screen.width*2f/7f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight), "back")){ guiState = GUIState.WELCOME; #if UNITY_ANDROID && !UNITY_EDITOR SoomlaStore.StopIabServiceInBg(); #endif } GUI.DrawTexture(new Rect(Screen.width*2f/7f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight),tBack); width = buttonHeight*227/94; if(GUI.Button(new Rect(Screen.width*5f/7f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight), "back")){ guiState = GUIState.PRODUCTS; } GUI.DrawTexture(new Rect(Screen.width*5f/7f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight),tGetMore); } /// <summary> /// Displays the currencies screen of the game's store. /// </summary> void currencyScreen() { //white background GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),tWhitePixel); Color backupColor = GUI.color; TextAnchor backupAlignment = GUI.skin.label.alignment; Font backupFont = GUI.skin.label.font; GUI.color = Color.red; GUI.skin.label.alignment = TextAnchor.UpperLeft; GUI.Label(new Rect(10,10,Screen.width-10,Screen.height-10),"SOOMLA Example Store"); GUI.color = Color.black; GUI.skin.label.alignment = TextAnchor.UpperRight; GUI.Label(new Rect(10,10,Screen.width-40,Screen.height),""+StoreInventory.GetItemBalance(StoreInfo.Currencies[0].ItemId)); GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.skin.label.font = tTitle; GUI.Label(new Rect(0,Screen.height/8f,Screen.width,Screen.height/8f),"Virtual Currency Packs"); GUI.color = backupColor; GUI.DrawTexture(new Rect(Screen.width-30,10,30,30),tMuffins); float productSize = Screen.width*0.30f; float totalHeight = StoreInfo.CurrencyPacks.Count*productSize; //Here we start a scrollView, the first rectangle is the position of the scrollView on the screen, //the second rectangle is the size of the panel inside the scrollView. //All rectangles after this point are relative to the position of the scrollView. productScrollPosition = GUI.BeginScrollView(new Rect(0,Screen.height*2f/8f,Screen.width,Screen.height*5f/8f),productScrollPosition,new Rect(0,0,Screen.width,totalHeight)); float y = 0; foreach(VirtualCurrencyPack cp in StoreInfo.CurrencyPacks){ GUI.color = backupColor; //We draw a button so we can detect a touch and then draw an image on top of it. if(GUI.Button(new Rect(0,y,Screen.width,productSize),"") && !isDragging){ Debug.Log("SOOMLA/UNITY Wants to buy: " + cp.Name); try { StoreInventory.BuyItem(cp.ItemId); } catch (Exception e) { Debug.Log ("SOOMLA/UNITY " + e.Message); } } GUI.DrawTexture(new Rect(0,y,Screen.width,productSize),tWhitePixel); //Resources.Load(path) The path is the relative path starting from the Resources folder. //Make sure the images used for UI, have the textureType GUI. You can change this in the Unity editor. GUI.DrawTexture(new Rect(0+productSize/8f, y+productSize/8f,productSize*6f/8f,productSize*6f/8f),itemsTextures[cp.ItemId]); GUI.color = Color.black; GUI.skin.label.font = fName; GUI.skin.label.alignment = TextAnchor.UpperLeft; GUI.Label(new Rect(productSize,y,Screen.width,productSize/3f),cp.Name); GUI.skin.label.font = fDesc; GUI.Label(new Rect(productSize + 10f,y+productSize/3f,Screen.width-productSize-15f,productSize/3f),cp.Description); GUI.Label(new Rect(Screen.width*3/4f,y+productSize*2/3f,Screen.width,productSize/3f),"price:" + ((PurchaseWithMarket)cp.PurchaseType).MarketItem.Price.ToString("0.00")); GUI.skin.label.alignment = TextAnchor.UpperRight; GUI.skin.label.font = fBuy; GUI.Label(new Rect(0,y,Screen.width-10,productSize),"Click to buy"); GUI.color = Color.grey; GUI.DrawTexture(new Rect(0,y+productSize-1,Screen.width,1),tWhitePixel); y+= productSize; } GUI.EndScrollView(); //We have just ended the scroll view this means that all the positions are relative top-left corner again. GUI.skin.label.alignment = backupAlignment; GUI.color = backupColor; GUI.skin.label.font = backupFont; float height = Screen.height/8f; float borderSize = height/8f; float buttonHeight = height-2*borderSize; float width = buttonHeight*180/95; if(GUI.Button(new Rect(Screen.width/2f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight), "back")){ guiState = GUIState.GOODS; } GUI.DrawTexture(new Rect(Screen.width/2f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight),tBack); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #if UNITY_EDITOR using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// Helper class for launching external processes inside of the unity editor. /// </summary> public class ExternalProcess : IDisposable { [DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ExternalProcessAPI_CreateProcess([MarshalAs(UnmanagedType.LPStr)] string cmdline); [DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)] private static extern bool ExternalProcessAPI_IsRunning(IntPtr handle); [DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)] private static extern void ExternalProcessAPI_SendLine(IntPtr handle, [MarshalAs(UnmanagedType.LPStr)] string line); [DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ExternalProcessAPI_GetLine(IntPtr handle); [DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)] private static extern void ExternalProcessAPI_DestroyProcess(IntPtr handle); [DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)] public static extern void ExternalProcessAPI_ConfirmOrBeginProcess([MarshalAs(UnmanagedType.LPStr)] string processName); private IntPtr mHandle; /* * First some static utility functions, used by some other code as well. * They are related to "external processes" so they appear here. */ private static string sAppDataPath; public static void Launch(string appName) { // Full or relative paths only. Currently unused. if (!appName.StartsWith(@"\")) { appName += @"\"; } string appPath = AppDataPath + appName; string appDir = Path.GetDirectoryName(appPath); Process pr = new Process(); pr.StartInfo.FileName = appPath; pr.StartInfo.WorkingDirectory = appDir; pr.Start(); } private static string AppDataPath { get { if (string.IsNullOrEmpty(sAppDataPath)) { sAppDataPath = Application.dataPath.Replace("/", @"\"); } return sAppDataPath; } } public static bool FindAndLaunch(string appName) { return FindAndLaunch(appName, null); } public static bool FindAndLaunch(string appName, string args) { // Start at working directory, append appName (should read "appRelativePath"), see if it exists. // If not go up to parent and try again till drive level reached. string appPath = FindPathToExecutable(appName); if (appPath == null) { return false; } string appDir = Path.GetDirectoryName(appPath); Process pr = new Process(); pr.StartInfo.FileName = appPath; pr.StartInfo.WorkingDirectory = appDir; pr.StartInfo.Arguments = args; return pr.Start(); } public static string FindPathToExecutable(string appName) { // Start at working directory, append appName (should read "appRelativePath"), see if it exists. // If not go up to parent and try again till drive level reached. if (!appName.StartsWith(@"\")) { appName = @"\" + appName; } string searchDir = AppDataPath; while (searchDir.Length > 3) { string appPath = searchDir + appName; if (File.Exists(appPath)) { return appPath; } searchDir = Path.GetDirectoryName(searchDir); } return null; } public static string MakeRelativePath(string path1, string path2) { // TBD- doesn't really belong in ExternalProcess. path1 = path1.Replace('\\', '/'); path2 = path2.Replace('\\', '/'); path1 = path1.Replace("\"", ""); path2 = path2.Replace("\"", ""); Uri uri1 = new Uri(path1); Uri uri2 = new Uri(path2); Uri relativePath = uri1.MakeRelativeUri(uri2); return relativePath.OriginalString; } /* * The actual ExternalProcess class. */ public static ExternalProcess CreateExternalProcess(string appName) { return CreateExternalProcess(appName, null); } public static ExternalProcess CreateExternalProcess(string appName, string args) { // Seems like it would be safer and more informative to call this static method and test for null after. try { return new ExternalProcess(appName, args); } catch (Exception ex) { UnityEngine.Debug.LogError("Unable to start process " + appName + ", " + ex.Message + "."); } return null; } private ExternalProcess(string appName, string args) { appName = appName.Replace("/", @"\"); string appPath = appName; if (!File.Exists(appPath)) { appPath = FindPathToExecutable(appName); } if (appPath == null) { throw new ArgumentException("Unable to find app " + appPath); } // This may throw, calling code should catch the exception. string launchString = args == null ? appPath : appPath + " " + args; mHandle = ExternalProcessAPI_CreateProcess(launchString); } ~ExternalProcess() { Dispose(false); } public bool IsRunning() { try { if (mHandle != IntPtr.Zero) { return ExternalProcessAPI_IsRunning(mHandle); } } catch { Terminate(); } return false; } public bool WaitForStart(float seconds) { return WaitFor(seconds, () => { return ExternalProcessAPI_IsRunning(mHandle); }); } public bool WaitForShutdown(float seconds) { return WaitFor(seconds, () => { return !ExternalProcessAPI_IsRunning(mHandle); }); } public bool WaitFor(float seconds, Func<bool> func) { if (seconds <= 0.0f) seconds = 5.0f; float end = Time.realtimeSinceStartup + seconds; bool hasHappened = false; while (Time.realtimeSinceStartup < end) { hasHappened = func(); if (hasHappened) { break; } Thread.Sleep(Math.Min(500, (int)(seconds * 1000))); } return hasHappened; } public void SendLine(string line) { try { if (mHandle != IntPtr.Zero) { ExternalProcessAPI_SendLine(mHandle, line); } } catch { Terminate(); } } public string GetLine() { try { if (mHandle != IntPtr.Zero) { return Marshal.PtrToStringAnsi(ExternalProcessAPI_GetLine(mHandle)); } } catch { Terminate(); } return null; } public void Terminate() { try { if (mHandle != IntPtr.Zero) { ExternalProcessAPI_DestroyProcess(mHandle); } } catch { // TODO: Should we be catching something here? } mHandle = IntPtr.Zero; } // IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { Terminate(); } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestSuites; using Microsoft.Protocols.TestTools; namespace Microsoft.Protocols.TestSuites.Rdp { /// <summary> /// A singleton Handler shared by all protocol-based SUT control adapter /// </summary> public class SUTControlProtocolHandler { #region variables ITestSite Site; // Agent list: server list for SUT control protocols List<IPEndPoint> AgentList; ISUTControltransport transport; TimeSpan timeout; ushort requestId; // whether always need response bool alwaysNeedResponse; private static SUTControlProtocolHandler context = null; #endregion variables #region Property /// <summary> /// Whether using TCP transport /// </summary> public bool IsUsingTCP { get { return (transport is TCPSUTControlTransport); } } #endregion Property #region Constructor /// <summary> /// private Constructor /// </summary> /// <param name="testSite"></param> private SUTControlProtocolHandler(ITestSite testSite) { this.Site = testSite; // Initiate request id requestId = 1; // Initiate transport string transportType = testSite.Properties["SUTControl.TransportType"]; if (transportType == null) { transportType = "TCP"; } if (transportType.Equals("TCP")) { transport = new TCPSUTControlTransport(); } else { transport = new UDPSUTControlTransport(); } // Initiate timeout time span timeout = new TimeSpan(0, 0, 20); // Initiate Connect payload type bool clientSupportRDPFile = false; try { clientSupportRDPFile = bool.Parse(testSite.Properties["SUTControl.ClientSupportRDPFile"]); } catch { } // Initiate alwaysNeedResponse alwaysNeedResponse = true; try { alwaysNeedResponse = bool.Parse(testSite.Properties["SUTControl.AlwaysNeedResponse"]); } catch { } // Get Agent addresses string addresses = testSite.Properties["SUTControl.AgentAddress"]; string[] addressList = addresses.Split(';'); AgentList = new List<IPEndPoint>(); foreach (string address in addressList) { try { if (address != null && address.Trim().Length > 0) { int separator = address.IndexOf(':'); string add = address.Substring(0, separator).Trim(); string port = address.Substring(separator + 1).Trim(); IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(add), int.Parse(port)); AgentList.Add(endpoint); } } catch (Exception e) { this.Site.Log.Add(LogEntryKind.Comment, "RDP SUT Control Protocol Adapter: Illegal address string :" + e.Message); } } } #endregion Constructor #region public methods /// <summary> /// Static method to get a SUTControlProtocolHandler instance /// </summary> /// <param name="testSite"></param> /// <returns></returns> public static SUTControlProtocolHandler GetInstance(ITestSite testSite) { if (context == null) { context = new SUTControlProtocolHandler(testSite); } return context; } /// <summary> /// Get Next requestId /// </summary> /// <returns>RequestId</returns> public ushort GetNextRequestId() { return requestId++; } /// <summary> /// Send SUT control request message to SUT agent and get the response is necessary /// </summary> /// <param name="requestMessage">SUT Control Request Message</param> /// <param name="ResponseNeeded">Whether response is needed, if true, must get a response, if false, apply the value of alwaysNeedResponse</param> /// <param name="payload">out parameter, is the payload of response</param> /// <returns></returns> public int OperateSUTControl(SUT_Control_Request_Message requestMessage, bool ResponseNeeded, out byte[] payload) { payload = null; foreach (IPEndPoint agentEndpoint in AgentList) { if (transport.Connect(timeout, agentEndpoint)) { transport.SendSUTControlRequestMessage(requestMessage); if (alwaysNeedResponse || ResponseNeeded) { //expect response only when alwaysNeedResponse is true SUT_Control_Response_Message responseMessage = transport.ExpectSUTControlResponseMessage(timeout, requestMessage.requestId); if (responseMessage != null) { if (responseMessage.resultCode == (uint)SUTControl_ResultCode.SUCCESS) { transport.Disconnect(); payload = responseMessage.payload; this.Site.Log.Add(LogEntryKind.Comment, "RDP SUT Control Protocol Adapter: CommandId is {0}: Success, agent: {1}.", requestMessage.commandId, agentEndpoint.ToString()); return 1; } else { string errorMessage = (responseMessage.errorMessage != null) ? responseMessage.errorMessage : ""; this.Site.Log.Add(LogEntryKind.Comment, "RDP SUT Control Protocol Adapter: CommandId is {0}: error in response: {1}, error message: {2}", requestMessage.commandId, agentEndpoint.ToString(), errorMessage); } } else { this.Site.Log.Add(LogEntryKind.Comment, "RDP SUT Control Protocol Adapter: CommandId is {0}: Not get response from agent: {1}.", requestMessage.commandId, agentEndpoint.ToString()); } } transport.Disconnect(); } else { this.Site.Log.Add(LogEntryKind.Comment, "RDP SUT Control Protocol Adapter: CommandId is {0}: Cannot connect to the agent: {1}.", requestMessage.commandId, agentEndpoint.ToString()); } } if (alwaysNeedResponse || ResponseNeeded) { // if alwaysNeedResponse is true, all response return failure return -1; } else { // if alwaysNeedReponse is false, have send request to all Agents, return 1 for success return 1; } } #endregion Public methods } }
// 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.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Authorization { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; public static partial class RoleDefinitionsOperationsExtensions { /// <summary> /// Deletes the role definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope /// </param> /// <param name='roleDefinitionId'> /// Role definition id. /// </param> public static RoleDefinition Delete(this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId) { return Task.Factory.StartNew(s => ((IRoleDefinitionsOperations)s).DeleteAsync(scope, roleDefinitionId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the role definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope /// </param> /// <param name='roleDefinitionId'> /// Role definition id. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RoleDefinition> DeleteAsync( this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(scope, roleDefinitionId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get role definition by name (GUID). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope /// </param> /// <param name='roleDefinitionId'> /// Role definition Id /// </param> public static RoleDefinition Get(this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId) { return Task.Factory.StartNew(s => ((IRoleDefinitionsOperations)s).GetAsync(scope, roleDefinitionId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get role definition by name (GUID). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope /// </param> /// <param name='roleDefinitionId'> /// Role definition Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RoleDefinition> GetAsync( this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(scope, roleDefinitionId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a role definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope /// </param> /// <param name='roleDefinitionId'> /// Role definition id. /// </param> /// <param name='roleDefinition'> /// Role definition. /// </param> public static RoleDefinition CreateOrUpdate(this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId, RoleDefinition roleDefinition) { return Task.Factory.StartNew(s => ((IRoleDefinitionsOperations)s).CreateOrUpdateAsync(scope, roleDefinitionId, roleDefinition), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a role definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope /// </param> /// <param name='roleDefinitionId'> /// Role definition id. /// </param> /// <param name='roleDefinition'> /// Role definition. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RoleDefinition> CreateOrUpdateAsync( this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId, RoleDefinition roleDefinition, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(scope, roleDefinitionId, roleDefinition, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get role definition by name (GUID). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='roleDefinitionId'> /// Fully qualified role definition Id /// </param> public static RoleDefinition GetById(this IRoleDefinitionsOperations operations, string roleDefinitionId) { return Task.Factory.StartNew(s => ((IRoleDefinitionsOperations)s).GetByIdAsync(roleDefinitionId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get role definition by name (GUID). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='roleDefinitionId'> /// Fully qualified role definition Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RoleDefinition> GetByIdAsync( this IRoleDefinitionsOperations operations, string roleDefinitionId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetByIdWithHttpMessagesAsync(roleDefinitionId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get all role definitions that are applicable at scope and above. Use /// atScopeAndBelow filter to search below the given scope as well /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<RoleDefinition> List(this IRoleDefinitionsOperations operations, string scope, ODataQuery<RoleDefinitionFilter> odataQuery = default(ODataQuery<RoleDefinitionFilter>)) { return Task.Factory.StartNew(s => ((IRoleDefinitionsOperations)s).ListAsync(scope, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get all role definitions that are applicable at scope and above. Use /// atScopeAndBelow filter to search below the given scope as well /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RoleDefinition>> ListAsync( this IRoleDefinitionsOperations operations, string scope, ODataQuery<RoleDefinitionFilter> odataQuery = default(ODataQuery<RoleDefinitionFilter>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(scope, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get all role definitions that are applicable at scope and above. Use /// atScopeAndBelow filter to search below the given scope as well /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<RoleDefinition> ListNext(this IRoleDefinitionsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IRoleDefinitionsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get all role definitions that are applicable at scope and above. Use /// atScopeAndBelow filter to search below the given scope as well /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RoleDefinition>> ListNextAsync( this IRoleDefinitionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests { using System; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using ConfigDataInfo; using IaasCmdletInfo; using Management.Model; using Microsoft.WindowsAzure.ServiceManagement; using Model; //using Microsoft.WindowsAzure.ServiceManagement; //using Microsoft.WindowsAzure.Management.Model; //using Microsoft.WindowsAzure.Management.ServiceManagement.Model; //using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.IaasCmdletInfo; //using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; using System.Collections.Generic; public class ServiceManagementCmdletTestHelper { public Collection <PSObject> RunPSScript(string script) { List<string> st = new List<string>(); st.Add(script); WindowsAzurePowershellScript azurePowershellCmdlet = new WindowsAzurePowershellScript(st); return azurePowershellCmdlet.Run(); } public bool TestAzureServiceName(string serviceName) { TestAzureNameCmdletInfo testAzureNameCmdlet = new TestAzureNameCmdletInfo("Service", serviceName); WindowsAzurePowershellCmdlet testAzureName = new WindowsAzurePowershellCmdlet(testAzureNameCmdlet); Collection<bool> response = new Collection<bool>(); foreach (PSObject result in testAzureName.Run()) { response.Add((bool)result.BaseObject); } return response[0]; } public Collection<LocationsContext> GetAzureLocation() { GetAzureLocationCmdletInfo getAzureLocationCmdlet = new GetAzureLocationCmdletInfo(); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureLocationCmdlet); Collection<LocationsContext> locationsContext = new Collection<LocationsContext>(); foreach (PSObject result in azurePowershellCmdlet.Run()) { locationsContext.Add((LocationsContext)result.BaseObject); } return locationsContext; } public string GetAzureLocationName(string[] keywords, bool exactMatch = true) { Collection<LocationsContext> locations = GetAzureLocation(); if (keywords != null) { foreach (LocationsContext location in locations) { if (Utilities.MatchKeywords(location.Name, keywords, exactMatch) >= 0) { return location.Name; } } } else { if (locations.Count == 1) { return locations[0].Name; } } return null; } public Collection<OSVersionsContext> GetAzureOSVersion() { GetAzureOSVersionCmdletInfo getAzureOSVersionCmdletInfo = new GetAzureOSVersionCmdletInfo(); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureOSVersionCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<OSVersionsContext> osVersions = new Collection<OSVersionsContext>(); foreach (PSObject re in result) { osVersions.Add((OSVersionsContext)re.BaseObject); } return osVersions; } #region CertificateSetting, VMConifig, ProvisioningConfig public CertificateSetting NewAzureCertificateSetting(string thumbprint, string store) { NewAzureCertificateSettingCmdletInfo newAzureCertificateSettingCmdletInfo = new NewAzureCertificateSettingCmdletInfo(thumbprint, store); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureCertificateSettingCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (CertificateSetting)result[0].BaseObject; } return null; } public PersistentVM NewAzureVMConfig(AzureVMConfigInfo vmConfig) { NewAzureVMConfigCmdletInfo newAzureVMConfigCmdletInfo = new NewAzureVMConfigCmdletInfo(vmConfig); WindowsAzurePowershellCmdlet newAzureServiceCmdlet = new WindowsAzurePowershellCmdlet(newAzureVMConfigCmdletInfo); Collection<PSObject> result = newAzureServiceCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } public PersistentVM AddAzureProvisioningConfig(AzureProvisioningConfigInfo provConfig) { AddAzureProvisioningConfigCmdletInfo addAzureProvisioningConfigCmdletInfog = new AddAzureProvisioningConfigCmdletInfo(provConfig); WindowsAzurePowershellCmdlet addAzureProvisioningConfigCmdlet = new WindowsAzurePowershellCmdlet(addAzureProvisioningConfigCmdletInfog); Collection<PSObject> result = addAzureProvisioningConfigCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } #endregion #region AzureAffinityGroup public ManagementOperationContext NewAzureAffinityGroup(string name, string location, string label, string description) { NewAzureAffinityGroupCmdletInfo newAzureAffinityGroupCmdletInfo = new NewAzureAffinityGroupCmdletInfo(name, location, label, description); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureAffinityGroupCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public Collection<AffinityGroupContext> GetAzureAffinityGroup(string name) { GetAzureAffinityGroupCmdletInfo getAzureAffinityGroupCmdletInfo = new GetAzureAffinityGroupCmdletInfo(name); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureAffinityGroupCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<AffinityGroupContext> certCtxts = new Collection<AffinityGroupContext>(); foreach (PSObject re in result) { certCtxts.Add((AffinityGroupContext)re.BaseObject); } return certCtxts; } public ManagementOperationContext SetAzureAffinityGroup(string name, string label, string description) { SetAzureAffinityGroupCmdletInfo setAzureAffinityGroupCmdletInfo = new SetAzureAffinityGroupCmdletInfo(name, label, description); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureAffinityGroupCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public ManagementOperationContext RemoveAzureAffinityGroup(string name) { RemoveAzureAffinityGroupCmdletInfo removeAzureAffinityGroupCmdletInfo = new RemoveAzureAffinityGroupCmdletInfo(name); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureAffinityGroupCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } #endregion #region AzureCertificate public ManagementOperationContext AddAzureCertificate(string serviceName, PSObject cert, string password) { AddAzureCertificateCmdletInfo addAzureCertificateCmdletInfo = new AddAzureCertificateCmdletInfo(serviceName, cert, password); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(addAzureCertificateCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public ManagementOperationContext AddAzureCertificate(string serviceName, PSObject cert) { return AddAzureCertificate(serviceName, cert, null); } public Collection <CertificateContext> GetAzureCertificate(string serviceName, string thumbprint, string algorithm) { GetAzureCertificateCmdletInfo getAzureCertificateCmdletInfo = new GetAzureCertificateCmdletInfo(serviceName, thumbprint, algorithm); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureCertificateCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<CertificateContext> certCtxts = new Collection<CertificateContext>(); foreach (PSObject re in result) { certCtxts.Add((CertificateContext)re.BaseObject); } return certCtxts; } public Collection<CertificateContext> GetAzureCertificate(string serviceName) { return GetAzureCertificate(serviceName, null, null); } public ManagementOperationContext RemoveAzureCertificate(string serviceName, string thumbprint, string algorithm) { RemoveAzureCertificateCmdletInfo removeAzureCertificateCmdletInfo = new RemoveAzureCertificateCmdletInfo(serviceName, thumbprint, algorithm); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureCertificateCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } #endregion #region AzureDataDisk public PersistentVM AddAzureDataDisk(AddAzureDataDiskConfig diskConfig) { AddAzureDataDiskCmdletInfo addAzureDataDiskCmdletInfo = new AddAzureDataDiskCmdletInfo(diskConfig); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(addAzureDataDiskCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } public void AddDataDisk(string vmName, string serviceName, AddAzureDataDiskConfig [] diskConfigs) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (AddAzureDataDiskConfig config in diskConfigs) { config.Vm = vm; vm = AddAzureDataDisk(config); } UpdateAzureVM(vmName, serviceName, vm); } public PersistentVM SetAzureDataDisk(SetAzureDataDiskConfig discCfg) { SetAzureDataDiskCmdletInfo setAzureDataDiskCmdletInfo = new SetAzureDataDiskCmdletInfo(discCfg); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureDataDiskCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } public void SetDataDisk(string vmName, string serviceName, HostCaching hc, int lun) { SetAzureDataDiskConfig config = new SetAzureDataDiskConfig(hc, lun); config.Vm = GetAzureVM(vmName, serviceName).VM; UpdateAzureVM(vmName, serviceName, SetAzureDataDisk(config)); } public Collection<DataVirtualHardDisk> GetAzureDataDisk(string vmName, string serviceName) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); GetAzureDataDiskCmdletInfo getAzureDataDiskCmdlet = new GetAzureDataDiskCmdletInfo(vmRolectx.VM); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureDataDiskCmdlet); Collection<DataVirtualHardDisk> hardDisks = new Collection<DataVirtualHardDisk>(); foreach (PSObject disk in azurePowershellCmdlet.Run()) { hardDisks.Add((DataVirtualHardDisk)disk.BaseObject); } return hardDisks; } private PersistentVM RemoveAzureDataDisk(RemoveAzureDataDiskConfig discCfg) { RemoveAzureDataDiskCmdletInfo removeAzureDataDiskCmdletInfo = new RemoveAzureDataDiskCmdletInfo(discCfg); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureDataDiskCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } public void RemoveDataDisk(string vmName, string serviceName, int [] lunSlots) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (int lun in lunSlots) { RemoveAzureDataDiskConfig config = new RemoveAzureDataDiskConfig(lun, vm); RemoveAzureDataDisk(config); } UpdateAzureVM(vmName, serviceName, vm); } #endregion #region AzureDeployment public ManagementOperationContext NewAzureDeployment(string serviceName, string packagePath, string configPath, string slot, string label, string name, bool doNotStart, bool warning) { NewAzureDeploymentCmdletInfo newAzureDeploymentCmdletInfo = new NewAzureDeploymentCmdletInfo(serviceName, packagePath, configPath, slot, label, name, doNotStart, warning); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureDeploymentCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public DeploymentInfoContext GetAzureDeployment(string serviceName, string slot) { GetAzureDeploymentCmdletInfo getAzureDeploymentCmdletInfo = new GetAzureDeploymentCmdletInfo(serviceName, slot); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureDeploymentCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (DeploymentInfoContext)result[0].BaseObject; } return null; } private ManagementOperationContext SetAzureDeployment(SetAzureDeploymentCmdletInfo cmdletInfo) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(cmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public ManagementOperationContext SetAzureDeploymentStatus(string serviceName, string slot, string newStatus) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentStatusCmdletInfo(serviceName, slot, newStatus)); } public ManagementOperationContext SetAzureDeploymentConfig(string serviceName, string slot, string configPath) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentConfigCmdletInfo(serviceName, slot, configPath)); } public ManagementOperationContext SetAzureDeploymentUpgrade(string serviceName, string slot, string mode, string packagePath, string configPath) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentUpgradeCmdletInfo(serviceName, slot, mode, packagePath, configPath)); } public ManagementOperationContext SetAzureDeployment(string option, string serviceName, string packagePath, string newStatus, string configName, string slot, string mode, string label, string roleName, bool force) { return SetAzureDeployment(new SetAzureDeploymentCmdletInfo(option, serviceName, packagePath, newStatus, configName, slot, mode, label, roleName, force)); } public ManagementOperationContext RemoveAzureDeployment(string serviceName, string slot, bool force) { RemoveAzureDeploymentCmdletInfo removeAzureDeploymentCmdletInfo = new RemoveAzureDeploymentCmdletInfo(serviceName, slot, force); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureDeploymentCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public ManagementOperationContext MoveAzureDeployment(string serviceName) { MoveAzureDeploymentCmdletInfo moveAzureDeploymentCmdletInfo = new MoveAzureDeploymentCmdletInfo(serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(moveAzureDeploymentCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } #endregion #region AzureDisk // Add-AzureDisk public DiskContext AddAzureDisk(string diskName, string mediaPath, string label, string os) { AddAzureDiskCmdletInfo addAzureDiskCmdletInfo = new AddAzureDiskCmdletInfo(diskName, mediaPath, label, os); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(addAzureDiskCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (DiskContext)result[0].BaseObject; } return null; } // Get-AzureDisk public Collection<DiskContext> GetAzureDisk(string diskName) { return GetAzureDisk(new GetAzureDiskCmdletInfo(diskName)); } public Collection<DiskContext> GetAzureDisk() { return GetAzureDisk(new GetAzureDiskCmdletInfo((string)null)); } private Collection<DiskContext> GetAzureDisk(GetAzureDiskCmdletInfo getAzureDiskCmdletInfo) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureDiskCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<DiskContext> disks = new Collection<DiskContext>(); foreach (PSObject re in result) { disks.Add((DiskContext)re.BaseObject); } return disks; } public Collection<DiskContext> GetAzureDiskAttachedToRoleName(string[] roleName, bool exactMatch = true) { Collection<DiskContext> retDisks = new Collection<DiskContext>(); Collection<DiskContext> disks = GetAzureDisk(); foreach (DiskContext disk in disks) { if (disk.AttachedTo != null && disk.AttachedTo.RoleName != null) { if (Utilities.MatchKeywords(disk.AttachedTo.RoleName, roleName, exactMatch) >= 0) retDisks.Add(disk); } } return retDisks; } // Remove-AzureDisk public ManagementOperationContext RemoveAzureDisk(string diskName, bool deleteVhd) { RemoveAzureDiskCmdletInfo removeAzureDiskCmdletInfo = new RemoveAzureDiskCmdletInfo(diskName, deleteVhd); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureDiskCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } // Update-AzureDisk public DiskContext UpdateAzureDisk(string diskName, string label) { UpdateAzureDiskCmdletInfo updateAzureDiskCmdletInfo = new UpdateAzureDiskCmdletInfo(diskName, label); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(updateAzureDiskCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (DiskContext)result[0].BaseObject; } return null; } #endregion #region AzureDns public DnsServer NewAzureDns(string name, string ipAddress) { NewAzureDnsCmdletInfo newAzureDnsCmdletInfo = new NewAzureDnsCmdletInfo(name, ipAddress); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureDnsCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (DnsServer)result[0].BaseObject; } return null; } public DnsServerList GetAzureDns(DnsSettings settings) { GetAzureDnsCmdletInfo getAzureDnsCmdletInfo = new GetAzureDnsCmdletInfo(settings); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureDnsCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); DnsServerList dnsList = new DnsServerList(); foreach (PSObject re in result) { dnsList.Add((DnsServer)re.BaseObject); } return dnsList; } #endregion #region AzureEndpoint public PersistentVM AddAzureEndPoint(AzureEndPointConfigInfo endPointConfig) { AddAzureEndpointCmdletInfo addAzureEndPointCmdletInfo = new AddAzureEndpointCmdletInfo(endPointConfig); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(addAzureEndPointCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } public PersistentVM AddAzureEndPointNoLB(AzureEndPointConfigInfo endPointConfig) { AddAzureEndpointCmdletInfo addAzureEndPointCmdletInfo = AddAzureEndpointCmdletInfo.BuildNoLoadBalancedCmdletInfo(endPointConfig); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(addAzureEndPointCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } public void AddEndPoint(string vmName, string serviceName, AzureEndPointConfigInfo [] endPointConfigs) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (AzureEndPointConfigInfo config in endPointConfigs) { config.Vm = vm; vm = AddAzureEndPointNoLB(config); } UpdateAzureVM(vmName, serviceName, vm); } public Collection <InputEndpointContext> GetAzureEndPoint(PersistentVMRoleContext vmRoleCtxt) { GetAzureEndpointCmdletInfo getAzureEndpointCmdletInfo = new GetAzureEndpointCmdletInfo(vmRoleCtxt); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureEndpointCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<InputEndpointContext> epCtxts = new Collection<InputEndpointContext>(); foreach(PSObject re in result) { epCtxts.Add((InputEndpointContext)re.BaseObject); } return epCtxts; } public PersistentVM SetAzureEndPoint(AzureEndPointConfigInfo endPointConfig) { if (null != endPointConfig) { SetAzureEndpointCmdletInfo setAzureEndpointCmdletInfo = SetAzureEndpointCmdletInfo.BuildNoLoadBalancedCmdletInfo(endPointConfig); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureEndpointCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } } return null; } public void SetEndPoint(string vmName, string serviceName, AzureEndPointConfigInfo endPointConfig) { endPointConfig.Vm = GetAzureVM(vmName, serviceName).VM; UpdateAzureVM(vmName, serviceName, SetAzureEndPoint(endPointConfig)); } public PersistentVMRoleContext RemoveAzureEndPoint(string epName, PersistentVMRoleContext vmRoleCtxt) { RemoveAzureEndpointCmdletInfo removeAzureEndPointCmdletInfo = new RemoveAzureEndpointCmdletInfo(epName, vmRoleCtxt); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureEndPointCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVMRoleContext)result[0].BaseObject; } return null; } public void RemoveEndPoint(string vmName, string serviceName, string [] epNames) { PersistentVMRoleContext vmRoleCtxt = GetAzureVM(vmName, serviceName); foreach (string ep in epNames) { vmRoleCtxt.VM = RemoveAzureEndPoint(ep, vmRoleCtxt).VM; } UpdateAzureVM(vmName, serviceName, vmRoleCtxt.VM); } #endregion #region AzureOSDisk public PersistentVM SetAzureOSDisk(HostCaching hc, PersistentVM vm) { SetAzureOSDiskCmdletInfo setAzureOSDiskCmdletInfo = new SetAzureOSDiskCmdletInfo(hc, vm); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureOSDiskCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } public OSVirtualHardDisk GetAzureOSDisk(PersistentVM vm) { GetAzureOSDiskCmdletInfo getAzureOSDiskCmdletInfo = new GetAzureOSDiskCmdletInfo(vm); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureOSDiskCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (OSVirtualHardDisk)result[0].BaseObject; } return null; } #endregion #region AzureRole public ManagementOperationContext SetAzureRole(string serviceName, string slot, string roleName, int count) { SetAzureRoleCmdletInfo setAzureRoleCmdletInfo = new SetAzureRoleCmdletInfo(serviceName, slot, roleName, count); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureRoleCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public Collection<RoleContext> GetAzureRole(string serviceName, string slot, string roleName, bool details) { GetAzureRoleCmdletInfo getAzureRoleCmdletInfo = new GetAzureRoleCmdletInfo(serviceName, slot, roleName, details); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureRoleCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<RoleContext> roles = new Collection<RoleContext>(); foreach (PSObject re in result) { roles.Add((RoleContext)re.BaseObject); } return roles; } #endregion #region AzureQuickVM public PersistentVMRoleContext NewAzureQuickVM(OS os, string name, string serviceName, string imageName, string password, string locationName) { NewAzureQuickVMCmdletInfo newAzureQuickVMCmdlet = new NewAzureQuickVMCmdletInfo(os, name, serviceName, imageName, password, locationName); WindowsAzurePowershellCmdletSequence sequence = new WindowsAzurePowershellCmdletSequence(); SubscriptionData currentSubscription; if ((currentSubscription = GetCurrentAzureSubscription()) == null) { ImportAzurePublishSettingsFile(); currentSubscription = GetCurrentAzureSubscription(); } if (string.IsNullOrEmpty(currentSubscription.CurrentStorageAccount)) { StorageServicePropertiesOperationContext storageAccount = NewAzureStorageAccount(Utilities.GetUniqueShortName("storage"), locationName); if (storageAccount != null) { SetAzureSubscription(currentSubscription.SubscriptionName, storageAccount.StorageAccountName); currentSubscription = GetCurrentAzureSubscription(); } } if (!string.IsNullOrEmpty(currentSubscription.CurrentStorageAccount)) { sequence.Add(newAzureQuickVMCmdlet); sequence.Run(); return GetAzureVM(name, serviceName); } return null; } public PersistentVMRoleContext NewAzureQuickLinuxVM(OS os, string name, string serviceName, string imageName, string userName, string password, string locationName) { NewAzureQuickVMCmdletInfo newAzureQuickVMLinuxCmdlet = new NewAzureQuickVMCmdletInfo(os, name, serviceName, imageName, userName, password, locationName); WindowsAzurePowershellCmdletSequence sequence = new WindowsAzurePowershellCmdletSequence(); SubscriptionData currentSubscription; if ((currentSubscription = GetCurrentAzureSubscription()) == null) { currentSubscription = GetCurrentAzureSubscription(); } if (string.IsNullOrEmpty(currentSubscription.CurrentStorageAccount)) { StorageServicePropertiesOperationContext storageAccount = NewAzureStorageAccount(Utilities.GetUniqueShortName("storage"), locationName); if (storageAccount != null) { SetAzureSubscription(currentSubscription.SubscriptionName, storageAccount.StorageAccountName); currentSubscription = GetCurrentAzureSubscription(); } } if (!string.IsNullOrEmpty(currentSubscription.CurrentStorageAccount)) { sequence.Add(newAzureQuickVMLinuxCmdlet); sequence.Run(); return GetAzureVM(name, serviceName); } return null; } #endregion #region AzurePublishSettingsFile public void ImportAzurePublishSettingsFile() { this.ImportAzurePublishSettingsFile(Utilities.publishSettingsFile); } internal void ImportAzurePublishSettingsFile(string publishSettingsFile) { ImportAzurePublishSettingsFileCmdletInfo importAzurePublishSettingsFileCmdlet = new ImportAzurePublishSettingsFileCmdletInfo(publishSettingsFile); WindowsAzurePowershellCmdlet importAzurePublishSettingsFile = new WindowsAzurePowershellCmdlet(importAzurePublishSettingsFileCmdlet); importAzurePublishSettingsFile.Run(); } #endregion #region AzureSubscription public Collection<SubscriptionData> GetAzureSubscription() { GetAzureSubscriptionCmdletInfo getAzureSubscriptionCmdlet = new GetAzureSubscriptionCmdletInfo(); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureSubscriptionCmdlet); Collection<SubscriptionData> subscriptions = new Collection<SubscriptionData>(); foreach (PSObject result in azurePowershellCmdlet.Run()) { subscriptions.Add((SubscriptionData)result.BaseObject); } return subscriptions; } public SubscriptionData GetCurrentAzureSubscription() { Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.IsDefault) { return subscription; } } return null; } public SubscriptionData SetAzureSubscription(string subscriptionName, string currentStorageAccount) { SetAzureSubscriptionCmdletInfo setAzureSubscriptionCmdlet = new SetAzureSubscriptionCmdletInfo(subscriptionName, currentStorageAccount); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureSubscriptionCmdlet); azurePowershellCmdlet.Run(); Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.SubscriptionName == subscriptionName) { return subscription; } } return null; } public SubscriptionData SetDefaultAzureSubscription(string subscriptionName) { SetAzureSubscriptionCmdletInfo setAzureSubscriptionCmdlet = new SetAzureSubscriptionCmdletInfo(subscriptionName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureSubscriptionCmdlet); azurePowershellCmdlet.Run(); Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.SubscriptionName == subscriptionName) { return subscription; } } return null; } #endregion #region AzureSubnet public SubnetNamesCollection GetAzureSubnet(PersistentVM vm) { GetAzureSubnetCmdletInfo getAzureSubnetCmdlet = new GetAzureSubnetCmdletInfo(vm); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureSubnetCmdlet); Collection <PSObject> result = azurePowershellCmdlet.Run(); SubnetNamesCollection subnets = new SubnetNamesCollection(); foreach (PSObject re in result) { subnets.Add((string)re.BaseObject); } return subnets; } public PersistentVM SetAzureSubnet(PersistentVM vm, string [] subnetNames) { SetAzureSubnetCmdletInfo setAzureSubnetCmdlet = new SetAzureSubnetCmdletInfo(vm, subnetNames); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureSubnetCmdlet); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } #endregion #region AzureStorageAccount public ManagementOperationContext NewAzureStorageAccount(string storageName, string locationName, string affinity, string label, string description) { NewAzureStorageAccountCmdletInfo newAzureStorageAccountCmdletInfo = new NewAzureStorageAccountCmdletInfo(storageName, locationName, affinity, label, description); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureStorageAccountCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public StorageServicePropertiesOperationContext NewAzureStorageAccount(string storageName, string locationName) { NewAzureStorageAccount(storageName, locationName, null, null, null); Collection<StorageServicePropertiesOperationContext> storageAccounts = GetAzureStorageAccount(null); foreach (StorageServicePropertiesOperationContext storageAccount in storageAccounts) { if (storageAccount.StorageAccountName == storageName) return storageAccount; } return null; } public Collection<StorageServicePropertiesOperationContext> GetAzureStorageAccount(string accountName) { GetAzureStorageAccountCmdletInfo getAzureStorageAccountCmdlet = new GetAzureStorageAccountCmdletInfo(accountName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureStorageAccountCmdlet); Collection<StorageServicePropertiesOperationContext> storageAccounts = new Collection<StorageServicePropertiesOperationContext>(); foreach (PSObject result in azurePowershellCmdlet.Run()) { storageAccounts.Add((StorageServicePropertiesOperationContext)result.BaseObject); } return storageAccounts; } public ManagementOperationContext SetAzureStorageAccount(string accountName, string label, string description, bool geoReplication) { SetAzureStorageAccountCmdletInfo setAzureStorageAccountCmdletInfo = new SetAzureStorageAccountCmdletInfo(accountName, label, description, geoReplication); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureStorageAccountCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public void RemoveAzureStorageAccount(string storageAccountName) { var removeAzureStorageAccountCmdletInfo = new RemoveAzureStorageAccountCmdletInfo(storageAccountName); var azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureStorageAccountCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); } #endregion #region AzureStorageKey public StorageServiceKeyOperationContext GetAzureStorageAccountKey(string stroageAccountName) { GetAzureStorageKeyCmdletInfo getAzureStorageKeyCmdletInfo = new GetAzureStorageKeyCmdletInfo(stroageAccountName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureStorageKeyCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (StorageServiceKeyOperationContext)result[0].BaseObject; } return null; } public StorageServiceKeyOperationContext NewAzureStorageAccountKey(string stroageAccountName, string keyType) { NewAzureStorageKeyCmdletInfo newAzureStorageKeyCmdletInfo = new NewAzureStorageKeyCmdletInfo(stroageAccountName, keyType); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureStorageKeyCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (StorageServiceKeyOperationContext)result[0].BaseObject; } return null; } #endregion #region AzureService public ManagementOperationContext NewAzureService(string serviceName, string location) { var newAzureServiceCmdletInfo = new NewAzureServiceCmdletInfo(serviceName, location); var newAzureServiceCmdlet = new WindowsAzurePowershellCmdlet(newAzureServiceCmdletInfo); var result = newAzureServiceCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } internal void NewAzureService(string serviceName, string serviceLabel, string locationName) { NewAzureServiceCmdletInfo newAzureServiceCmdletInfo = new NewAzureServiceCmdletInfo(serviceName, serviceLabel, locationName); WindowsAzurePowershellCmdlet newAzureServiceCmdlet = new WindowsAzurePowershellCmdlet(newAzureServiceCmdletInfo); Collection<PSObject> result = newAzureServiceCmdlet.Run(); } public void RemoveAzureService(string serviceName) { RemoveAzureServiceCmdletInfo removeAzureServiceCmdletInfo = new RemoveAzureServiceCmdletInfo(serviceName); WindowsAzurePowershellCmdlet removeAzureServiceCmdlet = new WindowsAzurePowershellCmdlet(removeAzureServiceCmdletInfo); var result = removeAzureServiceCmdlet.Run(); } public HostedServiceDetailedContext GetAzureService(string serviceName) { GetAzureServiceCmdletInfo getAzureServiceCmdletInfo = new GetAzureServiceCmdletInfo(serviceName); WindowsAzurePowershellCmdlet getAzureServiceCmdlet = new WindowsAzurePowershellCmdlet(getAzureServiceCmdletInfo); Collection<PSObject> result = getAzureServiceCmdlet.Run(); if (result.Count == 1) { return (HostedServiceDetailedContext)result[0].BaseObject; } return null; } #endregion #region AzureVM internal Collection<ManagementOperationContext> NewAzureVM(string serviceName, PersistentVM[] VMs) { return NewAzureVM(serviceName, VMs, null, null, null, null, null, null, null, null); } internal Collection<ManagementOperationContext> NewAzureVM(string serviceName, PersistentVM[] vms, string vnetName, DnsServer[] dnsSettings, string affinityGroup, string serviceLabel, string serviceDescription, string deploymentLabel, string deploymentDescription, string location) { NewAzureVMCmdletInfo newAzureVMCmdletInfo = new NewAzureVMCmdletInfo(serviceName, vms, vnetName, dnsSettings, affinityGroup, serviceLabel, serviceDescription, deploymentLabel, deploymentDescription, location); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureVMCmdletInfo); Collection<ManagementOperationContext> newAzureVMs = new Collection<ManagementOperationContext>(); foreach (PSObject result in azurePowershellCmdlet.Run()) { newAzureVMs.Add((ManagementOperationContext)result.BaseObject); } return newAzureVMs; } public PersistentVMRoleContext GetAzureVM(string vmName, string serviceName) { GetAzureVMCmdletInfo getAzureVMCmdletInfo = new GetAzureVMCmdletInfo(vmName, serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureVMCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVMRoleContext)result[0].BaseObject; } return null; } public void RemoveAzureVM(string vmName, string serviceName) { RemoveAzureVMCmdletInfo removeAzureVMCmdletInfo = new RemoveAzureVMCmdletInfo(vmName, serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureVMCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); } public void StartAzureVM(string vmName, string serviceName) { StartAzureVMCmdletInfo startAzureVMCmdlet = new StartAzureVMCmdletInfo(vmName, serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(startAzureVMCmdlet); azurePowershellCmdlet.Run(); } public void StopAzureVM(string vmName, string serviceName) { StopAzureVMCmdletInfo stopAzureVMCmdlet = new StopAzureVMCmdletInfo(vmName, serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(stopAzureVMCmdlet); azurePowershellCmdlet.Run(); } public void RestartAzureVM(string vmName, string serviceName) { RestartAzureVMCmdletInfo restartAzureVMCmdlet = new RestartAzureVMCmdletInfo(vmName, serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(restartAzureVMCmdlet); azurePowershellCmdlet.Run(); } public PersistentVMRoleContext ExportAzureVM(string vmName, string serviceName, string path) { //PersistentVMRoleContext result = new PersistentVMRoleContext ExportAzureVMCmdletInfo exportAzureVMCmdletInfo = new ExportAzureVMCmdletInfo(vmName, serviceName, path); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(exportAzureVMCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (PersistentVMRoleContext)result[0].BaseObject; } return null; } public Collection<PersistentVM> ImportAzureVM(string path) { Collection<PersistentVM> result = new Collection<PersistentVM>(); ImportAzureVMCmdletInfo importAzureVMCmdletInfo = new ImportAzureVMCmdletInfo(path); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(importAzureVMCmdletInfo); foreach (var vm in azurePowershellCmdlet.Run()) { result.Add((PersistentVM)vm.BaseObject); } return result; } private ManagementOperationContext UpdateAzureVM(string vmName, string serviceName, PersistentVM persistentVM) { UpdateAzureVMCmdletInfo updateAzureVMCmdletInfo = new UpdateAzureVMCmdletInfo(vmName, serviceName, persistentVM); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(updateAzureVMCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } #endregion #region AzureVMImage private OSImageContext OSImageContextRun(WindowsAzurePowershellCmdlet azurePSCmdlet) { Collection<PSObject> result = azurePSCmdlet.Run(); if (result.Count == 1) { return (OSImageContext)result[0].BaseObject; } return null; } public OSImageContext AddAzureVMImage(string imageName, string mediaLocation, OSType os, string label = null) { AddAzureVMImageCmdletInfo addAzureVMImageCmdlet = new AddAzureVMImageCmdletInfo(imageName, mediaLocation, os, label); return OSImageContextRun(new WindowsAzurePowershellCmdlet(addAzureVMImageCmdlet)); } public OSImageContext UpdateAzureVMImage(string imageName, string label) { UpdateAzureVMImageCmdletInfo updateAzureVMImageCmdlet = new UpdateAzureVMImageCmdletInfo(imageName, label); return OSImageContextRun(new WindowsAzurePowershellCmdlet(updateAzureVMImageCmdlet)); } public ManagementOperationContext RemoveAzureVMImage(string imageName, bool deleteVhd = false) { RemoveAzureVMImageCmdletInfo removeAzureVMImageCmdlet = new RemoveAzureVMImageCmdletInfo(imageName, deleteVhd); return ManagementOperationContextRun(new WindowsAzurePowershellCmdlet(removeAzureVMImageCmdlet)); } public void SaveAzureVMImage(string serviceName, string vmName, string newVmName, string newImageName = null) { SaveAzureVMImageCmdletInfo saveAzureVMImageCmdlet = new SaveAzureVMImageCmdletInfo(serviceName, vmName, newVmName, newImageName); ManagementOperationContextRun(new WindowsAzurePowershellCmdlet(saveAzureVMImageCmdlet)); } public Collection<OSImageContext> GetAzureVMImage(string imageName = null) { GetAzureVMImageCmdletInfo getAzureVMImageCmdlet = new GetAzureVMImageCmdletInfo(imageName); WindowsAzurePowershellCmdletSequence azurePowershellCmdlet = new WindowsAzurePowershellCmdletSequence(); azurePowershellCmdlet.Add(getAzureVMImageCmdlet); Collection<OSImageContext> osImageContext = new Collection<OSImageContext>(); foreach (PSObject result in azurePowershellCmdlet.Run()) { osImageContext.Add((OSImageContext)result.BaseObject); } return osImageContext; } public string GetAzureVMImageName(string[] keywords, bool exactMatch = true) { Collection<OSImageContext> vmImages = GetAzureVMImage(); foreach (OSImageContext image in vmImages) { if (Utilities.MatchKeywords(image.ImageName, keywords, exactMatch) >= 0) return image.ImageName; } return null; } #endregion #region AzureVhd public VhdUploadContext AddAzureVhd(AddAzureVhdCmdletInfo cmdletInfo) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(cmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (VhdUploadContext)result[0].BaseObject; } return null; } public string AddAzureVhdStop(AddAzureVhdCmdletInfo cmdletInfo, int ms) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(cmdletInfo); return azurePowershellCmdlet.RunAndStop(ms).ToString(); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination) { var addAzureVhdCmdletInfo = new AddAzureVhdCmdletInfo(destination, localFile.FullName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(addAzureVhdCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (VhdUploadContext)result[0].BaseObject; } return null; } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, int numberOfUploaderThreads, bool overWrite) { var addAzureVhdCmdletInfo = new AddAzureVhdCmdletInfo(destination, localFile.FullName, numberOfUploaderThreads, overWrite); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(addAzureVhdCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (VhdUploadContext)result[0].BaseObject; } return null; } public VhdDownloadContext SaveAzureVhd(Uri source, FileInfo localFilePath, int? numThreads, string storageKey, bool overwrite) { SaveAzureVhdCmdletInfo saveAzureVhdCmdletInfo = new SaveAzureVhdCmdletInfo(source, localFilePath, numThreads, storageKey, overwrite); return runSaveAzureVhd(saveAzureVhdCmdletInfo); } public string SaveAzureVhdStop(Uri source, FileInfo localFilePath, int? numThreads, string storageKey, bool overwrite, int ms) { SaveAzureVhdCmdletInfo saveAzureVhdCmdletInfo = new SaveAzureVhdCmdletInfo(source, localFilePath, numThreads, storageKey, overwrite); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(saveAzureVhdCmdletInfo); return azurePowershellCmdlet.RunAndStop(ms).ToString(); } private VhdDownloadContext runSaveAzureVhd(SaveAzureVhdCmdletInfo saveAzureVhdCmdletInfo) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(saveAzureVhdCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (VhdDownloadContext)result[0].BaseObject; } return null; } #endregion #region AzureVnetConfig public Collection<VirtualNetworkConfigContext> GetAzureVNetConfig(string filePath) { GetAzureVNetConfigCmdletInfo getAzureVNetConfigCmdletInfo = new GetAzureVNetConfigCmdletInfo(filePath); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureVNetConfigCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<VirtualNetworkConfigContext> vnetGateways = new Collection<VirtualNetworkConfigContext>(); foreach (PSObject re in result) { vnetGateways.Add((VirtualNetworkConfigContext)re.BaseObject); } return vnetGateways; } public ManagementOperationContext SetAzureVNetConfig(string filePath) { SetAzureVNetConfigCmdletInfo setAzureVNetConfigCmdletInfo = new SetAzureVNetConfigCmdletInfo(filePath); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureVNetConfigCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext) result[0].BaseObject; } return null; } public ManagementOperationContext RemoveAzureVNetConfig() { RemoveAzureVNetConfigCmdletInfo removeAzureVNetConfigCmdletInfo = new RemoveAzureVNetConfigCmdletInfo(); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureVNetConfigCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } #endregion #region AzureVNetGateway public ManagementOperationContext NewAzureVNetGateway(string vnetName) { NewAzureVNetGatewayCmdletInfo newAzureVNetGatewayCmdletInfo = new NewAzureVNetGatewayCmdletInfo(vnetName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureVNetGatewayCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public Collection <VirtualNetworkGatewayContext> GetAzureVNetGateway(string vnetName) { GetAzureVNetGatewayCmdletInfo getAzureVNetGatewayCmdletInfo = new GetAzureVNetGatewayCmdletInfo(vnetName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureVNetGatewayCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<VirtualNetworkGatewayContext> vnetGateways = new Collection<VirtualNetworkGatewayContext>(); foreach (PSObject re in result) { vnetGateways.Add ((VirtualNetworkGatewayContext) re.BaseObject); } return vnetGateways; } public ManagementOperationContext SetAzureVNetGateway(string option, string vnetName, string localNetwork) { SetAzureVNetGatewayCmdletInfo setAzureVNetGatewayCmdletInfo = new SetAzureVNetGatewayCmdletInfo(option, vnetName, localNetwork); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureVNetGatewayCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public ManagementOperationContext RemoveAzureVNetGateway(string vnetName) { GetAzureVNetGatewayKeyCmdletInfo a = new GetAzureVNetGatewayKeyCmdletInfo("aaa", "vvv"); RemoveAzureVNetGatewayCmdletInfo removeAzureVNetGatewayCmdletInfo = new RemoveAzureVNetGatewayCmdletInfo(vnetName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureVNetGatewayCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } public SharedKeyContext GetAzureVNetGatewayKey(string vnetName, string localnet) { GetAzureVNetGatewayKeyCmdletInfo getAzureVNetGatewayKeyCmdletInfo = new GetAzureVNetGatewayKeyCmdletInfo(vnetName, localnet); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureVNetGatewayKeyCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (SharedKeyContext) result[0].BaseObject; } return null; } #endregion #region AzureVNet public Collection<GatewayConnectionContext> GetAzureVNetConnection(string vnetName) { GetAzureVNetConnectionCmdletInfo getAzureVNetConnectionCmdletInfo = new GetAzureVNetConnectionCmdletInfo(vnetName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureVNetConnectionCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<GatewayConnectionContext> connections = new Collection<GatewayConnectionContext>(); foreach (PSObject re in result) { connections.Add((GatewayConnectionContext)re.BaseObject); } return connections; } public Collection<VirtualNetworkSiteContext> GetAzureVNetSite(string vnetName) { GetAzureVNetSiteCmdletInfo getAzureVNetSiteCmdletInfo = new GetAzureVNetSiteCmdletInfo(vnetName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureVNetSiteCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<VirtualNetworkSiteContext> connections = new Collection<VirtualNetworkSiteContext>(); foreach (PSObject re in result) { connections.Add((VirtualNetworkSiteContext)re.BaseObject); } return connections; } #endregion public void GetAzureRemoteDesktopFile(string vmName, string serviceName, string localPath, bool launch) { GetAzureRemoteDesktopFileCmdletInfo getAzureRemoteDesktopFileCmdletInfo = new GetAzureRemoteDesktopFileCmdletInfo(vmName, serviceName, localPath, launch); WindowsAzurePowershellCmdlet getAzureRemoteDesktopFileCmdlet = new WindowsAzurePowershellCmdlet(getAzureRemoteDesktopFileCmdletInfo); Collection<PSObject> result = getAzureRemoteDesktopFileCmdlet.Run(); } internal PersistentVM GetPersistentVM(PersistentVMConfigInfo configInfo) { PersistentVM vm = null; if (null != configInfo) { if (configInfo.VmConfig != null) { vm = NewAzureVMConfig(configInfo.VmConfig); } if (configInfo.ProvConfig != null) { configInfo.ProvConfig.Vm = vm; vm = AddAzureProvisioningConfig(configInfo.ProvConfig); } if (configInfo.DiskConfig != null) { configInfo.DiskConfig.Vm = vm; vm = AddAzureDataDisk(configInfo.DiskConfig); } if (configInfo.EndPointConfig != null) { configInfo.EndPointConfig.Vm = vm; vm = AddAzureEndPoint(configInfo.EndPointConfig); } } return vm; } internal void AddVMDataDisks(string vmName, string serviceName, AddAzureDataDiskConfig[] diskConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); foreach (AddAzureDataDiskConfig discCfg in diskConfig) { discCfg.Vm = vmRolectx.VM; vmRolectx.VM = AddAzureDataDisk(discCfg); } UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } internal void SetVMDataDisks(string vmName, string serviceName, SetAzureDataDiskConfig[] diskConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); foreach (SetAzureDataDiskConfig discCfg in diskConfig) { discCfg.Vm = vmRolectx.VM; vmRolectx.VM = SetAzureDataDisk(discCfg); } UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } internal void SetVMSize(string vmName, string serviceName, SetAzureVMSizeConfig vmSizeConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); vmSizeConfig.Vm = vmRolectx.VM; vmRolectx.VM = SetAzureVMSize(vmSizeConfig); UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } private PersistentVM SetAzureVMSize(SetAzureVMSizeConfig sizeCfg) { SetAzureVMSizeCmdletInfo setAzureVMSizeCmdletInfo = new SetAzureVMSizeCmdletInfo(sizeCfg); WindowsAzurePowershellCmdlet setAzureDataDiskCmdlet = new WindowsAzurePowershellCmdlet(setAzureVMSizeCmdletInfo); Collection<PSObject> result = setAzureDataDiskCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } internal void AddVMDataDisksAndEndPoint(string vmName, string serviceName, AddAzureDataDiskConfig[] dataDiskConfig, AzureEndPointConfigInfo endPointConfig) { AddVMDataDisks(vmName, serviceName, dataDiskConfig); AddEndPoint(vmName, serviceName, new [] {endPointConfig}); } private ManagementOperationContext ManagementOperationContextRun(WindowsAzurePowershellCmdlet azurePSCmdlet) { Collection<PSObject> result = azurePSCmdlet.Run(); if (result.Count == 1) { return (ManagementOperationContext)result[0].BaseObject; } return null; } private PersistentVM PersistentVMRun(WindowsAzurePowershellCmdlet azurePSCmdlet) { Collection<PSObject> result = azurePSCmdlet.Run(); if (result.Count == 1) { return (PersistentVM)result[0].BaseObject; } return null; } } }
// 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. namespace System.Runtime.Serialization { using System; using Microsoft.CodeDom; using System.Collections.Generic; using System.Security; using Microsoft.Xml; using Microsoft.Xml.Serialization; using Microsoft.Xml.Schema; public class XsdDataContractImporter { private ImportOptions _options; private CodeCompileUnit _codeCompileUnit; private DataContractSet _dataContractSet; private static readonly XmlQualifiedName[] s_emptyTypeNameArray = new XmlQualifiedName[0]; private static readonly XmlSchemaElement[] s_emptyElementArray = new XmlSchemaElement[0]; private XmlQualifiedName[] _singleTypeNameArray; private XmlSchemaElement[] _singleElementArray; public XsdDataContractImporter() { } public XsdDataContractImporter(CodeCompileUnit codeCompileUnit) { _codeCompileUnit = codeCompileUnit; } public ImportOptions Options { get { return _options; } set { _options = value; } } public CodeCompileUnit CodeCompileUnit { get { return GetCodeCompileUnit(); } } private CodeCompileUnit GetCodeCompileUnit() { if (_codeCompileUnit == null) _codeCompileUnit = new CodeCompileUnit(); return _codeCompileUnit; } private DataContractSet DataContractSet { get { if (_dataContractSet == null) { _dataContractSet = Options == null ? new DataContractSet(null, null, null) : new DataContractSet(Options.DataContractSurrogate, Options.ReferencedTypes, Options.ReferencedCollectionTypes); } return _dataContractSet; } } public void Import(XmlSchemaSet schemas) { if (schemas == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("schemas")); InternalImport(schemas, null, null, null); } public void Import(XmlSchemaSet schemas, ICollection<XmlQualifiedName> typeNames) { if (schemas == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("schemas")); if (typeNames == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("typeNames")); InternalImport(schemas, typeNames, s_emptyElementArray, s_emptyTypeNameArray); } public void Import(XmlSchemaSet schemas, XmlQualifiedName typeName) { if (schemas == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("schemas")); if (typeName == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("typeName")); SingleTypeNameArray[0] = typeName; InternalImport(schemas, SingleTypeNameArray, s_emptyElementArray, s_emptyTypeNameArray); } public XmlQualifiedName Import(XmlSchemaSet schemas, XmlSchemaElement element) { if (schemas == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("schemas")); if (element == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("element")); SingleTypeNameArray[0] = null; SingleElementArray[0] = element; InternalImport(schemas, s_emptyTypeNameArray, SingleElementArray, SingleTypeNameArray/*filled on return*/); return SingleTypeNameArray[0]; } public bool CanImport(XmlSchemaSet schemas) { if (schemas == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("schemas")); return InternalCanImport(schemas, null, null, null); } public bool CanImport(XmlSchemaSet schemas, ICollection<XmlQualifiedName> typeNames) { if (schemas == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("schemas")); if (typeNames == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("typeNames")); return InternalCanImport(schemas, typeNames, s_emptyElementArray, s_emptyTypeNameArray); } public bool CanImport(XmlSchemaSet schemas, XmlQualifiedName typeName) { if (schemas == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("schemas")); if (typeName == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("typeName")); return InternalCanImport(schemas, new XmlQualifiedName[] { typeName }, s_emptyElementArray, s_emptyTypeNameArray); } public bool CanImport(XmlSchemaSet schemas, XmlSchemaElement element) { if (schemas == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("schemas")); if (element == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("element")); SingleTypeNameArray[0] = null; SingleElementArray[0] = element; return InternalCanImport(schemas, s_emptyTypeNameArray, SingleElementArray, SingleTypeNameArray); } public CodeTypeReference GetCodeTypeReference(XmlQualifiedName typeName) { DataContract dataContract = FindDataContract(typeName); CodeExporter codeExporter = new CodeExporter(DataContractSet, Options, GetCodeCompileUnit()); return codeExporter.GetCodeTypeReference(dataContract); } public CodeTypeReference GetCodeTypeReference(XmlQualifiedName typeName, XmlSchemaElement element) { if (element == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("element")); if (typeName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("typeName")); DataContract dataContract = FindDataContract(typeName); CodeExporter codeExporter = new CodeExporter(DataContractSet, Options, GetCodeCompileUnit()); #pragma warning disable 56506 // Code Exporter will never be null return codeExporter.GetElementTypeReference(dataContract, element.IsNillable); } internal DataContract FindDataContract(XmlQualifiedName typeName) { if (typeName == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("typeName")); DataContract dataContract = DataContract.GetBuiltInDataContract(typeName.Name, typeName.Namespace); if (dataContract == null) { dataContract = DataContractSet[typeName]; if (dataContract == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRSerialization.TypeHasNotBeenImported, typeName.Name, typeName.Namespace))); } return dataContract; } public ICollection<CodeTypeReference> GetKnownTypeReferences(XmlQualifiedName typeName) { if (typeName == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("typeName")); DataContract dataContract = DataContract.GetBuiltInDataContract(typeName.Name, typeName.Namespace); if (dataContract == null) { dataContract = DataContractSet[typeName]; if (dataContract == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRSerialization.TypeHasNotBeenImported, typeName.Name, typeName.Namespace))); } CodeExporter codeExporter = new CodeExporter(DataContractSet, Options, GetCodeCompileUnit()); return codeExporter.GetKnownTypeReferences(dataContract); } private XmlQualifiedName[] SingleTypeNameArray { get { if (_singleTypeNameArray == null) _singleTypeNameArray = new XmlQualifiedName[1]; return _singleTypeNameArray; } } private XmlSchemaElement[] SingleElementArray { get { if (_singleElementArray == null) _singleElementArray = new XmlSchemaElement[1]; return _singleElementArray; } } private void InternalImport(XmlSchemaSet schemas, ICollection<XmlQualifiedName> typeNames, ICollection<XmlSchemaElement> elements, XmlQualifiedName[] elementTypeNames/*filled on return*/) { DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { SchemaImporter schemaImporter = new SchemaImporter(schemas, typeNames, elements, elementTypeNames/*filled on return*/, DataContractSet, ImportXmlDataType); schemaImporter.Import(); CodeExporter codeExporter = new CodeExporter(DataContractSet, Options, GetCodeCompileUnit()); codeExporter.Export(); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } _dataContractSet = oldValue; TraceImportError(ex); throw; } } private bool ImportXmlDataType { get { return this.Options == null ? false : this.Options.ImportXmlType; } } private void TraceImportError(Exception exception) { } private bool InternalCanImport(XmlSchemaSet schemas, ICollection<XmlQualifiedName> typeNames, ICollection<XmlSchemaElement> elements, XmlQualifiedName[] elementTypeNames) { DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { SchemaImporter schemaImporter = new SchemaImporter(schemas, typeNames, elements, elementTypeNames, DataContractSet, ImportXmlDataType); schemaImporter.Import(); return true; } catch (InvalidDataContractException) { _dataContractSet = oldValue; return false; } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } _dataContractSet = oldValue; TraceImportError(ex); throw; } } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Cloud.ClientTesting; using Google.Rpc; using Google.Type; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Xunit; namespace Google.Cloud.Vision.V1P2Beta1.Snippets { [SnippetOutputCollector] public class ImageAnnotatorClientSnippets { [Fact] public void Annotate() { Image image = LoadResourceImage("SchmidtBrinPage.jpg"); // Snippet: Annotate ImageAnnotatorClient client = ImageAnnotatorClient.Create(); AnnotateImageRequest request = new AnnotateImageRequest { Image = image, Features = { new Feature { Type = Feature.Types.Type.FaceDetection }, // By default, no limits are put on the number of results per annotation. // Use the MaxResults property to specify a limit. new Feature { Type = Feature.Types.Type.LandmarkDetection, MaxResults = 5 }, } }; AnnotateImageResponse response = client.Annotate(request); Console.WriteLine("Faces:"); foreach (FaceAnnotation face in response.FaceAnnotations) { Console.WriteLine($" Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {face.BoundingPoly}"); } Console.WriteLine("Landmarks:"); foreach (EntityAnnotation landmark in response.LandmarkAnnotations) { Console.WriteLine($"Score: {(int)(landmark.Score * 100)}%; Description: {landmark.Description}"); } if (response.Error != null) { Console.WriteLine($"Error detected: {response.Error}"); } // End snippet Assert.Equal(3, response.FaceAnnotations.Count); Assert.Equal(0, response.LandmarkAnnotations.Count); } [Fact] public void BatchAnnotateImages() { Image image1 = LoadResourceImage("SchmidtBrinPage.jpg"); Image image2 = LoadResourceImage("Chrome.png"); // Sample: BatchAnnotateImages // Additional: BatchAnnotateImages(IEnumerable<AnnotateImageRequest>,*) ImageAnnotatorClient client = ImageAnnotatorClient.Create(); // Perform face recognition on one image, and logo recognition on another. AnnotateImageRequest request1 = new AnnotateImageRequest { Image = image1, Features = { new Feature { Type = Feature.Types.Type.FaceDetection } } }; AnnotateImageRequest request2 = new AnnotateImageRequest { Image = image2, Features = { new Feature { Type = Feature.Types.Type.LogoDetection } } }; BatchAnnotateImagesResponse response = client.BatchAnnotateImages(new[] { request1, request2 }); Console.WriteLine("Faces in image 1:"); foreach (FaceAnnotation face in response.Responses[0].FaceAnnotations) { Console.WriteLine($" Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {face.BoundingPoly}"); } Console.WriteLine("Logos in image 2:"); foreach (EntityAnnotation logo in response.Responses[1].LogoAnnotations) { Console.WriteLine($"Description: {logo.Description}"); } foreach (Status error in response.Responses.Select(r => r.Error)) { Console.WriteLine($"Error detected: error"); } // End sample Assert.Equal(3, response.Responses[0].FaceAnnotations.Count); Assert.Equal(1, response.Responses[1].LogoAnnotations.Count); } [Fact] public void DetectFaces() { Image image = LoadResourceImage("SchmidtBrinPage.jpg"); // Snippet: DetectFaces ImageAnnotatorClient client = ImageAnnotatorClient.Create(); IReadOnlyList<FaceAnnotation> result = client.DetectFaces(image); foreach (FaceAnnotation face in result) { Console.WriteLine($"Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {face.BoundingPoly}"); } // End snippet Assert.Equal(3, result.Count); // Check the bounding boxes of the faces, with a tolerance of 5px on each edge. var rectangles = result.Select(x => Rectangle.FromBoundingPoly(x.BoundingPoly)).ToList(); Assert.True(rectangles.All(x => x != null)); rectangles = rectangles.OrderBy(r => r.Left).ToList(); Assert.True(rectangles[0].Equals(new Rectangle(196, 64, 293, 177), 5.0)); Assert.True(rectangles[1].Equals(new Rectangle(721, 162, 846, 308), 5.0)); Assert.True(rectangles[2].Equals(new Rectangle(1009, 113, 1149, 276), 5.0)); } [Fact] public void DetectLandmarks() { Image image = LoadResourceImage("SydneyOperaHouse.jpg"); // Snippet: DetectLandmarks ImageAnnotatorClient client = ImageAnnotatorClient.Create(); IReadOnlyList<EntityAnnotation> result = client.DetectLandmarks(image); foreach (EntityAnnotation landmark in result) { Console.WriteLine($"Score: {(int)(landmark.Score * 100)}%; Description: {landmark.Description}"); } // End snippet Assert.Equal(2, result.Count); var descriptions = result.Select(r => r.Description).OrderBy(d => d).ToList(); Assert.Equal(new[] { "Sydney Harbour Bridge", "Sydney Opera House" }, descriptions); } [Fact] public void DetectImageProperties() { Image image = LoadResourceImage("SchmidtBrinPage.jpg"); // Snippet: DetectImageProperties ImageAnnotatorClient client = ImageAnnotatorClient.Create(); ImageProperties properties = client.DetectImageProperties(image); ColorInfo dominantColor = properties.DominantColors.Colors.OrderByDescending(c => c.PixelFraction).First(); Console.WriteLine($"Dominant color in image: {dominantColor}"); // End snippet Assert.Equal(0.18, dominantColor.PixelFraction, 2); Assert.Equal(new Color { Red = 16, Green = 13, Blue = 8 }, dominantColor.Color); } [Fact] public void DetectLabels() { Image image = LoadResourceImage("Gladiolos.jpg"); // Snippet: DetectLabels ImageAnnotatorClient client = ImageAnnotatorClient.Create(); IReadOnlyList<EntityAnnotation> labels = client.DetectLabels(image); foreach (EntityAnnotation label in labels) { Console.WriteLine($"Score: {(int)(label.Score * 100)}%; Description: {label.Description}"); } // End snippet // Not exhaustive, but let's check certain basic labels. var descriptions = labels.Select(l => l.Description).ToList(); Assert.Contains("flower", descriptions); Assert.Contains("plant", descriptions); Assert.Contains("vase", descriptions); } [Fact] public void DetectText() { Image image = LoadResourceImage("Ellesborough.png"); // Snippet: DetectText ImageAnnotatorClient client = ImageAnnotatorClient.Create(); IReadOnlyList<EntityAnnotation> textAnnotations = client.DetectText(image); foreach (EntityAnnotation text in textAnnotations) { Console.WriteLine($"Description: {text.Description}"); } // End snippet var descriptions = textAnnotations.Select(t => t.Description).ToList(); Assert.Contains("Ellesborough", descriptions); } [Fact] public void DetectSafeSearch() { Image image = LoadResourceImage("SchmidtBrinPage.jpg"); // Snippet: DetectSafeSearch ImageAnnotatorClient client = ImageAnnotatorClient.Create(); SafeSearchAnnotation annotation = client.DetectSafeSearch(image); // Each category is classified as Very Unlikely, Unlikely, Possible, Likely or Very Likely. Console.WriteLine($"Adult? {annotation.Adult}"); Console.WriteLine($"Spoof? {annotation.Spoof}"); Console.WriteLine($"Violence? {annotation.Violence}"); Console.WriteLine($"Medical? {annotation.Medical}"); // End snippet Assert.InRange(annotation.Adult, Likelihood.VeryUnlikely, Likelihood.Unlikely); Assert.InRange(annotation.Spoof, Likelihood.VeryUnlikely, Likelihood.Unlikely); Assert.InRange(annotation.Violence, Likelihood.VeryUnlikely, Likelihood.Unlikely); Assert.InRange(annotation.Medical, Likelihood.VeryUnlikely, Likelihood.Unlikely); } [Fact] public void DetectLogos() { Image image = LoadResourceImage("Chrome.png"); // Snippet: DetectLogos ImageAnnotatorClient client = ImageAnnotatorClient.Create(); IReadOnlyList<EntityAnnotation> logos = client.DetectLogos(image); foreach (EntityAnnotation logo in logos) { Console.WriteLine($"Description: {logo.Description}"); } // End snippet Assert.Equal(1, logos.Count); Assert.Equal("Google Chrome", logos[0].Description); } [Fact] public void DetectCropHints() { Image image = LoadResourceImage("Gladiolos.jpg"); // Snippet: DetectCropHints ImageAnnotatorClient client = ImageAnnotatorClient.Create(); CropHintsAnnotation cropHints = client.DetectCropHints(image); foreach (CropHint hint in cropHints.CropHints) { Console.WriteLine("Crop hint:"); string poly = string.Join(" - ", hint.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})")); Console.WriteLine($" Poly: {poly}"); Console.WriteLine($" Confidence: {hint.Confidence}"); Console.WriteLine($" Importance fraction: {hint.ImportanceFraction}"); } // End snippet Assert.Equal(1, cropHints.CropHints.Count); } [Fact] public void DetectDocumentText() { Image image = LoadResourceImage("DocumentText.png"); // Snippet: DetectDocumentText ImageAnnotatorClient client = ImageAnnotatorClient.Create(); TextAnnotation text = client.DetectDocumentText(image); Console.WriteLine($"Text: {text.Text}"); foreach (var page in text.Pages) { foreach (var block in page.Blocks) { string box = string.Join(" - ", block.BoundingBox.Vertices.Select(v => $"({v.X}, {v.Y})")); Console.WriteLine($"Block {block.BlockType} at {box}"); foreach (var paragraph in block.Paragraphs) { box = string.Join(" - ", paragraph.BoundingBox.Vertices.Select(v => $"({v.X}, {v.Y})")); Console.WriteLine($" Paragraph at {box}"); foreach (var word in paragraph.Words) { Console.WriteLine($" Word: {string.Join("", word.Symbols.Select(s => s.Text))}"); } } } } // End snippet var lines = text.Pages[0].Blocks .Select(b => b.Paragraphs[0].Words.Select(w => string.Join("", w.Symbols.Select(s => s.Text)))) .ToList(); Assert.Equal(new[] { "Sample", "text", "line", "1", }, lines[0]); Assert.Equal(new[] { "Text", "near", "the", "middle", }, lines[1]); Assert.Equal(new[] { "Text", "near", "bottom", "right", }, lines[2]); } [Fact] public void DetectWebInformation() { Image image = LoadResourceImage("SchmidtBrinPage.jpg"); // Snippet: DetectWebInformation ImageAnnotatorClient client = ImageAnnotatorClient.Create(); WebDetection webDetection = client.DetectWebInformation(image); foreach (WebDetection.Types.WebImage webImage in webDetection.FullMatchingImages) { Console.WriteLine($"Full image: {webImage.Url} ({webImage.Score})"); } foreach (WebDetection.Types.WebImage webImage in webDetection.PartialMatchingImages) { Console.WriteLine($"Partial image: {webImage.Url} ({webImage.Score})"); } foreach (WebDetection.Types.WebPage webPage in webDetection.PagesWithMatchingImages) { Console.WriteLine($"Page with matching image: {webPage.Url} ({webPage.Score})"); } foreach (WebDetection.Types.WebEntity entity in webDetection.WebEntities) { Console.WriteLine($"Web entity: {entity.EntityId} / {entity.Description} ({entity.Score})"); } // End snippet } [Fact] public void ErrorHandling_SingleImage() { // Sample: ErrorHandling_SingleImage // We create a request which passes simple validation, but isn't a valid image. Image image = Image.FromBytes(new byte[10]); ImageAnnotatorClient client = ImageAnnotatorClient.Create(); try { IReadOnlyList<EntityAnnotation> logos = client.DetectLogos(image); // Normally use logos here... } catch (AnnotateImageException e) { AnnotateImageResponse response = e.Response; Console.WriteLine(response.Error); } // End sample } private static Image LoadResourceImage(string name) { var type = typeof(ImageAnnotatorClientSnippets); using (var stream = type.GetTypeInfo().Assembly.GetManifestResourceStream($"{type.Namespace}.{name}")) { return Image.FromStream(stream); } } } }
using System; using System.Collections; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using NUnit.Framework; using Spring.Util; namespace Spring.Collections { [TestFixture] public class PriorityQueueTests { protected static Int32 zero = Int32.Parse("0"); protected static Int32 one = Int32.Parse("1"); protected static Int32 two = Int32.Parse("2"); protected static Int32 three = Int32.Parse("3"); protected static Int32 four = Int32.Parse("4"); protected static Int32 five = Int32.Parse("5"); protected static Int32 six = Int32.Parse("6"); protected static Int32 seven = Int32.Parse("7"); protected static Int32 eight = Int32.Parse("8"); protected static Int32 nine = Int32.Parse("9"); protected static Int32 m1 = Int32.Parse("-1"); protected static Int32 m2 = Int32.Parse("-2"); protected static Int32 m3 = Int32.Parse("-3"); protected static Int32 m4 = Int32.Parse("-4"); protected static Int32 m5 = Int32.Parse("-5"); protected static Int32 m10 = Int32.Parse("-10"); private int SIZE = 20; internal class MyReverseComparator : IComparer { public virtual int Compare(Object x, Object y) { int i = (int)x; int j = (int)y; if (i < j) return 1; if (i > j) return - 1; return 0; } } private PriorityQueue populatedQueue(int n) { PriorityQueue q = new PriorityQueue(n); Assert.IsTrue((q.Count == 0)); for (int i = n - 1; i >= 0; i -= 2) Assert.IsTrue(q.Offer(i)); for (int i = (n & 1); i < n; i += 2) Assert.IsTrue(q.Offer(i)); Assert.IsFalse((q.Count == 0)); Assert.AreEqual(n, q.Count); return q; } [Test] public void CreateUnboundedQueue() { Assert.AreEqual(0, new PriorityQueue(SIZE).Count); } [Test] [ExpectedException(typeof (ArgumentException))] public void ThrowsArgumentExceptionForZeroCapacity() { new PriorityQueue(0); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void ThrowsArgumentNullExceptionForNullCollection() { PriorityQueue q = new PriorityQueue((ICollection) null); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ThrowsArgumentNullExceptionForNullCollectionElements() { object[] ints = new object[SIZE]; PriorityQueue q = new PriorityQueue(new ArrayList(ints)); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void ThrowsArgumentNullExceptionForSomeNullCollectionElements() { object[] ints = new object[SIZE]; for (int i = 0; i < SIZE - 1; ++i) ints[i] = i; PriorityQueue q = new PriorityQueue(new ArrayList(ints)); } [Test] public void ConstructorFromExistingCollection() { Int32[] ints = new Int32[SIZE]; for (int i = 0; i < SIZE; ++i) ints[i] = i; PriorityQueue q = new PriorityQueue(new ArrayList(ints)); for (int i = 0; i < SIZE; ++i) Assert.AreEqual(ints[i], q.Poll()); Assert.IsTrue( q.IsEmpty ); } [Test] public void ConstructorUsingComparator() { MyReverseComparator cmp = new MyReverseComparator(); PriorityQueue q = new PriorityQueue(SIZE, cmp); Assert.AreEqual(cmp, q.Comparator()); Int32[] ints = new Int32[SIZE]; for (int i = 0; i < SIZE; ++i) ints[i] = i; q.AddAll(new ArrayList(ints)); for (int i = SIZE - 1; i >= 0; --i) Assert.AreEqual(ints[i], q.Poll()); Assert.IsTrue( q.IsEmpty ); } [Test] public void IsEmpty() { PriorityQueue q = new PriorityQueue(2); Assert.IsTrue( q.IsEmpty ); q.Add(1); Assert.IsFalse( q.IsEmpty ); q.Add(2); q.Remove(); q.Remove(); Assert.IsTrue( q.IsEmpty ); } [Test] public void Size() { PriorityQueue q = populatedQueue(SIZE); for (int i = 0; i < SIZE; ++i) { Assert.AreEqual(SIZE - i, q.Count); q.Remove(); } for (int i = 0; i < SIZE; ++i) { Assert.AreEqual(i, q.Count); q.Add(i); } } [Test] [ExpectedException(typeof (ArgumentNullException))] public void OfferWithNullObject() { PriorityQueue q = new PriorityQueue(1); q.Offer(null); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void AddWithNullObject() { PriorityQueue q = new PriorityQueue(1); q.Add(null); } [Test] public void OfferWithComparableElements() { PriorityQueue q = new PriorityQueue(1); Assert.IsTrue(q.Offer(zero)); Assert.IsTrue(q.Offer(one)); } [Test] [ExpectedException(typeof (InvalidCastException))] public void OfferNonComparable() { PriorityQueue q = new PriorityQueue(1); q.Offer(new Object()); q.Offer(new Object()); q.Offer(new Object()); } [Test] public void AddWithComparableElements() { PriorityQueue q = new PriorityQueue(SIZE); for (int i = 0; i < SIZE; ++i) { Assert.AreEqual(i, q.Count); Assert.IsTrue(q.Add(i)); } } [Test] [ExpectedException(typeof (ArgumentNullException))] public void AddAllWithNullElements() { PriorityQueue q = new PriorityQueue(1); q.AddAll(null); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void AddAllWithCollectionWithNullElements() { PriorityQueue q = new PriorityQueue(SIZE); object[] ints = new object[SIZE]; q.AddAll(new ArrayList(ints)); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void AddAllWithCollectionWithSomeNullElements() { PriorityQueue q = new PriorityQueue(SIZE); object[] ints = new object[SIZE]; for (int i = 0; i < SIZE - 1; ++i) ints[i] = i; q.AddAll(new ArrayList(ints)); } [Test] public void AddAllWithCollection() { Int32[] empty = new Int32[0]; Int32[] ints = new Int32[SIZE]; for (int i = 0; i < SIZE; ++i) ints[i] = (SIZE - 1 - i); PriorityQueue q = new PriorityQueue(SIZE); Assert.IsFalse(q.AddAll(new ArrayList(empty))); Assert.IsTrue(q.AddAll(new ArrayList(ints))); for (int i = 0; i < SIZE; ++i) Assert.AreEqual(i, q.Poll()); } [Test] public void Poll() { PriorityQueue q = populatedQueue(SIZE); for (int i = 0; i < SIZE; ++i) { Assert.AreEqual(i, (q.Poll())); } Assert.IsNull(q.Poll()); } [Test] public void Peek() { PriorityQueue q = populatedQueue(SIZE); for (int i = 0; i < SIZE; ++i) { Assert.AreEqual(i, (q.Peek())); q.Poll(); Assert.IsTrue(q.Peek() == null || i != (int)(q.Peek())); } Assert.IsNull(q.Peek()); } [Test] [ExpectedException(typeof (NoElementsException))] public void Element() { PriorityQueue q = populatedQueue(SIZE); for (int i = 0; i < SIZE; ++i) { Assert.AreEqual(i, (q.Element())); q.Poll(); } q.Element(); } [Test] [ExpectedException(typeof (NoElementsException))] public void Remove() { PriorityQueue q = populatedQueue(SIZE); for (int i = 0; i < SIZE; ++i) { Assert.AreEqual(i, (q.Remove())); } q.Remove(); } [Test] public void RemoveElement() { PriorityQueue q = populatedQueue(SIZE); for (int i = 1; i < SIZE; i += 2) { Assert.IsTrue(q.Remove(i)); } for (int i = 0; i < SIZE; i += 2) { Assert.IsTrue(q.Remove(i)); Assert.IsFalse(q.Remove((i + 1))); } Assert.IsTrue((q.Count == 0)); } [Test] public void Contains() { PriorityQueue q = populatedQueue(SIZE); for (int i = 0; i < SIZE; ++i) { Assert.IsTrue(CollectionUtils.Contains(q, i)); q.Poll(); Assert.IsFalse(CollectionUtils.Contains(q, i)); } } [Test] public void Clear() { PriorityQueue q = populatedQueue(SIZE); q.Clear(); Assert.IsTrue((q.Count == 0)); Assert.AreEqual(0, q.Count); q.Add(1); Assert.IsFalse((q.Count == 0)); q.Clear(); Assert.IsTrue((q.Count == 0)); } [Test] public void ContainsAll() { PriorityQueue q = populatedQueue(SIZE); PriorityQueue p = new PriorityQueue(SIZE); for (int i = 0; i < SIZE; ++i) { Assert.IsTrue(CollectionUtils.ContainsAll(q, p)); Assert.IsFalse(CollectionUtils.ContainsAll(p, q)); p.Add(i); } Assert.IsTrue(CollectionUtils.ContainsAll(p, q)); } [Test] public void RemoveAll() { for (int i = 1; i < SIZE; ++i) { PriorityQueue q = populatedQueue(SIZE); PriorityQueue p = populatedQueue(i); CollectionUtils.RemoveAll(q, p); Assert.AreEqual(SIZE - i, q.Count); for (int j = 0; j < i; ++j) { Int32 I = (int) p.Remove(); Assert.IsFalse(CollectionUtils.Contains(q, I)); } } } [Test] public void ToArrayObject() { PriorityQueue q = populatedQueue(SIZE); Object[] o = (Object[]) CollectionUtils.ToArrayList(q).ToArray(typeof (object)); Array.Sort(o); for (int i = 0; i < o.Length; i++) Assert.AreEqual(o[i], q.Poll()); } [Test] public void ToArrayNonObject() { PriorityQueue q = populatedQueue(SIZE); Int32[] ints = (Int32[]) CollectionUtils.ToArrayList(q).ToArray(typeof (int)); Array.Sort(ints); for (int i = 0; i < ints.Length; i++) Assert.AreEqual(ints[i], q.Poll()); } [Test] public void Iterator() { PriorityQueue q = populatedQueue(SIZE); int i = 0; IEnumerator it = q.GetEnumerator(); while (it.MoveNext()) { Assert.IsTrue(CollectionUtils.Contains(q, it.Current)); ++i; } Assert.AreEqual(i, SIZE); } [Test] public void Serialization() { PriorityQueue q = populatedQueue(SIZE); MemoryStream bout = new MemoryStream(10000); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(bout, q); MemoryStream bin = new MemoryStream(bout.ToArray()); BinaryFormatter formatter2 = new BinaryFormatter(); PriorityQueue r = (PriorityQueue) formatter2.Deserialize(bin); Assert.AreEqual(q.Count, r.Count); while (!(q.Count == 0)) Assert.AreEqual(q.Remove(), r.Remove()); } [Test] [ExpectedException(typeof(ArgumentException))] public void QueueCopyToArrayWithSmallerDestinationArray() { PriorityQueue source = populatedQueue(SIZE); object[] dest = new object[SIZE/2]; source.CopyTo(dest); } [Test] [ExpectedException(typeof(ArgumentException))] public void QueueCopyToArrayWithIndexOutOfDestinationArrayRange() { PriorityQueue source = populatedQueue(SIZE); object[] dest = new object[SIZE/2]; source.CopyTo(dest, 11); } [Test] [ExpectedException(typeof(IndexOutOfRangeException))] public void QueueCopyToArrayWithValidSizeButInvalidStartingIndex() { PriorityQueue source = populatedQueue(SIZE); object[] dest = new object[SIZE]; source.CopyTo(dest, 10); } [Test] public void CompleteQueueCopyToArrayWithValidSize() { PriorityQueue source = populatedQueue(SIZE); object[] dest = new object[SIZE]; source.CopyTo(dest); for ( int i = 0; i < SIZE; i++ ) { Assert.AreEqual(source.Poll(), dest[i]); } } [Test] public void PartialQueueCopyToArrayWithValidSize() { PriorityQueue source = populatedQueue(SIZE); object[] dest = new object[SIZE*2]; source.CopyTo(dest, SIZE / 2); for ( int i = 0; i < SIZE; i++ ) { Assert.IsNull(dest[i]); } for ( int i = SIZE; i < SIZE / 2; i++ ) { Assert.AreEqual(dest[i], i - SIZE / 2 ); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading; using System.Threading.Tasks; using Dapper; namespace Dommel; public static partial class DommelMapper { /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static TReturn? Get<T1, T2, TReturn>(this IDbConnection connection, object id, Func<T1, T2, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class => MultiMap<T1, T2, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static async Task<TReturn?> GetAsync<T1, T2, TReturn>(this IDbConnection connection, object id, Func<T1, T2, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class => (await MultiMapAsync<T1, T2, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static TReturn? Get<T1, T2, T3, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, TReturn> map, IDbTransaction? transaction = null) where TReturn : class => MultiMap<T1, T2, T3, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static async Task<TReturn?> GetAsync<T1, T2, T3, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class => (await MultiMapAsync<T1, T2, T3, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static TReturn? Get<T1, T2, T3, T4, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, TReturn> map, IDbTransaction? transaction = null) where TReturn : class => MultiMap<T1, T2, T3, T4, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static async Task<TReturn?> GetAsync<T1, T2, T3, T4, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class => (await MultiMapAsync<T1, T2, T3, T4, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static TReturn? Get<T1, T2, T3, T4, T5, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, TReturn> map, IDbTransaction? transaction = null) where TReturn : class => MultiMap<T1, T2, T3, T4, T5, DontMap, DontMap, TReturn>(connection, map, id, transaction).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static async Task<TReturn?> GetAsync<T1, T2, T3, T4, T5, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class => (await MultiMapAsync<T1, T2, T3, T4, T5, DontMap, DontMap, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="T6">The sixth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static TReturn? Get<T1, T2, T3, T4, T5, T6, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, T6, TReturn> map, IDbTransaction? transaction = null) where TReturn : class => MultiMap<T1, T2, T3, T4, T5, T6, DontMap, TReturn>(connection, map, id, transaction).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="T6">The sixth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static async Task<TReturn?> GetAsync<T1, T2, T3, T4, T5, T6, TReturn>( this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, T6, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) => (await MultiMapAsync<T1, T2, T3, T4, T5, T6, DontMap, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="T6">The sixth type parameter.</typeparam> /// <typeparam name="T7">The seventh type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static TReturn? Get<T1, T2, T3, T4, T5, T6, T7, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, T6, T7, TReturn> map, IDbTransaction? transaction = null) where TReturn : class => MultiMap<T1, T2, T3, T4, T5, T6, T7, TReturn>(connection, map, id, transaction).FirstOrDefault(); /// <summary> /// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="T6">The sixth type parameter.</typeparam> /// <typeparam name="T7">The seventh type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="id">The id of the entity in the database.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns>The entity with the corresponding id joined with the specified types.</returns> public static async Task<TReturn?> GetAsync<T1, T2, T3, T4, T5, T6, T7, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, T6, T7, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class => (await MultiMapAsync<T1, T2, T3, T4, T5, T6, T7, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault(); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static IEnumerable<TReturn> GetAll<T1, T2, TReturn>( this IDbConnection connection, Func<T1, T2, TReturn> map, IDbTransaction? transaction = null, bool buffered = true) => MultiMap<T1, T2, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, TReturn>( this IDbConnection connection, Func<T1, T2, TReturn> map, IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static IEnumerable<TReturn> GetAll<T1, T2, T3, TReturn>( this IDbConnection connection, Func<T1, T2, T3, TReturn> map, IDbTransaction? transaction = null, bool buffered = true) => MultiMap<T1, T2, T3, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, T3, TReturn>( this IDbConnection connection, Func<T1, T2, T3, TReturn> map, IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, T3, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static IEnumerable<TReturn> GetAll<T1, T2, T3, T4, TReturn>( this IDbConnection connection, Func<T1, T2, T3, T4, TReturn> map, IDbTransaction? transaction = null, bool buffered = true) => MultiMap<T1, T2, T3, T4, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, T3, T4, TReturn>( this IDbConnection connection, Func<T1, T2, T3, T4, TReturn> map, IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, T3, T4, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static IEnumerable<TReturn> GetAll<T1, T2, T3, T4, T5, TReturn>( this IDbConnection connection, Func<T1, T2, T3, T4, T5, TReturn> map, IDbTransaction? transaction = null, bool buffered = true) => MultiMap<T1, T2, T3, T4, T5, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, T3, T4, T5, TReturn>( this IDbConnection connection, Func<T1, T2, T3, T4, T5, TReturn> map, IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, T3, T4, T5, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="T6">The sixth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static IEnumerable<TReturn> GetAll<T1, T2, T3, T4, T5, T6, TReturn>( this IDbConnection connection, Func<T1, T2, T3, T4, T5, T6, TReturn> map, IDbTransaction? transaction = null, bool buffered = true) => MultiMap<T1, T2, T3, T4, T5, T6, DontMap, TReturn>(connection, map, id: null, transaction, buffered); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="T6">The sixth type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, T3, T4, T5, T6, TReturn>( this IDbConnection connection, Func<T1, T2, T3, T4, T5, T6, TReturn> map, IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, T3, T4, T5, T6, DontMap, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="T6">The sixth type parameter.</typeparam> /// <typeparam name="T7">The seventh type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static IEnumerable<TReturn> GetAll<T1, T2, T3, T4, T5, T6, T7, TReturn>( this IDbConnection connection, Func<T1, T2, T3, T4, T5, T6, T7, TReturn> map, IDbTransaction? transaction = null, bool buffered = true) => MultiMap<T1, T2, T3, T4, T5, T6, T7, TReturn>(connection, map, id: null, transaction, buffered); /// <summary> /// Retrieves all the entities of type <typeparamref name="TReturn"/> /// joined with the types specified as type parameters. /// </summary> /// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The third type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="T6">The sixth type parameter.</typeparam> /// <typeparam name="T7">The seventh type parameter.</typeparam> /// <typeparam name="TReturn">The return type parameter.</typeparam> /// <param name="connection">The connection to the database. This can either be open or closed.</param> /// <param name="map">The mapping to perform on the entities in the result set.</param> /// <param name="transaction">Optional transaction for the command.</param> /// <param name="buffered"> /// A value indicating whether the result of the query should be executed directly, /// or when the query is materialized (using <c>ToList()</c> for example). /// </param> /// <param name="cancellationToken">Optional cancellation token for the command.</param> /// <returns> /// A collection of entities of type <typeparamref name="TReturn"/> /// joined with the specified type types. /// </returns> public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, T3, T4, T5, T6, T7, TReturn>( this IDbConnection connection, Func<T1, T2, T3, T4, T5, T6, T7, TReturn> map, IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, T3, T4, T5, T6, T7, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken); private static IEnumerable<TReturn> MultiMap<T1, T2, T3, T4, T5, T6, T7, TReturn>( IDbConnection connection, Delegate map, object? id, IDbTransaction? transaction = null, bool buffered = true, Func<DynamicParameters, string>? appendSql = null) { var resultType = typeof(TReturn); var includeTypes = new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) } .Where(t => t != typeof(DontMap)) .ToArray(); var sql = BuildMultiMapQuery(GetSqlBuilder(connection), resultType, includeTypes, id, out var parameters); if (appendSql != null) { parameters ??= new DynamicParameters(); sql += appendSql(parameters); } LogQuery<TReturn>(sql); var splitOn = CreateSplitOn(includeTypes); return includeTypes.Length switch { 2 => connection.Query(sql, (Func<T1, T2, TReturn>)map, parameters, transaction, buffered, splitOn), 3 => connection.Query(sql, (Func<T1, T2, T3, TReturn>)map, parameters, transaction, buffered, splitOn), 4 => connection.Query(sql, (Func<T1, T2, T3, T4, TReturn>)map, parameters, transaction, buffered, splitOn), 5 => connection.Query(sql, (Func<T1, T2, T3, T4, T5, TReturn>)map, parameters, transaction, buffered, splitOn), 6 => connection.Query(sql, (Func<T1, T2, T3, T4, T5, T6, TReturn>)map, parameters, transaction, buffered, splitOn), 7 => connection.Query(sql, (Func<T1, T2, T3, T4, T5, T6, T7, TReturn>)map, parameters, transaction, buffered, splitOn), _ => throw new InvalidOperationException($"Invalid amount of include types: {includeTypes.Length}."), }; } private static Task<IEnumerable<TReturn>> MultiMapAsync<T1, T2, T3, T4, T5, T6, T7, TReturn>( IDbConnection connection, Delegate map, object? id, IDbTransaction? transaction = null, bool buffered = true, Func<DynamicParameters, string>? appendSql = null, CancellationToken cancellationToken = default) { var resultType = typeof(TReturn); var includeTypes = new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) } .Where(t => t != typeof(DontMap)) .ToArray(); var sql = BuildMultiMapQuery(GetSqlBuilder(connection), resultType, includeTypes, id, out var parameters); if (appendSql != null) { parameters ??= new DynamicParameters(); sql += appendSql(parameters); } LogQuery<TReturn>(sql); var splitOn = CreateSplitOn(includeTypes); var commandDefinition = new CommandDefinition(sql, parameters, transaction, flags: buffered ? CommandFlags.Buffered : CommandFlags.None, cancellationToken: cancellationToken); return includeTypes.Length switch { 2 => connection.QueryAsync(commandDefinition, (Func<T1, T2, TReturn>)map, splitOn), 3 => connection.QueryAsync(commandDefinition, (Func<T1, T2, T3, TReturn>)map, splitOn), 4 => connection.QueryAsync(commandDefinition, (Func<T1, T2, T3, T4, TReturn>)map, splitOn), 5 => connection.QueryAsync(commandDefinition, (Func<T1, T2, T3, T4, T5, TReturn>)map, splitOn), 6 => connection.QueryAsync(commandDefinition, (Func<T1, T2, T3, T4, T5, T6, TReturn>)map, splitOn), 7 => connection.QueryAsync(commandDefinition, (Func<T1, T2, T3, T4, T5, T6, T7, TReturn>)map, splitOn), _ => throw new InvalidOperationException($"Invalid amount of include types: {includeTypes.Length}."), }; } internal static string CreateSplitOn(Type[] includeTypes) { // Create a splitOn parameter from the key properties of the included types // We use the column name resolver directly rather than via the Resolvers class // because Dapper needs an un-quoted column identifier. // E.g. FooId rather than [FooId] for SQL server, etc. return string.Join(",", includeTypes .Select(t => Resolvers.KeyProperties(t).First()) .Select(p => ColumnNameResolver.ResolveColumnName(p.Property))); } internal static string BuildMultiMapQuery(ISqlBuilder sqlBuilder, Type resultType, Type[] includeTypes, object? id, out DynamicParameters? parameters) { var resultTableName = Resolvers.Table(resultType, sqlBuilder); var resultTableKeyColumnName = Resolvers.Column(Resolvers.KeyProperties(resultType).Single().Property, sqlBuilder); var sql = $"select * from {resultTableName}"; // Determine the table to join with. var sourceType = includeTypes[0]; for (var i = 1; i < includeTypes.Length; i++) { // Determine the table name of the joined table. var includeType = includeTypes[i]; var foreignKeyTableName = Resolvers.Table(includeType, sqlBuilder); // Determine the foreign key and the relationship type. var foreignKeyProperty = Resolvers.ForeignKeyProperty(sourceType, includeType, out var relation); var foreignKeyPropertyName = Resolvers.Column(foreignKeyProperty, sqlBuilder); if (relation == ForeignKeyRelation.OneToOne) { // Determine the primary key of the foreign key table. var foreignKeyTableKeyColumName = Resolvers.Column(Resolvers.KeyProperties(includeType).Single().Property, sqlBuilder); sql += $" left join {foreignKeyTableName} on {foreignKeyPropertyName} = {foreignKeyTableKeyColumName}"; } else if (relation == ForeignKeyRelation.OneToMany) { // Determine the primary key of the source table. var sourceKeyColumnName = Resolvers.Column(Resolvers.KeyProperties(sourceType).Single().Property, sqlBuilder); sql += $" left join {foreignKeyTableName} on {sourceKeyColumnName} = {foreignKeyPropertyName}"; } } parameters = null; if (id != null) { sql += $" where {resultTableKeyColumnName} = {sqlBuilder.PrefixParameter("Id")}"; parameters = new DynamicParameters(); parameters.Add("Id", id); } return sql; } internal class DontMap { } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Azure; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Microsoft.AspNetCore.DataProtection.Repositories; #pragma warning disable AZC0001 // namespace Azure.Extensions.AspNetCore.DataProtection.Blobs #pragma warning restore { /// <summary> /// An <see cref="IXmlRepository"/> which is backed by Azure Blob Storage. /// </summary> /// <remarks> /// Instances of this type are thread-safe. /// </remarks> internal sealed class AzureBlobXmlRepository : IXmlRepository { private const int ConflictMaxRetries = 5; private static readonly TimeSpan ConflictBackoffPeriod = TimeSpan.FromMilliseconds(200); private static readonly XName RepositoryElementName = "repository"; private static BlobHttpHeaders _blobHttpHeaders = new BlobHttpHeaders() { ContentType = "application/xml; charset=utf-8" }; private readonly Random _random; private BlobData _cachedBlobData; private readonly BlobClient _blobClient; /// <summary> /// Creates a new instance of the <see cref="AzureBlobXmlRepository"/>. /// </summary> /// <param name="blobClient">A <see cref="BlobClient"/> that is connected to the blob we are reading from and writing to.</param> public AzureBlobXmlRepository(BlobClient blobClient) { _random = new Random(); _blobClient = blobClient; } /// <inheritdoc /> public IReadOnlyCollection<XElement> GetAllElements() { // Shunt the work onto a ThreadPool thread so that it's independent of any // existing sync context or other potentially deadlock-causing items. var elements = Task.Run(() => GetAllElementsAsync()).GetAwaiter().GetResult(); return new ReadOnlyCollection<XElement>(elements); } /// <inheritdoc /> public void StoreElement(XElement element, string friendlyName) { if (element == null) { throw new ArgumentNullException(nameof(element)); } // Shunt the work onto a ThreadPool thread so that it's independent of any // existing sync context or other potentially deadlock-causing items. Task.Run(() => StoreElementAsync(element)).GetAwaiter().GetResult(); } private static XDocument CreateDocumentFromBlob(byte[] blob) { using (var memoryStream = new MemoryStream(blob)) { var xmlReaderSettings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit, IgnoreProcessingInstructions = true }; using (var xmlReader = XmlReader.Create(memoryStream, xmlReaderSettings)) { return XDocument.Load(xmlReader); } } } private async Task<IList<XElement>> GetAllElementsAsync() { var data = await GetLatestDataAsync().ConfigureAwait(false); if (data == null || data.BlobContents.Length == 0) { // no data in blob storage return Array.Empty<XElement>(); } // The document will look like this: // // <root> // <child /> // <child /> // ... // </root> // // We want to return the first-level child elements to our caller. var doc = CreateDocumentFromBlob(data.BlobContents); return doc.Root.Elements().ToList(); } private async Task<BlobData> GetLatestDataAsync() { // Set the appropriate AccessCondition based on what we believe the latest // file contents to be, then make the request. var latestCachedData = Volatile.Read(ref _cachedBlobData); // local ref so field isn't mutated under our feet var requestCondition = (latestCachedData != null) ? new BlobRequestConditions() { IfNoneMatch = latestCachedData.ETag } : null; try { using (var memoryStream = new MemoryStream()) { var response = await _blobClient.DownloadToAsync( destination: memoryStream, conditions: requestCondition).ConfigureAwait(false); if (response.Status == 304) { // 304 Not Modified // Thrown when we already have the latest cached data. // This isn't an error; we'll return our cached copy of the data. return latestCachedData; } // At this point, our original cache either didn't exist or was outdated. // We'll update it now and return the updated value latestCachedData = new BlobData() { BlobContents = memoryStream.ToArray(), ETag = response.Headers.ETag }; } Volatile.Write(ref _cachedBlobData, latestCachedData); } catch (RequestFailedException ex) when (ex.Status == 404) { // 404 Not Found // Thrown when no file exists in storage. // This isn't an error; we'll delete our cached copy of data. latestCachedData = null; Volatile.Write(ref _cachedBlobData, latestCachedData); } return latestCachedData; } private int GetRandomizedBackoffPeriod() { // returns a TimeSpan in the range [0.8, 1.0) * ConflictBackoffPeriod // not used for crypto purposes var multiplier = 0.8 + (_random.NextDouble() * 0.2); return (int) (multiplier * ConflictBackoffPeriod.Ticks); } private async Task StoreElementAsync(XElement element) { // holds the last error in case we need to rethrow it ExceptionDispatchInfo lastError = null; for (var i = 0; i < ConflictMaxRetries; i++) { if (i > 1) { // If multiple conflicts occurred, wait a small period of time before retrying // the operation so that other writers can make forward progress. await Task.Delay(GetRandomizedBackoffPeriod()).ConfigureAwait(false); } if (i > 0) { // If at least one conflict occurred, make sure we have an up-to-date // view of the blob contents. await GetLatestDataAsync().ConfigureAwait(false); } // Merge the new element into the document. If no document exists, // create a new default document and inject this element into it. var latestData = Volatile.Read(ref _cachedBlobData); var doc = (latestData != null) ? CreateDocumentFromBlob(latestData.BlobContents) : new XDocument(new XElement(RepositoryElementName)); doc.Root.Add(element); // Turn this document back into a byte[]. var serializedDoc = new MemoryStream(); doc.Save(serializedDoc, SaveOptions.DisableFormatting); serializedDoc.Position = 0; // Generate the appropriate precondition header based on whether or not // we believe data already exists in storage. BlobRequestConditions requestConditions; if (latestData != null) { requestConditions = new BlobRequestConditions() { IfMatch = latestData.ETag }; } else { requestConditions = new BlobRequestConditions() { IfNoneMatch = ETag.All }; } try { // Send the request up to the server. var response = await _blobClient.UploadAsync( serializedDoc, httpHeaders: _blobHttpHeaders, conditions: requestConditions).ConfigureAwait(false); // If we got this far, success! // We can update the cached view of the remote contents. Volatile.Write(ref _cachedBlobData, new BlobData() { BlobContents = serializedDoc.ToArray(), ETag = response.Value.ETag // was updated by Upload routine }); return; } catch (RequestFailedException ex) when (ex.Status == 409 || ex.Status == 412) { // 409 Conflict // This error is rare but can be thrown in very special circumstances, // such as if the blob in the process of being created. We treat it // as equivalent to 412 for the purposes of retry logic. // 412 Precondition Failed // We'll get this error if another writer updated the repository and we // have an outdated view of its contents. If this occurs, we'll just // refresh our view of the remote contents and try again up to the max // retry limit. lastError = ExceptionDispatchInfo.Capture(ex); } } // if we got this far, something went awry lastError.Throw(); } private sealed class BlobData { internal byte[] BlobContents; internal ETag? ETag; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using NUnit.Framework; using ServiceStack.Common; using ServiceStack.Common.Utils; using ServiceStack.Markdown; using ServiceStack.WebHost.EndPoints.Formats; using ServiceStack.WebHost.EndPoints.Support.Markdown; namespace ServiceStack.ServiceHost.Tests.Formats { [TestFixture] public class TemplateTests { string staticTemplatePath; string staticTemplateContent; string dynamicPagePath; string dynamicPageContent; string dynamicListPagePath; string dynamicListPageContent; private MarkdownFormat markdownFormat; Dictionary<string, object> templateArgs; [TestFixtureSetUp] public void TestFixtureSetUp() { staticTemplatePath = "~/Views/Template/default.shtml".MapProjectPath(); staticTemplateContent = File.ReadAllText(staticTemplatePath); dynamicPagePath = "~/Views/Template/DynamicTpl.md".MapProjectPath(); dynamicPageContent = File.ReadAllText(dynamicPagePath); dynamicListPagePath = "~/Views/Template/DynamicListTpl.md".MapProjectPath(); dynamicListPageContent = File.ReadAllText(dynamicListPagePath); } [SetUp] public void OnBeforeEachTest() { markdownFormat = new MarkdownFormat(); templateArgs = new Dictionary<string, object> { { MarkdownPage.ModelName, person } }; } [Test] public void Can_Render_MarkdownTemplate() { var template = new MarkdownTemplate(staticTemplatePath, "default", staticTemplateContent); template.Prepare(); Assert.That(template.TextBlocks.Length, Is.EqualTo(2)); const string mockResponse = "[Replaced with Template]"; var expectedHtml = staticTemplateContent.ReplaceFirst(MarkdownFormat.TemplatePlaceHolder, mockResponse); var mockArgs = new Dictionary<string, object> { { MarkdownTemplate.BodyPlaceHolder, mockResponse } }; var templateOutput = template.RenderToString(mockArgs); Console.WriteLine("Template Output: " + templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } public class Person { public string FirstName { get; set; } public string LastName { get; set; } public List<Link> Links { get; set; } } public class Link { public Link() { this.Labels = new List<string>(); } public string Name { get; set; } public string Href { get; set; } public List<string> Labels { get; set; } } Person person = new Person { FirstName = "Demis", LastName = "Bellot", Links = new List<Link> { new Link { Name = "ServiceStack", Href = "http://www.servicestack.net", Labels = {"REST","JSON","XML"} }, new Link { Name = "AjaxStack", Href = "http://www.ajaxstack.com", Labels = {"HTML5", "AJAX", "SPA"} }, }, }; [Test] public void Can_Render_MarkdownPage() { var dynamicPage = new MarkdownPage(markdownFormat, dynamicPageContent, "DynamicTpl", dynamicPageContent); dynamicPage.Prepare(); Assert.That(dynamicPage.HtmlBlocks.Length, Is.EqualTo(9)); var expectedHtml = markdownFormat.Transform(dynamicPageContent) .Replace("@Model.FirstName", person.FirstName) .Replace("@Model.LastName", person.LastName); var templateOutput = dynamicPage.RenderToHtml(templateArgs); Console.WriteLine("Template Output: " + templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_MarkdownPage_with_foreach() { var dynamicPage = new MarkdownPage(markdownFormat, dynamicListPagePath, "DynamicListTpl", dynamicListPageContent); dynamicPage.Prepare(); Assert.That(dynamicPage.HtmlBlocks.Length, Is.EqualTo(11)); var expectedMarkdown = dynamicListPageContent .Replace("@Model.FirstName", person.FirstName) .Replace("@Model.LastName", person.LastName); var foreachLinks = " - ServiceStack - http://www.servicestack.net\r\n" + " - AjaxStack - http://www.ajaxstack.com\r\n"; expectedMarkdown = expectedMarkdown.ReplaceForeach(foreachLinks); var expectedHtml = markdownFormat.Transform(expectedMarkdown); Console.WriteLine("ExpectedHtml: " + expectedHtml); var templateOutput = dynamicPage.RenderToHtml(templateArgs); Console.WriteLine("Template Output: " + templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_MarkdownPage_with_IF_statement() { var template = @"# Dynamic If Markdown Template Hello @Model.FirstName, @if (Model.FirstName == ""Bellot"") { * @Model.FirstName } @if (Model.LastName == ""Bellot"") { * @Model.LastName } ### heading 3"; var expected = @"# Dynamic If Markdown Template Hello Demis, * Bellot ### heading 3"; var expectedHtml = markdownFormat.Transform(expected); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicIfTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToHtml(templateArgs); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_Markdown_with_Nested_Statements() { var template = @"# @Model.FirstName Dynamic Nested Markdown Template # heading 1 @foreach (var link in Model.Links) { @if (link.Name == ""AjaxStack"") { - @link.Name - @link.Href } } @if (Model.Links.Count == 2) { ## Haz 2 links @foreach (var link in Model.Links) { - @link.Name - @link.Href @foreach (var label in link.Labels) { - @label } } } ### heading 3"; var expected = @"# Demis Dynamic Nested Markdown Template # heading 1 - AjaxStack - http://www.ajaxstack.com ## Haz 2 links - ServiceStack - http://www.servicestack.net - REST - JSON - XML - AjaxStack - http://www.ajaxstack.com - HTML5 - AJAX - SPA ### heading 3"; var expectedHtml = markdownFormat.Transform(expected); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicNestedTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToHtml(templateArgs); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } public class CustomMarkdownViewBase<T> : MarkdownViewBase<T> { public MvcHtmlString Table(Person model) { return new CustomMarkdownViewBase().Table(model); } } public class CustomMarkdownViewBase : MarkdownViewBase { public MvcHtmlString Table(Person model) { var sb = new StringBuilder(); sb.AppendFormat("<table><caption>{0}'s Links</caption>", model.FirstName); sb.AppendLine("<thead><tr><th>Name</th><th>Link</th></tr></thead>"); sb.AppendLine("<tbody>"); foreach (var link in model.Links) { sb.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", link.Name, link.Href); } sb.AppendLine("</tbody>"); sb.AppendLine("</table>"); return MvcHtmlString.Create(sb.ToString()); } private static string[] MenuItems = new[] { "About Us", "Blog", "Links", "Contact" }; public void Menu(string selectedId) { var sb = new StringBuilder(); sb.Append("<ul>\n"); foreach (var menuItem in MenuItems) { var cls = menuItem == selectedId ? " class='selected'" : ""; sb.AppendFormat("<li><a href='{0}'{1}>{0}</a></li>\n", menuItem, cls); } sb.Append("</ul>\n"); ScopeArgs.Add("Menu", MvcHtmlString.Create(sb.ToString())); } } public class CustomMarkdownHelper { public static CustomMarkdownHelper Instance = new CustomMarkdownHelper(); public MvcHtmlString InlineBlock(string content, string id) { return MvcHtmlString.Create( "<div id=\"" + id + "\"><div class=\"inner inline-block\">" + content + "</div></div>"); } } [Test] public void Can_Render_Markdown_with_StaticMethods() { var headerTemplate = @"## Header Links! - [Google](http://google.com) - [Bing](http://bing.com)"; var template = @"## Welcome to Razor! @Html.Partial(""HeaderLinks"", Model) Hello @Upper(Model.LastName), @Model.FirstName ### Breadcrumbs @Combine("" / "", Model.FirstName, Model.LastName) ### Menus @foreach (var link in Model.Links) { - @link.Name - @link.Href @foreach (var label in link.Labels) { - @label } } ### HTML Table @Table(Model) "; var expectedHtml = @"<h2>Welcome to Razor!</h2> <h2>Header Links!</h2> <ul> <li><a href=""http://google.com"">Google</a></li> <li><a href=""http://bing.com"">Bing</a></li> </ul> <p>Hello BELLOT, Demis</p> <h3>Breadcrumbs</h3> Demis / Bellot <h3>Menus</h3> <ul> <li>ServiceStack - http://www.servicestack.net <ul> <li>REST</li> <li>JSON</li> <li>XML</li> </ul></li> <li>AjaxStack - http://www.ajaxstack.com <ul> <li>HTML5</li> <li>AJAX</li> <li>SPA</li> </ul></li> </ul> <h3>HTML Table</h3> <table><caption>Demis's Links</caption><thead><tr><th>Name</th><th>Link</th></tr></thead> <tbody> <tr><td>ServiceStack</td><td>http://www.servicestack.net</td></tr><tr><td>AjaxStack</td><td>http://www.ajaxstack.com</td></tr></tbody> </table> ".Replace("\r\n", "\n"); markdownFormat.MarkdownBaseType = typeof(CustomMarkdownViewBase); markdownFormat.MarkdownGlobalHelpers = new Dictionary<string, Type> { {"Ext", typeof(CustomMarkdownHelper)} }; markdownFormat.RegisterMarkdownPage(new MarkdownPage(markdownFormat, "/path/to/page", "HeaderLinks", headerTemplate)); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicIfTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToHtml(templateArgs); templateOutput = templateOutput.Replace("\r\n", "\n"); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_inherit_from_Generic_view_page_from_model_directive() { var template = @"@model ServiceStack.ServiceHost.Tests.Formats.TemplateTests+Person # Generic View Page ## Form fields @Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName) "; var expectedHtml = @" <h1>Generic View Page</h1> <h2>Form fields</h2> <label for=""FirstName"">FirstName</label> <input name=""FirstName"" type=""text"" value=""Demis"" />".Replace("\r\n", "\n"); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToHtml(templateArgs); templateOutput = templateOutput.Replace("\r\n", "\n"); Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase<>))); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_inherit_from_CustomViewPage_using_inherits_directive() { var template = @"@inherits ServiceStack.ServiceHost.Tests.Formats.TemplateTests+CustomMarkdownViewBase<ServiceStack.ServiceHost.Tests.Formats.TemplateTests+Person> # Generic View Page ## Form fields @Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName) ## Person Table @Table(Model) "; var expectedHtml = @" <h1>Generic View Page</h1> <h2>Form fields</h2> <label for=""FirstName"">FirstName</label> <input name=""FirstName"" type=""text"" value=""Demis"" /> <h2>Person Table</h2> <table><caption>Demis's Links</caption><thead><tr><th>Name</th><th>Link</th></tr></thead> <tbody> <tr><td>ServiceStack</td><td>http://www.servicestack.net</td></tr><tr><td>AjaxStack</td><td>http://www.ajaxstack.com</td></tr></tbody> </table> ".Replace("\r\n", "\n"); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToHtml(templateArgs); templateOutput = templateOutput.Replace("\r\n", "\n"); Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(CustomMarkdownViewBase<>))); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_MarkdownPage_with_external_helper() { var template = @"# View Page with Custom Helper ## External Helper <img src='path/to/img' class='inline-block' /> @Ext.InlineBlock(Model.FirstName, ""first-name"") "; var expectedHtml = @"<h1>View Page with Custom Helper</h1> <h2>External Helper</h2> <p><img src='path/to/img' class='inline-block' /> <div id=""first-name""><div class=""inner inline-block"">Demis</div></div>".Replace("\r\n", "\n"); markdownFormat.MarkdownGlobalHelpers.Add("Ext", typeof(CustomMarkdownHelper)); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToHtml(templateArgs); templateOutput = templateOutput.Replace("\r\n", "\n"); Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase))); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_MarkdownPage_with_external_helper_using_helper_directive() { var template = @"@helper Ext: ServiceStack.ServiceHost.Tests.Formats.TemplateTests+CustomMarkdownHelper # View Page with Custom Helper ## External Helper <img src='path/to/img' class='inline-block' /> @Ext.InlineBlock(Model.FirstName, ""first-name"") "; var expectedHtml = @" <h1>View Page with Custom Helper</h1> <h2>External Helper</h2> <p><img src='path/to/img' class='inline-block' /> <div id=""first-name""><div class=""inner inline-block"">Demis</div></div>".Replace("\r\n", "\n"); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToHtml(templateArgs); templateOutput = templateOutput.Replace("\r\n", "\n"); Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase))); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_page_to_Markdown_only() { var headerTemplate = @"## Header Links! - [Google](http://google.com) - [Bing](http://bing.com) "; var template = @"## Welcome to Razor! @Html.Partial(""HeaderLinks"", Model) Hello @Upper(Model.LastName), @Model.FirstName ### Breadcrumbs @Combine("" / "", Model.FirstName, Model.LastName) ### Menus @foreach (var link in Model.Links) { - @link.Name - @link.Href @foreach (var label in link.Labels) { - @label } }"; var expectedHtml = @"## Welcome to Razor! ## Header Links! - [Google](http://google.com) - [Bing](http://bing.com) Hello BELLOT, Demis ### Breadcrumbs Demis / Bellot ### Menus - ServiceStack - http://www.servicestack.net - REST - JSON - XML - AjaxStack - http://www.ajaxstack.com - HTML5 - AJAX - SPA ".Replace("\r\n", "\n"); markdownFormat.RegisterMarkdownPage(new MarkdownPage(markdownFormat, "/path/to/page", "HeaderLinks", headerTemplate)); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToMarkdown(templateArgs); templateOutput = templateOutput.Replace("\r\n", "\n"); Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase))); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_Markdown_with_variable_statements() { var template = @"## Welcome to Razor! @var lastName = Model.LastName; Hello @Upper(lastName), @Model.FirstName ### Breadcrumbs @Combine("" / "", Model.FirstName, lastName) @var links = Model.Links ### Menus @foreach (var link in links) { - @link.Name - @link.Href @var labels = link.Labels @foreach (var label in labels) { - @label } }"; var expectedHtml = @"## Welcome to Razor! Hello BELLOT, Demis ### Breadcrumbs Demis / Bellot ### Menus - ServiceStack - http://www.servicestack.net - REST - JSON - XML - AjaxStack - http://www.ajaxstack.com - HTML5 - AJAX - SPA ".Replace("\r\n", "\n"); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToMarkdown(templateArgs); templateOutput = templateOutput.Replace("\r\n", "\n"); Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase))); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_MarkdownPage_with_comments() { var template = @"# Dynamic If Markdown Template Hello @Model.FirstName, @if (Model.FirstName == ""Bellot"") { * @Model.FirstName } @* @if (Model.LastName == ""Bellot"") { * @Model.LastName } *@ @* Plain text in a comment *@ ### heading 3"; var expectedHtml = @"<h1>Dynamic If Markdown Template</h1> <p>Hello Demis,</p> <h3>heading 3</h3> ".Replace("\r\n", "\n"); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicIfTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToHtml(templateArgs); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_MarkdownPage_with_unmatching_escaped_braces() { var template = @"# Dynamic If Markdown Template Hello @Model.FirstName, { -- unmatched, leave unescaped outside statement { -- inside matching braces, outside statement -- } @if (Model.LastName == ""Bellot"") { * @Model.LastName {{ -- inside matching braces, escape inside statement -- }} {{ -- unmatched } ### heading 3"; var expectedHtml = @"<h1>Dynamic If Markdown Template</h1> <p>Hello Demis, { -- unmatched, leave unescaped outside statement</p> <p>{ -- inside matching braces, outside statement -- }</p> <ul> <li>Bellot</li> </ul> <p>{ -- inside matching braces, escape inside statement -- }</p> <p>{ -- unmatched</p> <h3>heading 3</h3> ".Replace("\r\n", "\n"); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicIfTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToHtml(templateArgs); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_capture_Section_statements_and_store_them_in_scopeargs() { var template = @"## Welcome to Razor! @var lastName = Model.LastName; @section Salutations { Hello @Upper(lastName), @Model.FirstName } @section Breadcrumbs { ### Breadcrumbs @Combine("" / "", Model.FirstName, lastName) } @var links = Model.Links @section Menus { ### Menus @foreach (var link in links) { - @link.Name - @link.Href @var labels = link.Labels @foreach (var label in labels) { - @label } } } ## Captured Sections <div id='breadcrumbs'>@Breadcrumbs</div> @Menus ## Salutations @Salutations "; var expectedHtml = @"<h2>Welcome to Razor!</h2> <h2>Captured Sections</h2> <div id='breadcrumbs'><h3>Breadcrumbs</h3> <p>Demis / Bellot</p> </div> <p><h3>Menus</h3> <ul> <li>ServiceStack - http://www.servicestack.net <ul> <li>REST</li> <li>JSON</li> <li>XML</li> </ul></li> <li>AjaxStack - http://www.ajaxstack.com <ul> <li>HTML5</li> <li>AJAX</li> <li>SPA</li> </ul></li> </ul> </p> <h2>Salutations</h2> <p><p>Hello BELLOT, Demis</p> </p> ".Replace("\r\n", "\n"); var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template); dynamicPage.Prepare(); var templateOutput = dynamicPage.RenderToHtml(templateArgs); templateOutput = templateOutput.Replace("\r\n", "\n"); Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase))); Console.WriteLine(templateOutput); Assert.That(templateArgs["Salutations"].ToString(), Is.EqualTo("<p>Hello BELLOT, Demis</p>\n")); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_Template_with_section_and_variable_placeholders() { var template = @"## Welcome to Razor! @var lastName = Model.LastName; Hello @Upper(lastName), @Model.FirstName, @section Breadcrumbs { ### Breadcrumbs @Combine("" / "", Model.FirstName, lastName) } @section Menus { ### Menus @foreach (var link in Model.Links) { - @link.Name - @link.Href @var labels = link.Labels @foreach (var label in labels) { - @label } } }"; var websiteTemplate = @"<!doctype html> <html lang=""en-us""> <head> <title><!--@lastName--> page</title> </head> <body> <header> <!--@Menus--> </header> <h1>Website Template</h1> <div id=""content""><!--@Body--></div> <footer> <!--@Breadcrumbs--> </footer> </body> </html>"; var expectedHtml = @"<!doctype html> <html lang=""en-us""> <head> <title>Bellot page</title> </head> <body> <header> <h3>Menus</h3> <ul> <li>ServiceStack - http://www.servicestack.net <ul> <li>REST</li> <li>JSON</li> <li>XML</li> </ul></li> <li>AjaxStack - http://www.ajaxstack.com <ul> <li>HTML5</li> <li>AJAX</li> <li>SPA</li> </ul></li> </ul> </header> <h1>Website Template</h1> <div id=""content""><h2>Welcome to Razor!</h2> <p>Hello BELLOT, Demis,</p> </div> <footer> <h3>Breadcrumbs</h3> <p>Demis / Bellot</p> </footer> </body> </html>".Replace("\r\n", "\n"); markdownFormat.AddTemplate("/path/to/tpl", websiteTemplate); markdownFormat.AddPage( new MarkdownPage(markdownFormat, "/path/to/page-tpl", "DynamicModelTpl", template) { TemplatePath = "/path/to/tpl" }); var templateOutput = markdownFormat.RenderDynamicPageHtml("DynamicModelTpl", person); templateOutput = templateOutput.Replace("\r\n", "\n"); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } [Test] public void Can_Render_Static_ContentPage_that_populates_variable_and_displayed_on_website_template() { var websiteTemplate = @"<!doctype html> <html lang=""en-us""> <head> <title>Static page</title> </head> <body> <header> <!--@Header--> </header> <div id='menus'> <!--@Menu--> </div> <h1>Website Template</h1> <div id=""content""><!--@Body--></div> </body> </html>".NormalizeNewLines(); var template = @"# Static Markdown Template @Menu(""Links"") @section Header { ### Static Page Title } ### heading 3 paragraph"; var expectedHtml = @"<!doctype html> <html lang=""en-us""> <head> <title>Static page</title> </head> <body> <header> <h3>Static Page Title</h3> </header> <div id='menus'> <ul> <li><a href='About Us'>About Us</a></li> <li><a href='Blog'>Blog</a></li> <li><a href='Links' class='selected'>Links</a></li> <li><a href='Contact'>Contact</a></li> </ul> </div> <h1>Website Template</h1> <div id=""content""><h1>Static Markdown Template</h1> <h3>heading 3</h3> <p>paragraph</p> </div> </body> </html>".NormalizeNewLines(); markdownFormat.MarkdownBaseType = typeof(CustomMarkdownViewBase); markdownFormat.AddTemplate("/path/to/tpl", websiteTemplate); markdownFormat.RegisterMarkdownPage( new MarkdownPage(markdownFormat, "/path/to/pagetpl", "StaticTpl", template, MarkdownPageType.ContentPage) { TemplatePath = "/path/to/tpl" }); var templateOutput = markdownFormat.RenderStaticPage("/path/to/pagetpl", true); Console.WriteLine(templateOutput); Assert.That(templateOutput, Is.EqualTo(expectedHtml)); } } }
// Copyright 2021 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using System; using System.Drawing; namespace ArcGISRuntime.WinUI.Samples.AddGraphicsRenderer { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Add graphics with renderer", category: "GraphicsOverlay", description: "A renderer allows you to change the style of all graphics in a graphics overlay by referencing a single symbol style. A renderer will only affect graphics that do not specify their own symbol style.", instructions: "Pan and zoom on the map to view graphics for points, lines, and polygons (including polygons with curve segments) which are stylized using renderers.", tags: new[] { "arc", "bezier", "curve", "display", "ellipse", "graphics", "marker", "overlay", "renderer", "segment", "symbol", "true curve", "Featured" })] public sealed partial class AddGraphicsRenderer { public AddGraphicsRenderer() { InitializeComponent(); Initialize(); } private void Initialize() { // Create a map for the map view. MyMapView.Map = new Map(BasemapStyle.ArcGISTopographic); // Add graphics overlays to the map view. MyMapView.GraphicsOverlays.AddRange(new[] { MakePointGraphicsOverlay(), MakeLineGraphicsOverlay(), MakeSquareGraphicsOverlay(), MakeCurvedGraphicsOverlay(), MakeEllipseGraphicsOverlay() }); } private GraphicsOverlay MakeEllipseGraphicsOverlay() { // Create a simple fill symbol with outline. SimpleLineSymbol curvedLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Purple, 1); SimpleFillSymbol curvedFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Purple, curvedLineSymbol); // Create a graphics overlay for the polygons with curve segments. GraphicsOverlay ellipseGraphicsOverlay = new GraphicsOverlay(); // Create and assign a simple renderer to the graphics overlay. ellipseGraphicsOverlay.Renderer = new SimpleRenderer(curvedFillSymbol); // Create the polygon geometry, then create a graphic using that polygon. Polygon ellipse = MakeEllipseGeometry(); Graphic ellipseGraphic = new Graphic(ellipse); // Add the graphic to the graphics overlay. ellipseGraphicsOverlay.Graphics.Add(ellipseGraphic); return ellipseGraphicsOverlay; } private GraphicsOverlay MakePointGraphicsOverlay() { // Create a simple marker symbol. SimpleMarkerSymbol pointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Diamond, Color.Green, 10); // Create a graphics overlay for the points. GraphicsOverlay pointGraphicsOverlay = new GraphicsOverlay(); // Create and assign a simple renderer to the graphics overlay. pointGraphicsOverlay.Renderer = new SimpleRenderer(pointSymbol); // Create a graphic with the map point geometry. MapPoint pointGeometry = new MapPoint(x: 40e5, y: 40e5, SpatialReferences.WebMercator); Graphic pointGraphic = new Graphic(pointGeometry); // Add the graphic to the overlay. pointGraphicsOverlay.Graphics.Add(pointGraphic); return pointGraphicsOverlay; } private GraphicsOverlay MakeLineGraphicsOverlay() { // Create a simple line symbol. SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Blue, 5); // Create a graphics overlay for the polylines. GraphicsOverlay lineGraphicsOverlay = new GraphicsOverlay(); // Create and assign a simple renderer to the graphics overlay. lineGraphicsOverlay.Renderer = new SimpleRenderer(lineSymbol); // Create a line graphic with new Polyline geometry. PolylineBuilder lineBuilder = new PolylineBuilder(SpatialReferences.WebMercator); lineBuilder.AddPoint(x: -10e5, y: 40e5); lineBuilder.AddPoint(x: 20e5, y: 50e5); Graphic lineGraphic = new Graphic(lineBuilder.ToGeometry()); // Add the graphic to the overlay. lineGraphicsOverlay.Graphics.Add(lineGraphic); return lineGraphicsOverlay; } private GraphicsOverlay MakeSquareGraphicsOverlay() { // Create a simple fill symbol. SimpleFillSymbol squareSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Yellow, null); // Create a graphics overlay for the square polygons. GraphicsOverlay squareGraphicsOverlay = new GraphicsOverlay(); // Create and assign a simple renderer to the graphics overlay. squareGraphicsOverlay.Renderer = new SimpleRenderer(squareSymbol); // Create a polygon graphic with `new Polygon` geometry. PolygonBuilder polygonBuilder = new PolygonBuilder(SpatialReferences.WebMercator); polygonBuilder.AddPoint(x: -20e5, y: 20e5); polygonBuilder.AddPoint(x: 20e5, y: 20e5); polygonBuilder.AddPoint(x: 20e5, y: -20e5); polygonBuilder.AddPoint(x: -20e5, y: -20e5); Graphic polygonGraphic = new Graphic(polygonBuilder.ToGeometry()); // Add the graphic to the overlay. squareGraphicsOverlay.Graphics.Add(polygonGraphic); return squareGraphicsOverlay; } private GraphicsOverlay MakeCurvedGraphicsOverlay() { // Create a simple fill symbol with outline. SimpleLineSymbol curvedLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1); SimpleFillSymbol curvedFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Red, curvedLineSymbol); // Create a graphics overlay for the polygons with curve segments. GraphicsOverlay curvedGraphicsOverlay = new GraphicsOverlay(); // Create and assign a simple renderer to the graphics overlay. curvedGraphicsOverlay.Renderer = new SimpleRenderer(curvedFillSymbol); // Create a heart-shaped graphic. MapPoint origin = new MapPoint(x: 40e5, y: 5e5, SpatialReferences.WebMercator); Geometry heartGeometry = MakeHeartGeometry(origin, 10e5); Graphic heartGraphic = new Graphic(heartGeometry); curvedGraphicsOverlay.Graphics.Add(heartGraphic); return curvedGraphicsOverlay; } private Geometry MakeHeartGeometry(MapPoint center, double sideLength) { if (sideLength <= 0) return null; SpatialReference spatialReference = center.SpatialReference; // The x and y coordinates to simplify the calculation. double minX = center.X - 0.5 * sideLength; double minY = center.Y - 0.5 * sideLength; // The radius of the arcs. double arcRadius = sideLength * 0.25; // Bottom left curve. MapPoint leftCurveStart = new MapPoint(center.X, minY, spatialReference); MapPoint leftCurveEnd = new MapPoint(minX, minY + 0.75 * sideLength, spatialReference); MapPoint leftControlMapPoint1 = new MapPoint(center.X, minY + 0.25 * sideLength, spatialReference); MapPoint leftControlMapPoint2 = new MapPoint(minX, center.Y, spatialReference: spatialReference); CubicBezierSegment leftCurve = new CubicBezierSegment(leftCurveStart, leftControlMapPoint1, leftControlMapPoint2, leftCurveEnd, spatialReference); // Top left arc. MapPoint leftArcCenter = new MapPoint(minX + 0.25 * sideLength, minY + 0.75 * sideLength, spatialReference); EllipticArcSegment leftArc = EllipticArcSegment.CreateCircularEllipticArc(leftArcCenter, arcRadius, Math.PI, centralAngle: -Math.PI, spatialReference); // Top right arc. MapPoint rightArcCenter = new MapPoint(minX + 0.75 * sideLength, minY + 0.75 * sideLength, spatialReference); EllipticArcSegment rightArc = EllipticArcSegment.CreateCircularEllipticArc(rightArcCenter, arcRadius, Math.PI, centralAngle: -Math.PI, spatialReference); // Bottom right curve. MapPoint rightCurveStart = new MapPoint(minX + sideLength, minY + 0.75 * sideLength, spatialReference); MapPoint rightCurveEnd = leftCurveStart; MapPoint rightControlMapPoint1 = new MapPoint(minX + sideLength, center.Y, spatialReference); MapPoint rightControlMapPoint2 = leftControlMapPoint1; CubicBezierSegment rightCurve = new CubicBezierSegment(rightCurveStart, rightControlMapPoint1, rightControlMapPoint2, rightCurveEnd, spatialReference); // Create the heart polygon. Part newPart = new Part(new Segment[] { leftCurve, leftArc, rightArc, rightCurve }, spatialReference); PolygonBuilder builder = new PolygonBuilder(spatialReference); builder.AddPart(newPart); return builder.ToGeometry(); } private Polygon MakeEllipseGeometry() { // Creates a GeodesicEllipseParameters object to use for GeometryEngine.EllipseGeodesic method. GeodesicEllipseParameters parameters = new GeodesicEllipseParameters { Center = new MapPoint(70e5, 10e5, SpatialReferences.WebMercator), GeometryType = GeometryType.Polygon, SemiAxis1Length = 1000, SemiAxis2Length = 2000, AxisDirection = 45, MaxPointCount = 100, // Angular unit is degrees by default. AngularUnit = AngularUnits.Degrees, // Linear unit is meters by default. LinearUnit = LinearUnits.Kilometers, MaxSegmentLength = 20 }; Polygon ellipsePoly = (Polygon)GeometryEngine.EllipseGeodesic(parameters); return ellipsePoly; } } }
#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 subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System.Globalization; using MbUnit.Framework; using Subtext.Framework; using Subtext.Framework.Configuration; using Subtext.Framework.Exceptions; using Subtext.Framework.Providers; using Subtext.Framework.Security; namespace UnitTests.Subtext.Framework.Configuration { /// <summary> /// These are unit tests specifically of the blog creation process, /// as there are many validation rules involved. /// </summary> [TestFixture] public class BlogCreationTests { string _hostName; /// <summary> /// Ensures that creating a blog will hash the password /// if UseHashedPassword is set in web.config (as it should be). /// </summary> [Test] [RollBack] public void CreatingBlogHashesPassword() { const string password = "MyPassword"; string hashedPassword = SecurityHelper.HashPassword(password); Config.CreateBlog("", "username", password, _hostName, "MyBlog1"); Blog info = Config.GetBlog(_hostName, "MyBlog1"); Assert.IsNotNull(info, "We tried to get blog at " + _hostName + "/MyBlog1 but it was null"); Config.Settings.UseHashedPasswords = true; Assert.IsTrue(Config.Settings.UseHashedPasswords, "This test is voided because we're not hashing passwords"); Assert.AreEqual(hashedPassword, info.Password, "The password wasn't hashed."); } /// <summary> /// Ran into a problem where saving changes to a blog would rehash the password. /// We need a separate method for changing passwords. /// </summary> [Test] [RollBack] public void ModifyingBlogShouldNotChangePassword() { Config.Settings.UseHashedPasswords = true; Config.CreateBlog("", "username", "thePassword", _hostName, "MyBlog1"); Blog info = Config.GetBlog(_hostName.ToUpper(CultureInfo.InvariantCulture), "MyBlog1"); string password = info.Password; info.LicenseUrl = "http://subtextproject.com/"; ObjectProvider.Instance().UpdateConfigData(info); info = Config.GetBlog(_hostName.ToUpper(CultureInfo.InvariantCulture), "MyBlog1"); Assert.AreEqual(password, info.Password); } /// <summary> /// If a blog already exists with a domain name and subfolder, one /// cannot create a blog with the same domain name and no subfolder. /// </summary> [Test] [RollBack] public void CreatingBlogWithDuplicateHostNameRequiresSubfolderName() { Config.CreateBlog("", "username", "password", _hostName, "MyBlog1"); UnitTestHelper.AssertThrows<BlogRequiresSubfolderException>(() => Config.CreateBlog("", "username", "password", _hostName, string.Empty)); } /// <summary> /// Make sure adding two distinct blogs doesn't raise an exception. /// </summary> [Test] [RollBack] public void CreatingMultipleBlogs_WithDistinctProperties_DoesNotThrowException() { Config.CreateBlog("title", "username", "password", UnitTestHelper.GenerateUniqueString(), string.Empty); Config.CreateBlog("title", "username", "password", "www2." + UnitTestHelper.GenerateUniqueString(), string.Empty); Config.CreateBlog("title", "username", "password", UnitTestHelper.GenerateUniqueString(), string.Empty); Config.CreateBlog("title", "username", "password", _hostName, "Blog1"); Config.CreateBlog("title", "username", "password", _hostName, "Blog2"); Config.CreateBlog("title", "username", "password", _hostName, "Blog3"); } /// <summary> /// Ensures that one cannot create a blog with a duplicate host /// as another blog when both have no subfolder specified. /// </summary> [Test] [RollBack] public void CreateBlogCannotCreateOneWithDuplicateHostAndNoSubfolder() { Config.CreateBlog("title", "username", "password", _hostName, string.Empty); UnitTestHelper.AssertThrows<BlogDuplicationException>(() => Config.CreateBlog("title", "username2", "password2", _hostName, string.Empty)); } /// <summary> /// Ensures that one cannot create a blog with a duplicate host /// as another blog when both have no subfolder specified. /// </summary> [Test] [RollBack] public void CreateBlogCannotCreateBlogWithHostThatIsDuplicateOfAnotherBlogAlias() { Config.CreateBlog("title", "username", "password", _hostName, string.Empty); var alias = new BlogAlias {Host = "example.com", IsActive = true, BlogId = Config.GetBlog(_hostName, string.Empty).Id}; Config.AddBlogAlias(alias); UnitTestHelper.AssertThrows<BlogDuplicationException>(() => Config.CreateBlog("title", "username2", "password2", "example.com", string.Empty)); } /// <summary> /// Ensures that one cannot create a blog with a duplicate host /// as another blog when both have no subfolder specified. /// </summary> [Test] [RollBack] public void CreateBlogCannotAddAliasThatIsDuplicateOfAnotherBlog() { Config.CreateBlog("title", "username", "password", _hostName, string.Empty); Config.CreateBlog("title", "username2", "password2", "example.com", string.Empty); var alias = new BlogAlias {Host = "example.com", IsActive = true, BlogId = Config.GetBlog(_hostName, string.Empty).Id}; UnitTestHelper.AssertThrows<BlogDuplicationException>(() => Config.AddBlogAlias(alias)); } /// <summary> /// Ensures that one cannot create a blog with a duplicate subfolder and host /// as another blog. /// </summary> [Test] [RollBack] public void CreateBlogCannotCreateOneWithDuplicateHostAndSubfolder() { Config.CreateBlog("title", "username", "password", _hostName, "MyBlog"); UnitTestHelper.AssertThrows<BlogDuplicationException>(() => Config.CreateBlog("title", "username2", "password2", _hostName, "MyBlog")); } /// <summary> /// Ensures that one cannot update a blog to have a duplicate subfolder and host /// as another blog. /// </summary> [Test] [RollBack] public void UpdateBlogCannotConflictWithDuplicateHostAndSubfolder() { string secondHost = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("title", "username", "password", _hostName, "MyBlog"); Config.CreateBlog("title", "username2", "password2", secondHost, "MyBlog"); Blog info = Config.GetBlog(secondHost, "MyBlog"); info.Host = _hostName; UnitTestHelper.AssertThrows<BlogDuplicationException>(() => ObjectProvider.Instance().UpdateConfigData(info)); } /// <summary> /// Ensures that one update a blog to have a duplicate host /// as another blog when both have no subfolder specified. /// </summary> [Test] [RollBack] public void UpdateBlogCannotConflictWithDuplicateHost() { string anotherHost = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("title", "username", "password", _hostName, string.Empty); Config.CreateBlog("title", "username2", "password2", anotherHost, string.Empty); Blog info = Config.GetBlog(anotherHost, string.Empty); info.Host = _hostName; UnitTestHelper.AssertThrows<BlogDuplicationException>(() => ObjectProvider.Instance().UpdateConfigData(info)); } /// <summary> /// Ensures that creating a blog cannot "hide" another blog. Read the /// remarks for more details. /// </summary> /// <remarks> /// <p>This exception occurs when adding a blog with the same hostname as another blog, /// but the original blog does not have an subfolder name defined.</p> /// <p>For example, if there exists a blog with the host "www.example.com" with no /// subfolder defined, and the admin adds another blog with the host "www.example.com" /// and subfolder as "MyBlog", this creates a multiple blog situation in the example.com /// domain. In that situation, each example.com blog MUST have an subfolder name defined. /// The URL to the example.com with no subfolder becomes the aggregate blog. /// </p> /// </remarks> [Test] [RollBack] public void CreateBlogCannotHideAnotherBlog() { Config.CreateBlog("title", "username", "password", _hostName, string.Empty); UnitTestHelper.AssertThrows<BlogHiddenException>(() => Config.CreateBlog("title", "username", "password", _hostName, "MyBlog")); } /// <summary> /// Ensures that updating a blog cannot "hide" another blog. Read the /// remarks for more details. /// </summary> /// <remarks> /// <p>This exception occurs when adding a blog with the same hostname as another blog, /// but the original blog does not have an subfolder name defined.</p> /// <p>For example, if there exists a blog with the host "www.example.com" with no /// subfolder defined, and the admin adds another blog with the host "www.example.com" /// and subfolder as "MyBlog", this creates a multiple blog situation in the example.com /// domain. In that situation, each example.com blog MUST have an subfolder name defined. /// The URL to the example.com with no subfolder becomes the aggregate blog. /// </p> /// </remarks> [Test] [RollBack] public void UpdatingBlogCannotHideAnotherBlog() { Config.CreateBlog("title", "username", "password", "www.mydomain.com", string.Empty); Blog info = Config.GetBlog("www.mydomain.com", string.Empty); info.Host = "mydomain.com"; info.Subfolder = "MyBlog"; ObjectProvider.Instance().UpdateConfigData(info); } /// <summary> /// If a blog already exists with a domain name and subfolder, one /// cannot modify another blog to have the same domain name, but with no subfolder. /// </summary> [Test] [RollBack] public void UpdatingBlogWithDuplicateHostNameRequiresSubfolderName() { string anotherHost = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("title", "username", "password", _hostName, "MyBlog1"); Config.CreateBlog("title", "username", "password", anotherHost, string.Empty); Blog info = Config.GetBlog(anotherHost, string.Empty); info.Host = _hostName; info.Subfolder = string.Empty; UnitTestHelper.AssertThrows<BlogRequiresSubfolderException>(() => ObjectProvider.Instance().UpdateConfigData(info)); } /// <summary> /// This really tests that looking for duplicates doesn't /// include the blog being edited. /// </summary> [Test] [RollBack] public void UpdatingBlogIsFine() { Config.CreateBlog("title", "username", "password", _hostName, string.Empty); Blog info = Config.GetBlog(_hostName.ToUpper(CultureInfo.InvariantCulture), string.Empty); info.Author = "Phil"; ObjectProvider.Instance().UpdateConfigData(info); //Make sure no exception is thrown. } [Test] [RollBack] public void CanUpdateMobileSkin() { Config.CreateBlog("title", "username", "password", _hostName, string.Empty); Blog info = Config.GetBlog(_hostName.ToUpper(CultureInfo.InvariantCulture), string.Empty); info.MobileSkin = new SkinConfig {TemplateFolder = "Mobile", SkinStyleSheet = "Mobile.css"}; ObjectProvider.Instance().UpdateConfigData(info); Blog blog = ObjectProvider.Instance().GetBlogById(info.Id); Assert.AreEqual("Mobile", blog.MobileSkin.TemplateFolder); Assert.AreEqual("Mobile.css", blog.MobileSkin.SkinStyleSheet); } /// <summary> /// Makes sure that every invalid character is checked /// within the subfolder name. /// </summary> [Test] [RollBack] public void EnsureInvalidCharactersMayNotBeUsedInSubfolderName() { string[] badNames = { "a{b", "a}b", "a[e", "a]e", "a/e", @"a\e", "a@e", "a!e", "a#e", "a$e", "a'e", "a%", ":e", "a^", "ae&", "*ae", "a(e", "a)e", "a?e", "+a", "e|", "a\"", "e=", "a'", "e<", "a>e", "a;", ",e", "a e" }; foreach(string badName in badNames) { Assert.IsFalse(Config.IsValidSubfolderName(badName), badName + " is not a valid app name."); } } /// <summary> /// Makes sure that every invalid character is checked /// within the subfolder name. /// </summary> [Test] [RollBack] public void ReservedSubtextWordsAreNotValidForSubfolders() { string[] badSubfolders = { "name.", "tags", "Admin", "bin", "ExternalDependencies", "HostAdmin", "Images", "Install", "Properties", "Providers", "Scripts", "Skins", "SystemMessages", "UI", "Modules", "Services", "Category", "Archive", "Archives", "Comments", "Articles", "Posts", "Story", "Stories", "Gallery", "aggbug", "Sitemap" }; foreach(string subfolderCandidate in badSubfolders) { Assert.IsFalse(Config.IsValidSubfolderName(subfolderCandidate), subfolderCandidate + " is not a valid app name."); } } /// <summary> /// Sets the up test fixture. This is called once for /// this test fixture before all the tests run. /// </summary> [TestFixtureSetUp] public void SetUpTestFixture() { //Confirm app settings UnitTestHelper.AssertAppSettings(); } [SetUp] public void SetUp() { _hostName = UnitTestHelper.GenerateUniqueString(); UnitTestHelper.SetHttpContextWithBlogRequest(_hostName, "MyBlog"); } [TearDown] public void TearDown() { } /// <summary> /// Tests that creating a blog with a reserved keyword (bin) is not allowed. /// </summary> [Test] [RollBack] public void CannotCreateBlogWithSubfolderNameBin() { UnitTestHelper.AssertThrows<InvalidSubfolderNameException>(() => Config.CreateBlog("title", "blah", "blah", _hostName, "bin")); } /// <summary> /// Tests that modifying a blog with a reserved keyword (bin) is not allowed. /// </summary> [Test] [RollBack] public void CannotRenameBlogToHaveSubfolderNameBin() { Config.CreateBlog("title", "blah", "blah", _hostName, "Anything"); Blog info = Config.GetBlog(_hostName, "Anything"); info.Subfolder = "bin"; UnitTestHelper.AssertThrows<InvalidSubfolderNameException>(() => ObjectProvider.Instance().UpdateConfigData(info)); } /// <summary> /// Tests that creating a blog with a reserved keyword (archive) is not allowed. /// </summary> [Test] [RollBack] public void CannotCreateBlogWithSubfolderNameArchive() { UnitTestHelper.AssertThrows<InvalidSubfolderNameException>(() => Config.CreateBlog("title", "blah", "blah", _hostName, "archive")); } /// <summary> /// Tests that creating a blog that ends with . is not allowed /// </summary> [Test] [RollBack] public void CannotCreateBlogWithSubfolderNameEndingWithDot() { UnitTestHelper.AssertThrows<InvalidSubfolderNameException>(() => Config.CreateBlog("title", "blah", "blah", _hostName, "archive.")); } /// <summary> /// Tests that creating a blog that contains invalid characters is not allowed. /// </summary> [Test] [RollBack] public void CannotCreateBlogWithSubfolderNameWithInvalidCharacters() { UnitTestHelper.AssertThrows<InvalidSubfolderNameException>(() => Config.CreateBlog("title", "blah", "blah", _hostName, "My!Blog")); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using Host.Configuration; using IdentityModel; using IdentityServer4; using IdentityServer4.Quickstart.UI; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; using Serilog; using System.Linq; using System.Security.Claims; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using Host.Extensions; using Microsoft.AspNetCore.Authentication.Certificate; using Microsoft.AspNetCore.HttpOverrides; namespace Host { public class Startup { private readonly IConfiguration _config; public Startup(IConfiguration config) { _config = config; IdentityModelEventSource.ShowPII = true; } public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); // cookie policy to deal with temporary browser incompatibilities services.AddSameSiteCookiePolicy(); // configures IIS out-of-proc settings (see https://github.com/aspnet/AspNetCore/issues/14882) services.Configure<IISOptions>(iis => { iis.AuthenticationDisplayName = "Windows"; iis.AutomaticAuthentication = false; }); // configures IIS in-proc settings services.Configure<IISServerOptions>(iis => { iis.AuthenticationDisplayName = "Windows"; iis.AutomaticAuthentication = false; }); var builder = services.AddIdentityServer(options => { options.Events.RaiseSuccessEvents = true; options.Events.RaiseFailureEvents = true; options.Events.RaiseErrorEvents = true; options.Events.RaiseInformationEvents = true; options.MutualTls.Enabled = true; options.MutualTls.DomainName = "mtls"; //options.MutualTls.AlwaysEmitConfirmationClaim = true; }) .AddInMemoryClients(Clients.Get()) //.AddInMemoryClients(_config.GetSection("Clients")) .AddInMemoryIdentityResources(Resources.GetIdentityResources()) .AddInMemoryApiResources(Resources.GetApiResources()) .AddSigningCredential() .AddExtensionGrantValidator<Extensions.ExtensionGrantValidator>() .AddExtensionGrantValidator<Extensions.NoSubjectExtensionGrantValidator>() .AddJwtBearerClientAuthentication() .AddAppAuthRedirectUriValidator() .AddTestUsers(TestUsers.Users) .AddProfileService<HostProfileService>() .AddMutualTlsSecretValidators(); services.AddExternalIdentityProviders(); services.AddAuthentication() .AddCertificate(options => { options.AllowedCertificateTypes = CertificateTypes.All; options.RevocationMode = X509RevocationMode.NoCheck; }); services.AddCertificateForwardingForNginx(); services.AddLocalApiAuthentication(principal => { principal.Identities.First().AddClaim(new Claim("additional_claim", "additional_value")); return Task.FromResult(principal); }); } public void Configure(IApplicationBuilder app) { app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseCertificateForwarding(); app.UseCookiePolicy(); app.UseSerilogRequestLogging(); app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseRouting(); app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } } public static class BuilderExtensions { public static IIdentityServerBuilder AddSigningCredential(this IIdentityServerBuilder builder) { // create random RS256 key //builder.AddDeveloperSigningCredential(); // use an RSA-based certificate with RS256 var rsaCert = new X509Certificate2("./keys/identityserver.test.rsa.p12", "changeit"); builder.AddSigningCredential(rsaCert, "RS256"); // ...and PS256 builder.AddSigningCredential(rsaCert, "PS256"); // or manually extract ECDSA key from certificate (directly using the certificate is not support by Microsoft right now) var ecCert = new X509Certificate2("./keys/identityserver.test.ecdsa.p12", "changeit"); var key = new ECDsaSecurityKey(ecCert.GetECDsaPrivateKey()) { KeyId = CryptoRandom.CreateUniqueId(16) }; return builder.AddSigningCredential( key, IdentityServerConstants.ECDsaSigningAlgorithm.ES256); } } public static class ServiceExtensions { public static IServiceCollection AddExternalIdentityProviders(this IServiceCollection services) { // configures the OpenIdConnect handlers to persist the state parameter into the server-side IDistributedCache. services.AddOidcStateDataFormatterCache("aad", "demoidsrv"); services.AddAuthentication() .AddOpenIdConnect("Google", "Google", options => { options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme; options.ForwardSignOut = IdentityServerConstants.DefaultCookieAuthenticationScheme; options.Authority = "https://accounts.google.com/"; options.ClientId = "708996912208-9m4dkjb5hscn7cjrn5u0r4tbgkbj1fko.apps.googleusercontent.com"; options.CallbackPath = "/signin-google"; options.Scope.Add("email"); }) .AddOpenIdConnect("demoidsrv", "IdentityServer", options => { options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme; options.SignOutScheme = IdentityServerConstants.SignoutScheme; options.Authority = "https://demo.identityserver.io/"; options.ClientId = "implicit"; options.ResponseType = "id_token"; options.SaveTokens = true; options.CallbackPath = "/signin-idsrv"; options.SignedOutCallbackPath = "/signout-callback-idsrv"; options.RemoteSignOutPath = "/signout-idsrv"; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "role" }; }) .AddOpenIdConnect("aad", "Azure AD", options => { options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme; options.SignOutScheme = IdentityServerConstants.SignoutScheme; options.Authority = "https://login.windows.net/4ca9cb4c-5e5f-4be9-b700-c532992a3705"; options.ClientId = "96e3c53e-01cb-4244-b658-a42164cb67a9"; options.ResponseType = "id_token"; options.CallbackPath = "/signin-aad"; options.SignedOutCallbackPath = "/signout-callback-aad"; options.RemoteSignOutPath = "/signout-aad"; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "role" }; }) .AddOpenIdConnect("adfs", "ADFS", options => { options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme; options.SignOutScheme = IdentityServerConstants.SignoutScheme; options.Authority = "https://adfs.leastprivilege.vm/adfs"; options.ClientId = "c0ea8d99-f1e7-43b0-a100-7dee3f2e5c3c"; options.ResponseType = "id_token"; options.CallbackPath = "/signin-adfs"; options.SignedOutCallbackPath = "/signout-callback-adfs"; options.RemoteSignOutPath = "/signout-adfs"; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "role" }; }); return services; } public static void AddCertificateForwardingForNginx(this IServiceCollection services) { services.AddCertificateForwarding(options => { options.CertificateHeader = "X-SSL-CERT"; options.HeaderConverter = (headerValue) => { X509Certificate2 clientCertificate = null; if(!string.IsNullOrWhiteSpace(headerValue)) { byte[] bytes = Encoding.UTF8.GetBytes(Uri.UnescapeDataString(headerValue)); clientCertificate = new X509Certificate2(bytes); } return clientCertificate; }; }); } } }
// *********************************************************************** // Copyright (c) 2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if NET_4_0 || NET_4_5 || PORTABLE using System; using System.Threading.Tasks; using NUnit.Framework; #if NET_4_0 using Task = System.Threading.Tasks.TaskEx; #endif namespace NUnit.TestData { public class AsyncRealFixture { [Test] public async void AsyncVoid() { var result = await ReturnOne(); Assert.AreEqual(1, result); } #region async Task [Test] public async System.Threading.Tasks.Task AsyncTaskSuccess() { var result = await ReturnOne(); Assert.AreEqual(1, result); } [Test] public async System.Threading.Tasks.Task AsyncTaskFailure() { var result = await ReturnOne(); Assert.AreEqual(2, result); } [Test] public async System.Threading.Tasks.Task AsyncTaskError() { await ThrowException(); Assert.Fail("Should never get here"); } #endregion #region non-async Task [Test] public System.Threading.Tasks.Task TaskSuccess() { return Task.Run(() => Assert.AreEqual(1, 1)); } [Test] public System.Threading.Tasks.Task TaskFailure() { return Task.Run(() => Assert.AreEqual(1, 2)); } [Test] public System.Threading.Tasks.Task TaskError() { throw new InvalidOperationException(); } #endregion [Test] public async Task<int> AsyncTaskResult() { return await ReturnOne(); } [Test] public Task<int> TaskResult() { return ReturnOne(); } #region async Task<T> [TestCase(ExpectedResult = 1)] public async Task<int> AsyncTaskResultCheckSuccess() { return await ReturnOne(); } [TestCase(ExpectedResult = 2)] public async Task<int> AsyncTaskResultCheckFailure() { return await ReturnOne(); } [TestCase(ExpectedResult = 0)] public async Task<int> AsyncTaskResultCheckError() { return await ThrowException(); } #endregion #region non-async Task<T> [TestCase(ExpectedResult = 1)] public Task<int> TaskResultCheckSuccess() { return ReturnOne(); } [TestCase(ExpectedResult = 2)] public Task<int> TaskResultCheckFailure() { return ReturnOne(); } [TestCase(ExpectedResult = 0)] public Task<int> TaskResultCheckError() { return ThrowException(); } #endregion [TestCase(1, 2)] public async System.Threading.Tasks.Task AsyncTaskTestCaseWithParametersSuccess(int a, int b) { Assert.AreEqual(await ReturnOne(), b - a); } [TestCase(ExpectedResult = null)] public async Task<object> AsyncTaskResultCheckSuccessReturningNull() { return await Task.Run(() => (object)null); } [TestCase(ExpectedResult = null)] public Task<object> TaskResultCheckSuccessReturningNull() { return Task.Run(() => (object)null); } [Test] public async System.Threading.Tasks.Task NestedAsyncTaskSuccess() { var result = await Task.Run(async () => await ReturnOne()); Assert.AreEqual(1, result); } [Test] public async System.Threading.Tasks.Task NestedAsyncTaskFailure() { var result = await Task.Run(async () => await ReturnOne()); Assert.AreEqual(2, result); } [Test] public async System.Threading.Tasks.Task NestedAsyncTaskError() { await Task.Run(async () => await ThrowException()); Assert.Fail("Should never get here"); } [Test] public async System.Threading.Tasks.Task AsyncTaskMultipleSuccess() { var result = await ReturnOne(); Assert.AreEqual(await ReturnOne(), result); } [Test] public async System.Threading.Tasks.Task AsyncTaskMultipleFailure() { var result = await ReturnOne(); Assert.AreEqual(await ReturnOne() + 1, result); } [Test] public async System.Threading.Tasks.Task AsyncTaskMultipleError() { await ThrowException(); Assert.Fail("Should never get here"); } [Test] public async System.Threading.Tasks.Task TaskCheckTestContextAcrossTasks() { var testName = await GetTestNameFromContext(); Assert.IsNotNull(testName); Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name); } [Test] public async System.Threading.Tasks.Task TaskCheckTestContextWithinTestBody() { var testName = TestContext.CurrentContext.Test.Name; await ReturnOne(); Assert.IsNotNull(testName); Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name); } private static Task<string> GetTestNameFromContext() { return Task.Run(() => TestContext.CurrentContext.Test.Name); } private static Task<int> ReturnOne() { return Task.Run(() => 1); } private static Task<int> ThrowException() { Func<int> throws = () => { throw new InvalidOperationException(); }; return Task.Run( throws ); } } } #endif
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Contract ** ** <OWNER>maf,mbarnett,[....]</OWNER> ** ** Implementation details of CLR Contracts. ** ===========================================================*/ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. #if SILVERLIGHT #define FEATURE_UNTRUSTED_CALLERS #elif REDHAWK_RUNTIME #elif BARTOK_RUNTIME #else // CLR #define FEATURE_UNTRUSTED_CALLERS #define FEATURE_RELIABILITY_CONTRACTS #define FEATURE_SERIALIZATION #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; using System.Security.Permissions; #endif namespace System.Diagnostics.Contracts { public static partial class Contract { #region Private Methods [ThreadStatic] private static bool _assertingMustUseRewriter; /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> [SecuritySafeCritical] static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind) { if (_assertingMustUseRewriter) System.Diagnostics.Assert.Fail("Asserting that we must use the rewriter went reentrant.", "Didn't rewrite this mscorlib?"); _assertingMustUseRewriter = true; // For better diagnostics, report which assembly is at fault. Walk up stack and // find the first non-mscorlib assembly. Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object. StackTrace stack = new StackTrace(); Assembly probablyNotRewritten = null; for (int i = 0; i < stack.FrameCount; i++) { Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly; if (caller != thisAssembly) { probablyNotRewritten = caller; break; } } if (probablyNotRewritten == null) probablyNotRewritten = thisAssembly; String simpleName = probablyNotRewritten.GetName().Name; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, Environment.GetResourceString("MustUseCCRewrite", contractKind, simpleName), null, null, null); _assertingMustUseRewriter = false; } #endregion Private Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> [SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), "failureKind"); Contract.EndContractBlock(); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message var displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); } #if !FEATURE_CORECLR || FEATURE_NETCORE /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) /// to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust, because it will inform you of bugs in the appdomain and because the event handler /// could allow you to continue execution. /// </summary> public static event EventHandler<ContractFailedEventArgs> ContractFailed { #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif add { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value; } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif remove { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value; } } #endif // !FEATURE_CORECLR || FEATURE_NETCORE #endregion FailureBehavior } #if !FEATURE_CORECLR || FEATURE_NETCORE // Not usable on Silverlight by end users due to security, and full trust users have not yet expressed an interest. public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; private String _message; private String _condition; private Exception _originalException; private bool _handled; private bool _unwind; internal Exception thrownDuringHandler; #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) { Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; _message = message; _condition = condition; _originalException = originalException; } public String Message { get { return _message; } } public String Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } public Exception OriginalException { get { return _originalException; } } // Whether the event handler "handles" this contract failure, or to fail via escalation policy. public bool Handled { get { return _handled; } } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif public void SetHandled() { _handled = true; } public bool Unwind { get { return _unwind; } } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif public void SetUnwind() { _unwind = true; } } #endif // !FEATURE_CORECLR || FEATURE_NETCORE #if FEATURE_SERIALIZATION [Serializable] #else [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")] #endif [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] internal sealed class ContractException : Exception { readonly ContractFailureKind _Kind; readonly string _UserMessage; readonly string _Condition; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ContractFailureKind Kind { get { return _Kind; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Failure { get { return this.Message; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string UserMessage { get { return _UserMessage; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Condition { get { return _Condition; } } // Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT. private ContractException() { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; } public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException) : base(failure, innerException) { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; this._Kind = kind; this._UserMessage = userMessage; this._Condition = condition; } #if FEATURE_SERIALIZATION private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { _Kind = (ContractFailureKind)info.GetInt32("Kind"); _UserMessage = info.GetString("UserMessage"); _Condition = info.GetString("Condition"); } #endif // FEATURE_SERIALIZATION #if FEATURE_UNTRUSTED_CALLERS && FEATURE_SERIALIZATION [SecurityCritical] #if FEATURE_LINK_DEMAND && FEATURE_SERIALIZATION [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] #endif // FEATURE_LINK_DEMAND #endif // FEATURE_UNTRUSTED_CALLERS public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Kind", _Kind); info.AddValue("UserMessage", _UserMessage); info.AddValue("Condition", _Condition); } } } namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Private fields #if !FEATURE_CORECLR || FEATURE_NETCORE private static volatile EventHandler<ContractFailedEventArgs> contractFailedEvent; private static readonly Object lockObject = new Object(); #endif // !FEATURE_CORECLR || FEATURE_NETCORE internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); #endregion #if !FEATURE_CORECLR || FEATURE_NETCORE /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) or a /// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust. /// </summary> internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed { #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #endif add { // Eagerly prepare each event handler _marked with a reliability contract_, to // attempt to reduce out of memory exceptions while reporting contract violations. // This only works if the new handler obeys the constraints placed on // constrained execution regions. Eagerly preparing non-reliable event handlers // would be a perf hit and wouldn't significantly improve reliability. // UE: Please mention reliable event handlers should also be marked with the // PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed. System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value); lock (lockObject) { contractFailedEvent += value; } } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #endif remove { lock (lockObject) { contractFailedEvent -= value; } } } #endif // !FEATURE_CORECLR || FEATURE_NETCORE /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [SecuritySafeCritical] #endif static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), "failureKind"); Contract.EndContractBlock(); string returnValue; String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... #if !FEATURE_CORECLR || FEATURE_NETCORE ContractFailedEventArgs eventArgs = null; // In case of OOM. #endif // !FEATURE_CORECLR || FEATURE_NETCORE #if FEATURE_RELIABILITY_CONTRACTS System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText); #if !FEATURE_CORECLR || FEATURE_NETCORE EventHandler<ContractFailedEventArgs> contractFailedEventLocal = contractFailedEvent; if (contractFailedEventLocal != null) { eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException); foreach (EventHandler<ContractFailedEventArgs> handler in contractFailedEventLocal.GetInvocationList()) { try { handler(null, eventArgs); } catch (Exception e) { eventArgs.thrownDuringHandler = e; eventArgs.SetUnwind(); } } if (eventArgs.Unwind) { #if !FEATURE_CORECLR if (Environment.IsCLRHosted) TriggerCodeContractEscalationPolicy(failureKind, displayMessage, conditionText, innerException); #endif // unwind if (innerException == null) { innerException = eventArgs.thrownDuringHandler; } throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException); } } #endif // !FEATURE_CORECLR || FEATURE_NETCORE } finally { #if !FEATURE_CORECLR || FEATURE_NETCORE if (eventArgs != null && eventArgs.Handled) { returnValue = null; // handled } else #endif // !FEATURE_CORECLR || FEATURE_NETCORE { returnValue = displayMessage; } } resultFailureMessage = returnValue; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "conditionText")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR [SecuritySafeCritical] #endif static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { // If we're here, our intent is to pop up a dialog box (if we can). For developers // interacting live with a debugger, this is a good experience. For Silverlight // hosted in Internet Explorer, the assert window is great. If we cannot // pop up a dialog box, throw an exception (consider a library compiled with // "Assert On Failure" but used in a process that can't pop up asserts, like an // NT Service). For the CLR hosted by server apps like SQL or Exchange, we should // trigger escalation policy. #if !FEATURE_CORECLR if (Environment.IsCLRHosted) { TriggerCodeContractEscalationPolicy(kind, displayMessage, conditionText, innerException); // Hosts like SQL may choose to abort the thread, so we will not get here in all cases. // But if the host's chosen action was to throw an exception, we should throw an exception // here (which is easier to do in managed code with the right parameters). throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); } #endif // !FEATURE_CORECLR if (!Environment.UserInteractive) { throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); } // May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info. // Optional info like string for collapsed text vs. expanded text. String windowTitle = Environment.GetResourceString(GetResourceNameForFailure(kind)); const int numStackFramesToSkip = 2; // To make stack traces easier to read System.Diagnostics.Assert.Fail(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip); // If we got here, the user selected Ignore. Continue. } private static String GetResourceNameForFailure(ContractFailureKind failureKind) { String resourceName = null; switch (failureKind) { case ContractFailureKind.Assert: resourceName = "AssertionFailed"; break; case ContractFailureKind.Assume: resourceName = "AssumptionFailed"; break; case ContractFailureKind.Precondition: resourceName = "PreconditionFailed"; break; case ContractFailureKind.Postcondition: resourceName = "PostconditionFailed"; break; case ContractFailureKind.Invariant: resourceName = "InvariantFailed"; break; case ContractFailureKind.PostconditionOnException: resourceName = "PostconditionOnExceptionFailed"; break; default: Contract.Assume(false, "Unreachable code"); resourceName = "AssumptionFailed"; break; } return resourceName; } #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText) { String resourceName = GetResourceNameForFailure(failureKind); // Well-formatted English messages will take one of four forms. A sentence ending in // either a period or a colon, the condition string, then the message tacked // on to the end with two spaces in front. // Note that both the conditionText and userMessage may be null. Also, // on Silverlight we may not be able to look up a friendly string for the // error message. Let's leverage Silverlight's default error message there. String failureMessage; if (!String.IsNullOrEmpty(conditionText)) { resourceName += "_Cnd"; failureMessage = Environment.GetResourceString(resourceName, conditionText); } else { failureMessage = Environment.GetResourceString(resourceName); } // Now add in the user message, if present. if (!String.IsNullOrEmpty(userMessage)) { return failureMessage + " " + userMessage; } else { return failureMessage; } } #if !FEATURE_CORECLR // Will trigger escalation policy, if hosted and the host requested us to do something (such as // abort the thread or exit the process). Starting in Dev11, for hosted apps the default behavior // is to throw an exception. // Implementation notes: // We implement our default behavior of throwing an exception by simply returning from our native // method inside the runtime and falling through to throw an exception. // We must call through this method before calling the method on the Environment class // because our security team does not yet support SecuritySafeCritical on P/Invoke methods. // Note this can be called in the context of throwing another exception (EnsuresOnThrow). [SecuritySafeCritical] [DebuggerNonUserCode] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static void TriggerCodeContractEscalationPolicy(ContractFailureKind failureKind, String message, String conditionText, Exception innerException) { String exceptionAsString = null; if (innerException != null) exceptionAsString = innerException.ToString(); Environment.TriggerCodeContractFailure(failureKind, message, conditionText, exceptionAsString); } #endif // !FEATURE_CORECLR } } // namespace System.Runtime.CompilerServices
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Caching; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Screens.Edit.Components.Timelines.Summary.Parts; using osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations; namespace osu.Game.Screens.Edit.Compose.Components.Timeline { public class TimelineTickDisplay : TimelinePart<PointVisualisation> { [Resolved] private EditorBeatmap beatmap { get; set; } [Resolved] private Bindable<WorkingBeatmap> working { get; set; } [Resolved] private BindableBeatDivisor beatDivisor { get; set; } [Resolved(CanBeNull = true)] private IEditorChangeHandler changeHandler { get; set; } [Resolved] private OsuColour colours { get; set; } private static readonly int highest_divisor = BindableBeatDivisor.PREDEFINED_DIVISORS.Last(); public TimelineTickDisplay() { RelativeSizeAxes = Axes.Both; } private readonly Cached tickCache = new Cached(); [BackgroundDependencyLoader] private void load() { beatDivisor.BindValueChanged(_ => invalidateTicks()); if (changeHandler != null) // currently this is the best way to handle any kind of timing changes. changeHandler.OnStateChange += invalidateTicks; } private void invalidateTicks() { tickCache.Invalidate(); } /// <summary> /// The visible time/position range of the timeline. /// </summary> private (float min, float max) visibleRange = (float.MinValue, float.MaxValue); /// <summary> /// The next time/position value to the left of the display when tick regeneration needs to be run. /// </summary> private float? nextMinTick; /// <summary> /// The next time/position value to the right of the display when tick regeneration needs to be run. /// </summary> private float? nextMaxTick; [Resolved(canBeNull: true)] private Timeline timeline { get; set; } protected override void Update() { base.Update(); if (timeline != null) { var newRange = ( (ToLocalSpace(timeline.ScreenSpaceDrawQuad.TopLeft).X - PointVisualisation.MAX_WIDTH * 2) / DrawWidth * Content.RelativeChildSize.X, (ToLocalSpace(timeline.ScreenSpaceDrawQuad.TopRight).X + PointVisualisation.MAX_WIDTH * 2) / DrawWidth * Content.RelativeChildSize.X); if (visibleRange != newRange) { visibleRange = newRange; // actual regeneration only needs to occur if we've passed one of the known next min/max tick boundaries. if (nextMinTick == null || nextMaxTick == null || (visibleRange.min < nextMinTick || visibleRange.max > nextMaxTick)) tickCache.Invalidate(); } } if (!tickCache.IsValid) createTicks(); } private void createTicks() { int drawableIndex = 0; nextMinTick = null; nextMaxTick = null; for (int i = 0; i < beatmap.ControlPointInfo.TimingPoints.Count; i++) { var point = beatmap.ControlPointInfo.TimingPoints[i]; double until = i + 1 < beatmap.ControlPointInfo.TimingPoints.Count ? beatmap.ControlPointInfo.TimingPoints[i + 1].Time : working.Value.Track.Length; int beat = 0; for (double t = point.Time; t < until; t += point.BeatLength / beatDivisor.Value) { float xPos = (float)t; if (t < visibleRange.min) nextMinTick = xPos; else if (t > visibleRange.max) nextMaxTick ??= xPos; else { // if this is the first beat in the beatmap, there is no next min tick if (beat == 0 && i == 0) nextMinTick = float.MinValue; int indexInBar = beat % (point.TimeSignature.Numerator * beatDivisor.Value); int divisor = BindableBeatDivisor.GetDivisorForBeatIndex(beat, beatDivisor.Value); var colour = BindableBeatDivisor.GetColourFor(divisor, colours); // even though "bar lines" take up the full vertical space, we render them in two pieces because it allows for less anchor/origin churn. var line = getNextUsableLine(); line.X = xPos; line.Width = PointVisualisation.MAX_WIDTH * getWidth(indexInBar, divisor); line.Height = 0.9f * getHeight(indexInBar, divisor); line.Colour = colour; } beat++; } } int usedDrawables = drawableIndex; // save a few drawables beyond the currently used for edge cases. while (drawableIndex < Math.Min(usedDrawables + 16, Count)) Children[drawableIndex++].Hide(); // expire any excess while (drawableIndex < Count) Children[drawableIndex++].Expire(); tickCache.Validate(); Drawable getNextUsableLine() { PointVisualisation point; if (drawableIndex >= Count) Add(point = new PointVisualisation()); else point = Children[drawableIndex]; drawableIndex++; point.Show(); return point; } } private static float getWidth(int indexInBar, int divisor) { if (indexInBar == 0) return 1; switch (divisor) { case 1: case 2: return 0.6f; case 3: case 4: return 0.5f; case 6: case 8: return 0.4f; default: return 0.3f; } } private static float getHeight(int indexInBar, int divisor) { if (indexInBar == 0) return 1; switch (divisor) { case 1: case 2: return 0.9f; case 3: case 4: return 0.8f; case 6: case 8: return 0.7f; default: return 0.6f; } } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (changeHandler != null) changeHandler.OnStateChange -= invalidateTicks; } } }
namespace AngleSharp.Dom { using AngleSharp.Attributes; using System; using System.Collections.Generic; /// <summary> /// MutationObserver provides developers a way to react to changes in a /// DOM. /// </summary> [DomName("MutationObserver")] public sealed class MutationObserver { #region Fields private readonly Queue<IMutationRecord> _records; private readonly MutationCallback _callback; private readonly List<MutationObserving> _observing; #endregion #region ctor /// <summary> /// Creates a new mutation observer with the provided callback. /// </summary> /// <param name="callback">The callback to trigger.</param> [DomConstructor] public MutationObserver(MutationCallback callback) { _records = new Queue<IMutationRecord>(); _callback = callback ?? throw new ArgumentNullException(nameof(callback)); _observing = new List<MutationObserving>(); } #endregion #region Properties private MutationObserving? this[INode node] { get { foreach (var observing in _observing) { if (Object.ReferenceEquals(observing.Target, node)) { return observing; } } return null; } } #endregion #region Methods /// <summary> /// Queues a record. /// </summary> /// <param name="record">The record to queue up.</param> internal void Enqueue(MutationRecord record) { if (_records.Count > 0) { //Here we could schedule a callback! } _records.Enqueue(record); } /// <summary> /// Triggers the execution if the queue is not-empty. /// </summary> internal void Trigger() { var records = _records.ToArray(); _records.Clear(); ClearTransients(); if (records.Length != 0) { _callback(records, this); } } /// <summary> /// Gets the options, if any, for the given node. If null is returned /// then the node is not being observed. /// </summary> /// <param name="node">The node of interest.</param> /// <returns>The options set for the provided node.</returns> internal MutationOptions ResolveOptions(INode node) { foreach (var observing in _observing) { if (Object.ReferenceEquals(observing.Target, node) || observing.TransientNodes.Contains(node)) { return observing.Options; } } return default(MutationOptions); } /// <summary> /// Adds a transient observer for the given node with the provided /// ancestor, if the node's ancestor is currently observed. /// </summary> /// <param name="ancestor"> /// The ancestor that is currently observed. /// </param> /// <param name="node"> /// The node to observe as a transient observer. /// </param> internal void AddTransient(INode ancestor, INode node) { var obs = this[ancestor]; if (obs != null && obs.Options.IsObservingSubtree) { obs.TransientNodes.Add(node); } } /// <summary> /// Clears all transient observers. /// </summary> internal void ClearTransients() { foreach (var observing in _observing) { observing.TransientNodes.Clear(); } } /// <summary> /// Stops the MutationObserver instance from receiving /// notifications of DOM mutations. Until the observe() /// method is used again, observer's callback will not be invoked. /// </summary> [DomName("disconnect")] public void Disconnect() { foreach (var observing in _observing) { var node = (Node)observing.Target; node.Owner.Mutations.Unregister(this); } _records.Clear(); } /// <summary> /// Registers the MutationObserver instance to receive notifications of /// DOM mutations on the specified node. /// </summary> /// <param name="target"> /// The Node on which to observe DOM mutations. /// </param> /// <param name="childList"> /// If additions and removals of the target node's child elements /// (including text nodes) are to be observed. /// </param> /// <param name="subtree"> /// If mutations to not just target, but also target's descendants are /// to be observed. /// </param> /// <param name="attributes"> /// If mutations to target's attributes are to be observed. /// </param> /// <param name="characterData"> /// If mutations to target's data are to be observed. /// </param> /// <param name="attributeOldValue"> /// If attributes is set to true and target's attribute value before /// the mutation needs to be recorded. /// </param> /// <param name="characterDataOldValue"> /// If characterData is set to true and target's data before the /// mutation needs to be recorded. /// </param> /// <param name="attributeFilter"> /// The attributes to observe. If this is not set, then all attributes /// are being observed. /// </param> [DomName("observe")] [DomInitDict(offset: 1)] public void Connect(INode target, Boolean childList = false, Boolean subtree = false, Boolean? attributes = null, Boolean? characterData = null, Boolean? attributeOldValue = null, Boolean? characterDataOldValue = null, IEnumerable<String>? attributeFilter = null) { if (target is Node node) { var oldCharacterData = characterDataOldValue ?? false; var oldAttributeValue = attributeOldValue ?? false; var options = new MutationOptions { IsObservingChildNodes = childList, IsObservingSubtree = subtree, IsExaminingOldCharacterData = oldCharacterData, IsExaminingOldAttributeValue = oldAttributeValue, IsObservingCharacterData = characterData ?? oldCharacterData, IsObservingAttributes = attributes ?? (oldAttributeValue || attributeFilter != null), AttributeFilters = attributeFilter }; if (options.IsExaminingOldAttributeValue && !options.IsObservingAttributes) { throw new DomException(DomError.TypeMismatch); } if (options.AttributeFilters != null && !options.IsObservingAttributes) { throw new DomException(DomError.TypeMismatch); } if (options.IsExaminingOldCharacterData && !options.IsObservingCharacterData) { throw new DomException(DomError.TypeMismatch); } if (options.IsInvalid) { throw new DomException(DomError.Syntax); } if (node is Document document && document.DocumentElement is Node documentElement) { node = documentElement; target = documentElement; } if (node.Owner is null) { throw new DomException(DomError.HierarchyRequest); } node.Owner.Mutations.Register(this); var existing = this[target]; if (existing != null) { existing.TransientNodes.Clear(); _observing.Remove(existing); } _observing.Add(new MutationObserving(target, options)); } } /// <summary> /// Empties the MutationObserver instance's record queue and returns /// what was in there. /// </summary> /// <returns>Returns an Array of MutationRecords.</returns> [DomName("takeRecords")] public IEnumerable<IMutationRecord> Flush() { while (_records.Count > 0) { yield return _records.Dequeue(); } } #endregion #region Options internal struct MutationOptions { public Boolean IsObservingChildNodes; public Boolean IsObservingSubtree; public Boolean IsObservingCharacterData; public Boolean IsObservingAttributes; public Boolean IsExaminingOldCharacterData; public Boolean IsExaminingOldAttributeValue; public IEnumerable<String>? AttributeFilters; public Boolean IsInvalid => !IsObservingAttributes && !IsObservingCharacterData && !IsObservingChildNodes; } sealed class MutationObserving { private readonly INode _target; private readonly MutationOptions _options; private readonly List<INode> _transientNodes; public MutationObserving(INode target, MutationOptions options) { _target = target; _options = options; _transientNodes = new List<INode>(); } public INode Target => _target; public MutationOptions Options => _options; public List<INode> TransientNodes => _transientNodes; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedComparisonLessThanNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableCharTest(bool useInterpreter) { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableChar(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableFloat(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableLong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableSByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableUInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableULong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedComparisonLessThanNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyComparisonLessThanNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableChar(char? a, char? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableDouble(double? a, double? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableFloat(float? a, float? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } private static void VerifyComparisonLessThanNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.LessThan( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), true, null)); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a < b; bool? result = f(); Assert.Equal(a == null || b == null ? null : expected, result); } #endregion } }
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 news article /// </summary> public class NewsArticle_Core : TypeCore, IArticle { public NewsArticle_Core() { this._TypeId = 184; this._Id = "NewsArticle"; this._Schema_Org_Url = "http://schema.org/NewsArticle"; string label = ""; GetLabel(out label, "NewsArticle", typeof(NewsArticle_Core)); this._Label = label; this._Ancestors = new int[]{266,78,20}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{20}; this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,15,16,235,65,170,171,172,173}; } /// <summary> /// The subject matter of the content. /// </summary> private About_Core about; public About_Core About { get { return about; } set { about = value; SetPropertyInstance(about); } } /// <summary> /// Specifies the Person that is legally accountable for the CreativeWork. /// </summary> private AccountablePerson_Core accountablePerson; public AccountablePerson_Core AccountablePerson { get { return accountablePerson; } set { accountablePerson = value; SetPropertyInstance(accountablePerson); } } /// <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> /// A secondary title of the CreativeWork. /// </summary> private AlternativeHeadline_Core alternativeHeadline; public AlternativeHeadline_Core AlternativeHeadline { get { return alternativeHeadline; } set { alternativeHeadline = value; SetPropertyInstance(alternativeHeadline); } } /// <summary> /// The actual body of the article. /// </summary> private ArticleBody_Core articleBody; public ArticleBody_Core ArticleBody { get { return articleBody; } set { articleBody = value; SetPropertyInstance(articleBody); } } /// <summary> /// Articles may belong to one or more 'sections' in a magazine or newspaper, such as Sports, Lifestyle, etc. /// </summary> private ArticleSection_Core articleSection; public ArticleSection_Core ArticleSection { get { return articleSection; } set { articleSection = value; SetPropertyInstance(articleSection); } } /// <summary> /// The media objects that encode this creative work. This property is a synonym for encodings. /// </summary> private AssociatedMedia_Core associatedMedia; public AssociatedMedia_Core AssociatedMedia { get { return associatedMedia; } set { associatedMedia = value; SetPropertyInstance(associatedMedia); } } /// <summary> /// An embedded audio object. /// </summary> private Audio_Core audio; public Audio_Core Audio { get { return audio; } set { audio = value; SetPropertyInstance(audio); } } /// <summary> /// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely. /// </summary> private Author_Core author; public Author_Core Author { get { return author; } set { author = value; SetPropertyInstance(author); } } /// <summary> /// Awards won by this person or for this creative work. /// </summary> private Awards_Core awards; public Awards_Core Awards { get { return awards; } set { awards = value; SetPropertyInstance(awards); } } /// <summary> /// Comments, typically from users, on this CreativeWork. /// </summary> private Comment_Core comment; public Comment_Core Comment { get { return comment; } set { comment = value; SetPropertyInstance(comment); } } /// <summary> /// The location of the content. /// </summary> private ContentLocation_Core contentLocation; public ContentLocation_Core ContentLocation { get { return contentLocation; } set { contentLocation = value; SetPropertyInstance(contentLocation); } } /// <summary> /// Official rating of a piece of content\u2014for example,'MPAA PG-13'. /// </summary> private ContentRating_Core contentRating; public ContentRating_Core ContentRating { get { return contentRating; } set { contentRating = value; SetPropertyInstance(contentRating); } } /// <summary> /// A secondary contributor to the CreativeWork. /// </summary> private Contributor_Core contributor; public Contributor_Core Contributor { get { return contributor; } set { contributor = value; SetPropertyInstance(contributor); } } /// <summary> /// The party holding the legal copyright to the CreativeWork. /// </summary> private CopyrightHolder_Core copyrightHolder; public CopyrightHolder_Core CopyrightHolder { get { return copyrightHolder; } set { copyrightHolder = value; SetPropertyInstance(copyrightHolder); } } /// <summary> /// The year during which the claimed copyright for the CreativeWork was first asserted. /// </summary> private CopyrightYear_Core copyrightYear; public CopyrightYear_Core CopyrightYear { get { return copyrightYear; } set { copyrightYear = value; SetPropertyInstance(copyrightYear); } } /// <summary> /// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork. /// </summary> private Creator_Core creator; public Creator_Core Creator { get { return creator; } set { creator = value; SetPropertyInstance(creator); } } /// <summary> /// The date on which the CreativeWork was created. /// </summary> private DateCreated_Core dateCreated; public DateCreated_Core DateCreated { get { return dateCreated; } set { dateCreated = value; SetPropertyInstance(dateCreated); } } /// <summary> /// The location where the NewsArticle was produced. /// </summary> private Dateline_Core dateline; public Dateline_Core Dateline { get { return dateline; } set { dateline = value; SetPropertyInstance(dateline); } } /// <summary> /// The date on which the CreativeWork was most recently modified. /// </summary> private DateModified_Core dateModified; public DateModified_Core DateModified { get { return dateModified; } set { dateModified = value; SetPropertyInstance(dateModified); } } /// <summary> /// Date of first broadcast/publication. /// </summary> private DatePublished_Core datePublished; public DatePublished_Core DatePublished { get { return datePublished; } set { datePublished = value; SetPropertyInstance(datePublished); } } /// <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> /// A link to the page containing the comments of the CreativeWork. /// </summary> private DiscussionURL_Core discussionURL; public DiscussionURL_Core DiscussionURL { get { return discussionURL; } set { discussionURL = value; SetPropertyInstance(discussionURL); } } /// <summary> /// Specifies the Person who edited the CreativeWork. /// </summary> private Editor_Core editor; public Editor_Core Editor { get { return editor; } set { editor = value; SetPropertyInstance(editor); } } /// <summary> /// The media objects that encode this creative work /// </summary> private Encodings_Core encodings; public Encodings_Core Encodings { get { return encodings; } set { encodings = value; SetPropertyInstance(encodings); } } /// <summary> /// Genre of the creative work /// </summary> private Genre_Core genre; public Genre_Core Genre { get { return genre; } set { genre = value; SetPropertyInstance(genre); } } /// <summary> /// Headline of the article /// </summary> private Headline_Core headline; public Headline_Core Headline { get { return headline; } set { headline = value; SetPropertyInstance(headline); } } /// <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> /// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a> /// </summary> private InLanguage_Core inLanguage; public InLanguage_Core InLanguage { get { return inLanguage; } set { inLanguage = value; SetPropertyInstance(inLanguage); } } /// <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> /// Indicates whether this content is family friendly. /// </summary> private IsFamilyFriendly_Core isFamilyFriendly; public IsFamilyFriendly_Core IsFamilyFriendly { get { return isFamilyFriendly; } set { isFamilyFriendly = value; SetPropertyInstance(isFamilyFriendly); } } /// <summary> /// The keywords/tags used to describe this content. /// </summary> private Keywords_Core keywords; public Keywords_Core Keywords { get { return keywords; } set { keywords = value; SetPropertyInstance(keywords); } } /// <summary> /// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept. /// </summary> private Mentions_Core mentions; public Mentions_Core Mentions { get { return mentions; } set { mentions = value; SetPropertyInstance(mentions); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// The number of the column in which the NewsArticle appears in the print edition. /// </summary> private PrintColumn_Core printColumn; public PrintColumn_Core PrintColumn { get { return printColumn; } set { printColumn = value; SetPropertyInstance(printColumn); } } /// <summary> /// The edition of the print product in which the NewsArticle appears. /// </summary> private PrintEdition_Core printEdition; public PrintEdition_Core PrintEdition { get { return printEdition; } set { printEdition = value; SetPropertyInstance(printEdition); } } /// <summary> /// If this NewsArticle appears in print, this field indicates the name of the page on which the article is found. Please note that this field is intended for the exact page name (e.g. A5, B18). /// </summary> private PrintPage_Core printPage; public PrintPage_Core PrintPage { get { return printPage; } set { printPage = value; SetPropertyInstance(printPage); } } /// <summary> /// If this NewsArticle appears in print, this field indicates the print section in which the article appeared. /// </summary> private PrintSection_Core printSection; public PrintSection_Core PrintSection { get { return printSection; } set { printSection = value; SetPropertyInstance(printSection); } } /// <summary> /// Specifies the Person or Organization that distributed the CreativeWork. /// </summary> private Provider_Core provider; public Provider_Core Provider { get { return provider; } set { provider = value; SetPropertyInstance(provider); } } /// <summary> /// The publisher of the creative work. /// </summary> private Publisher_Core publisher; public Publisher_Core Publisher { get { return publisher; } set { publisher = value; SetPropertyInstance(publisher); } } /// <summary> /// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork. /// </summary> private PublishingPrinciples_Core publishingPrinciples; public PublishingPrinciples_Core PublishingPrinciples { get { return publishingPrinciples; } set { publishingPrinciples = value; SetPropertyInstance(publishingPrinciples); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The Organization on whose behalf the creator was working. /// </summary> private SourceOrganization_Core sourceOrganization; public SourceOrganization_Core SourceOrganization { get { return sourceOrganization; } set { sourceOrganization = value; SetPropertyInstance(sourceOrganization); } } /// <summary> /// A thumbnail image relevant to the Thing. /// </summary> private ThumbnailURL_Core thumbnailURL; public ThumbnailURL_Core ThumbnailURL { get { return thumbnailURL; } set { thumbnailURL = value; SetPropertyInstance(thumbnailURL); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } /// <summary> /// The version of the CreativeWork embodied by a specified resource. /// </summary> private Version_Core version; public Version_Core Version { get { return version; } set { version = value; SetPropertyInstance(version); } } /// <summary> /// An embedded video object. /// </summary> private Video_Core video; public Video_Core Video { get { return video; } set { video = value; SetPropertyInstance(video); } } /// <summary> /// The number of words in the text of the Article. /// </summary> private WordCount_Core wordCount; public WordCount_Core WordCount { get { return wordCount; } set { wordCount = value; SetPropertyInstance(wordCount); } } } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Collections; using System.Globalization; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Layout; using P2=Microsoft.Msagl.Core.Geometry.Point; using Microsoft.Msagl.Drawing; namespace Microsoft.Msagl.Drawing { /// <summary> /// Keep the information related to an object label /// </summary> [Serializable] public class Label: DrawingObject { ///<summary> ///</summary> public DrawingObject Owner { get; set; } /// <summary> /// an empty constructor /// </summary> public Label(){} /// <summary> /// a constructor with text /// </summary> /// <param name="textPar"></param> public Label(string textPar) { this.text = textPar; } ///<summary> ///</summary> public Point Center { get { if (Owner == null) return new Point(); var edge = Owner as Edge; if (edge != null) return edge.GeometryEdge.Label.Center; return ((Node)Owner).GeometryNode.Center; } } double width; double height; /// <summary> /// the width of the label /// </summary> public double Width { get { return GeometryLabel == null ? width : GeometryLabel.Width; } set { if (GeometryLabel == null) width = value; else GeometryLabel.Width = value; } } /// <summary> /// the height of the label /// </summary> public double Height { get { return GeometryLabel == null ? height : GeometryLabel.Height; } set { if (GeometryLabel == null) height = value; else GeometryLabel.Height = value; } } /// <summary> /// left coordinate /// </summary> public double Left { get { return Center.X - Width / 2; } } /// <summary> /// top coordinate /// </summary> public double Top { get { return Center.Y + Height / 2; } } /// <summary> /// left coordinate /// </summary> public double Right { get { return Center.X + Width / 2; } } /// <summary> /// top coordinate /// </summary> public double Bottom { get { return Center.Y - Height / 2; } } /// <summary> /// gets the left top corner /// </summary> public P2 LeftTop { get{ return new P2(Left,Top);}} /// <summary> /// gets the right bottom corner /// </summary> public P2 RightBottom { get { return new P2(Right, Bottom); } } /// <summary> /// returns the bounding box of the label /// </summary> override public Rectangle BoundingBox { get { return new Rectangle(LeftTop, RightBottom); } } /// <summary> /// gets or sets the label size /// </summary> virtual public Size Size { get { return new Size(Width, Height); } set { Width = value.Width; Height = value.Height; } } internal Color fontcolor = Color.Black; ///<summary> ///Label font color. ///</summary> [Description("type face color")] public Color FontColor { get { return fontcolor; } set { fontcolor = value; } } FontStyle fontStyle = FontStyle.Regular; ///<summary> ///Label font style. ///</summary> [Description("type face style")] public FontStyle FontStyle { get { return fontStyle; } set { fontStyle = value; } } ///<summary> ///Type face font. ///</summary> string fontName = ""; ///<summary> ///Type face font ///</summary> [Description("type face font"), DefaultValue("")] public string FontName { get { if (String.IsNullOrEmpty(fontName)) return DefaultFontName; else return fontName; } set { fontName = value; } } string text; /// <summary> /// A label of the entity. The label is rendered opposite to the ID. /// </summary> public string Text { get { return text; } set { if (value != null) text = value.Replace("\\n", "\n"); else text = ""; } } internal double fontsize = DefaultFontSize; ///<summary> ///The point size of the id. ///</summary> public double FontSize { get { return fontsize; } set { fontsize = value; } } internal static string defaultFontName = "Times-Roman"; /// <summary> /// the name of the defaul font /// </summary> public static string DefaultFontName { get { return defaultFontName; } set { defaultFontName = value; } } static int defaultFontSize = 12; /// <summary> /// the default font size /// </summary> static public int DefaultFontSize { get { return defaultFontSize; } set { defaultFontSize = value; } } Core.Layout.Label geometryLabel=new Core.Layout.Label(); /// <summary> /// gets or set geometry label /// </summary> public Core.Layout.Label GeometryLabel { get { return geometryLabel; } set { geometryLabel = value; } } /// <summary> /// gets the geometry of the label /// </summary> public override GeometryObject GeometryObject { get { return GeometryLabel; } set { GeometryLabel = (Core.Layout.Label) 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 Test.Cryptography; namespace System.Security.Cryptography.X509Certificates.Tests { internal static class TestData { public static byte[] MsCertificate = ( "308204ec308203d4a003020102021333000000b011af0a8bd03b9fdd00010000" + "00b0300d06092a864886f70d01010505003079310b3009060355040613025553" + "311330110603550408130a57617368696e67746f6e3110300e06035504071307" + "5265646d6f6e64311e301c060355040a13154d6963726f736f667420436f7270" + "6f726174696f6e312330210603550403131a4d6963726f736f667420436f6465" + "205369676e696e6720504341301e170d3133303132343232333333395a170d31" + "34303432343232333333395a308183310b300906035504061302555331133011" + "0603550408130a57617368696e67746f6e3110300e060355040713075265646d" + "6f6e64311e301c060355040a13154d6963726f736f667420436f72706f726174" + "696f6e310d300b060355040b13044d4f5052311e301c060355040313154d6963" + "726f736f667420436f72706f726174696f6e30820122300d06092a864886f70d" + "01010105000382010f003082010a0282010100e8af5ca2200df8287cbc057b7f" + "adeeeb76ac28533f3adb407db38e33e6573fa551153454a5cfb48ba93fa837e1" + "2d50ed35164eef4d7adb137688b02cf0595ca9ebe1d72975e41b85279bf3f82d" + "9e41362b0b40fbbe3bbab95c759316524bca33c537b0f3eb7ea8f541155c0865" + "1d2137f02cba220b10b1109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5" + "c90a21e2aae3013647fd2f826a8103f5a935dc94579dfb4bd40e82db388f12fe" + "e3d67a748864e162c4252e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a6" + "79b5b6dbcef9707b280184b82a29cfbfa90505e1e00f714dfdad5c238329ebc7" + "c54ac8e82784d37ec6430b950005b14f6571c50203010001a38201603082015c" + "30130603551d25040c300a06082b06010505070303301d0603551d0e04160414" + "5971a65a334dda980780ff841ebe87f9723241f230510603551d11044a3048a4" + "463044310d300b060355040b13044d4f5052313330310603550405132a333135" + "39352b34666166306237312d616433372d346161332d613637312d3736626330" + "35323334346164301f0603551d23041830168014cb11e8cad2b4165801c9372e" + "331616b94c9a0a1f30560603551d1f044f304d304ba049a0478645687474703a" + "2f2f63726c2e6d6963726f736f66742e636f6d2f706b692f63726c2f70726f64" + "756374732f4d6963436f645369675043415f30382d33312d323031302e63726c" + "305a06082b06010505070101044e304c304a06082b06010505073002863e6874" + "74703a2f2f7777772e6d6963726f736f66742e636f6d2f706b692f6365727473" + "2f4d6963436f645369675043415f30382d33312d323031302e637274300d0609" + "2a864886f70d0101050500038201010031d76e2a12573381d59dc6ebf93ad444" + "4d089eee5edf6a5bb779cf029cbc76689e90a19c0bc37fa28cf14dba9539fb0d" + "e0e19bf45d240f1b8d88153a7cdbadceb3c96cba392c457d24115426300d0dff" + "47ea0307e5e4665d2c7b9d1da910fa1cb074f24f696b9ea92484daed96a0df73" + "a4ef6a1aac4b629ef17cc0147f48cd4db244f9f03c936d42d8e87ce617a09b68" + "680928f90297ef1103ba6752adc1e9b373a6d263cd4ae23ee4f34efdffa1e0bb" + "02133b5d20de553fa3ae9040313875285e04a9466de6f57a7940bd1fcde845d5" + "aee25d3ef575c7e6666360ccd59a84878d2430f7ef34d0631db142674a0e4bbf" + "3a0eefb6953aa738e4259208a6886682").HexToByteArray(); public static readonly byte[] MsCertificatePemBytes = ByteUtils.AsciiBytes( @"-----BEGIN CERTIFICATE----- MIIE7DCCA9SgAwIBAgITMwAAALARrwqL0Duf3QABAAAAsDANBgkqhkiG9w0BAQUF ADB5MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMH UmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSMwIQYDVQQD ExpNaWNyb3NvZnQgQ29kZSBTaWduaW5nIFBDQTAeFw0xMzAxMjQyMjMzMzlaFw0x NDA0MjQyMjMzMzlaMIGDMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3Rv bjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0 aW9uMQ0wCwYDVQQLEwRNT1BSMR4wHAYDVQQDExVNaWNyb3NvZnQgQ29ycG9yYXRp b24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDor1yiIA34KHy8BXt/ re7rdqwoUz8620B9s44z5lc/pVEVNFSlz7SLqT+oN+EtUO01Fk7vTXrbE3aIsCzw WVyp6+HXKXXkG4Unm/P4LZ5BNisLQPu+O7q5XHWTFlJLyjPFN7Dz636o9UEVXAhl HSE38Cy6IgsQsRCddyKFhHxPuRuQsPWj/ov0DJpOoPXJCiHiquMBNkf9L4JqgQP1 qTXclFed+0vUDoLbOI8S/uPWenSIZOFixCUuKq6dGB8OHrbCryS0DlC83hyTXEmm ebW22875cHsoAYS4KinPv6kFBeHgD3FN/a1cI4Mp68fFSsjoJ4TTfsZDC5UABbFP ZXHFAgMBAAGjggFgMIIBXDATBgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQU WXGmWjNN2pgHgP+EHr6H+XIyQfIwUQYDVR0RBEowSKRGMEQxDTALBgNVBAsTBE1P UFIxMzAxBgNVBAUTKjMxNTk1KzRmYWYwYjcxLWFkMzctNGFhMy1hNjcxLTc2YmMw NTIzNDRhZDAfBgNVHSMEGDAWgBTLEejK0rQWWAHJNy4zFha5TJoKHzBWBgNVHR8E TzBNMEugSaBHhkVodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9k dWN0cy9NaWNDb2RTaWdQQ0FfMDgtMzEtMjAxMC5jcmwwWgYIKwYBBQUHAQEETjBM MEoGCCsGAQUFBzAChj5odHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRz L01pY0NvZFNpZ1BDQV8wOC0zMS0yMDEwLmNydDANBgkqhkiG9w0BAQUFAAOCAQEA MdduKhJXM4HVncbr+TrURE0Inu5e32pbt3nPApy8dmiekKGcC8N/oozxTbqVOfsN 4OGb9F0kDxuNiBU6fNutzrPJbLo5LEV9JBFUJjANDf9H6gMH5eRmXSx7nR2pEPoc sHTyT2lrnqkkhNrtlqDfc6TvahqsS2Ke8XzAFH9IzU2yRPnwPJNtQtjofOYXoJto aAko+QKX7xEDumdSrcHps3Om0mPNSuI+5PNO/f+h4LsCEztdIN5VP6OukEAxOHUo XgSpRm3m9Xp5QL0fzehF1a7iXT71dcfmZmNgzNWahIeNJDD37zTQYx2xQmdKDku/ Og7vtpU6pzjkJZIIpohmgg== -----END CERTIFICATE----- "); public const string PfxDataPassword = "12345"; public static SecureString CreatePfxDataPasswordSecureString() { var s = new SecureString(); // WARNING: // A key value of SecureString is in keeping string data off of the GC heap, such that it can // be reliably cleared when no longer needed. Creating a SecureString from a string or converting // a SecureString to a string diminishes that value. These conversion functions are for testing that // SecureString works, and does not represent a pattern to follow in any non-test situation. foreach (char c in PfxDataPassword.ToCharArray()) { s.AppendChar(c); } return s; } public static readonly byte[] PfxSha1Empty_ExpectedSig = ( "44b15120b8c7de19b4968d761600ffb8c54e5d0c1bcaba0880a20ab48912c8fd" + "fa81b28134eabf58f3211a0d1eefdaae115e7872d5a67045c3b62a5da4393940" + "e5a496413a6d55ea6309d0013e90657c83c6e40aa8fafeee66acbb6661c14190" + "11e1fde6f4fcc328bd7e537e4aa2dbe216d8f1f3aa7e5ec60eb9cfdca7a41d74").HexToByteArray(); public static readonly byte[] PfxData = ( "3082063A020103308205F606092A864886F70D010701A08205E7048205E33082" + "05DF3082035806092A864886F70D010701A08203490482034530820341308203" + "3D060B2A864886F70D010C0A0102A08202B6308202B2301C060A2A864886F70D" + "010C0103300E04085052002C7DA2C2A6020207D0048202907D485E3BFC6E6457" + "C811394C145D0E8A18325646854E4FF0097BC5A98547F5AD616C8EFDA8505AA8" + "7564ED4800A3139759497C60C6688B51F376ACAE906429C8771CB1428226B68A" + "6297207BCC9DD7F9563478DD83880AAB2304B545759B2275305DF4EFF9FAC24A" + "3CC9D3B2D672EFE45D8F48E24A16506C1D7566FC6D1B269FBF201B3AC3309D3E" + "BC6FD606257A7A707AA2F790EA3FE7A94A51138540C5319010CBA6DE9FB9D85F" + "CDC78DA60E33DF2F21C46FB9A8554B4F82E0A6EDBA4DB5585D77D331D35DAAED" + "51B6A5A3E000A299880FB799182C8CA3004B7837A9FEB8BFC76778089993F3D1" + "1D70233608AF7C50722D680623D2BF54BD4B1E7A604184D9F44E0AF8099FFA47" + "1E5536E7902793829DB9902DDB61264A62962950AD274EA516B2D44BE9036530" + "016E607B73F341AEEFED2211F6330364738B435B0D2ED6C57747F6C8230A053F" + "78C4DD65DB83B26C6A47836A6CBBAB92CBB262C6FB6D08632B4457F5FA8EABFA" + "65DB34157E1D301E9085CC443582CDD15404314872748545EB3FC3C574882655" + "8C9A85F966E315775BBE9DA34D1E8B6DADC3C9E120C6D6A2E1CFFE4EB014C3CE" + "FBC19356CE33DAC60F93D67A4DE247B0DAE13CD8B8C9F15604CC0EC9968E3AD7" + "F57C9F53C45E2ECB0A0945EC0BA04BAA15B48D8596EDC9F5FE9165A5D21949FB" + "5FE30A920AD2C0F78799F6443C300629B8CA4DCA19B9DBF1E27AAB7B12271228" + "119A95C9822BE6439414BEEAE24002B46EB97E030E18BD810ADE0BCF4213A355" + "038B56584B2FBCC3F5EA215D0CF667FFD823EA03AB62C3B193DFB4450AABB50B" + "AF306E8088EE7384FA2FDFF03E0DD7ACD61832223E806A94D46E196462522808" + "3163F1CAF333FDBBE2D54CA86968867CE0B6DD5E5B7F0633C6FAB4A19CC14F64" + "5EC14D0B1436F7623174301306092A864886F70D010915310604040100000030" + "5D06092B060104018237110131501E4E004D006900630072006F0073006F0066" + "00740020005300740072006F006E0067002000430072007900700074006F0067" + "007200610070006800690063002000500072006F007600690064006500723082" + "027F06092A864886F70D010706A08202703082026C0201003082026506092A86" + "4886F70D010701301C060A2A864886F70D010C0106300E0408E0C117E67A75D8" + "EB020207D080820238292882408B31826F0DC635F9BBE7C199A48A3B4FEFC729" + "DBF95508D6A7D04805A8DD612427F93124F522AC7D3C6F4DDB74D937F57823B5" + "B1E8CFAE4ECE4A1FFFD801558D77BA31985AA7F747D834CBE84464EF777718C9" + "865C819D6C9DAA0FA25E2A2A80B3F2AAA67D40E382EB084CCA85E314EA40C3EF" + "3ED1593904D7A16F37807C99AF06C917093F6C5AAEBB12A6C58C9956D4FBBDDE" + "1F1E389989C36E19DD38D4B978D6F47131E458AB68E237E40CB6A87F21C8773D" + "E845780B50995A51F041106F47C740B3BD946038984F1AC9E91230616480962F" + "11B0683F8802173C596C4BD554642F51A76F9DFFF9053DEF7B3C3F759FC7EEAC" + "3F2386106C4B8CB669589E004FB235F0357EA5CF0B5A6FC78A6D941A3AE44AF7" + "B601B59D15CD1EC61BCCC481FBB83EAE2F83153B41E71EF76A2814AB59347F11" + "6AB3E9C1621668A573013D34D13D3854E604286733C6BAD0F511D7F8FD6356F7" + "C3198D0CB771AF27F4B5A3C3B571FDD083FD68A9A1EEA783152C436F7513613A" + "7E399A1DA48D7E55DB7504DC47D1145DF8D7B6D32EAA4CCEE06F98BB3DDA2CC0" + "D0564A962F86DFB122E4F7E2ED6F1B509C58D4A3B2D0A68788F7E313AECFBDEF" + "456C31B96FC13586E02AEB65807ED83BB0CB7C28F157BC95C9C593C919469153" + "9AE3C620ED1D4D4AF0177F6B9483A5341D7B084BC5B425AFB658168EE2D8FB2B" + "FAB07A3BA061687A5ECD1F8DA9001DD3E7BE793923094ABB0F2CF4D24CB071B9" + "E568B18336BB4DC541352C9785C48D0F0E53066EB2009EFCB3E5644ED12252C1" + "BC303B301F300706052B0E03021A04144DEAB829B57A3156AEBC8239C0E7E884" + "EFD96E680414E147930B932899741C92D7652268938770254A2B020207D0").HexToByteArray(); public static byte[] StoreSavedAsPfxData = ( "3082070406092a864886f70d010702a08206f5308206f10201013100300b0609" + "2a864886f70d010701a08206d9308201e530820152a0030201020210d5b5bc1c" + "458a558845bff51cb4dff31c300906052b0e03021d05003011310f300d060355" + "040313064d794e616d65301e170d3130303430313038303030305a170d313130" + "3430313038303030305a3011310f300d060355040313064d794e616d6530819f" + "300d06092a864886f70d010101050003818d0030818902818100b11e30ea8742" + "4a371e30227e933ce6be0e65ff1c189d0d888ec8ff13aa7b42b68056128322b2" + "1f2b6976609b62b6bc4cf2e55ff5ae64e9b68c78a3c2dacc916a1bc7322dd353" + "b32898675cfb5b298b176d978b1f12313e3d865bc53465a11cca106870a4b5d5" + "0a2c410938240e92b64902baea23eb093d9599e9e372e48336730203010001a3" + "46304430420603551d01043b3039801024859ebf125e76af3f0d7979b4ac7a96" + "a1133011310f300d060355040313064d794e616d658210d5b5bc1c458a558845" + "bff51cb4dff31c300906052b0e03021d0500038181009bf6e2cf830ed485b86d" + "6b9e8dffdcd65efc7ec145cb9348923710666791fcfa3ab59d689ffd7234b787" + "2611c5c23e5e0714531abadb5de492d2c736e1c929e648a65cc9eb63cd84e57b" + "5909dd5ddf5dbbba4a6498b9ca225b6e368b94913bfc24de6b2bd9a26b192b95" + "7304b89531e902ffc91b54b237bb228be8afcda26476308204ec308203d4a003" + "020102021333000000b011af0a8bd03b9fdd0001000000b0300d06092a864886" + "f70d01010505003079310b300906035504061302555331133011060355040813" + "0a57617368696e67746f6e3110300e060355040713075265646d6f6e64311e30" + "1c060355040a13154d6963726f736f667420436f72706f726174696f6e312330" + "210603550403131a4d6963726f736f667420436f6465205369676e696e672050" + "4341301e170d3133303132343232333333395a170d3134303432343232333333" + "395a308183310b3009060355040613025553311330110603550408130a576173" + "68696e67746f6e3110300e060355040713075265646d6f6e64311e301c060355" + "040a13154d6963726f736f667420436f72706f726174696f6e310d300b060355" + "040b13044d4f5052311e301c060355040313154d6963726f736f667420436f72" + "706f726174696f6e30820122300d06092a864886f70d01010105000382010f00" + "3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" + "407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" + "137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" + "b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" + "109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" + "2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" + "2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" + "84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" + "0b950005b14f6571c50203010001a38201603082015c30130603551d25040c30" + "0a06082b06010505070303301d0603551d0e041604145971a65a334dda980780" + "ff841ebe87f9723241f230510603551d11044a3048a4463044310d300b060355" + "040b13044d4f5052313330310603550405132a33313539352b34666166306237" + "312d616433372d346161332d613637312d373662633035323334346164301f06" + "03551d23041830168014cb11e8cad2b4165801c9372e331616b94c9a0a1f3056" + "0603551d1f044f304d304ba049a0478645687474703a2f2f63726c2e6d696372" + "6f736f66742e636f6d2f706b692f63726c2f70726f64756374732f4d6963436f" + "645369675043415f30382d33312d323031302e63726c305a06082b0601050507" + "0101044e304c304a06082b06010505073002863e687474703a2f2f7777772e6d" + "6963726f736f66742e636f6d2f706b692f63657274732f4d6963436f64536967" + "5043415f30382d33312d323031302e637274300d06092a864886f70d01010505" + "00038201010031d76e2a12573381d59dc6ebf93ad4444d089eee5edf6a5bb779" + "cf029cbc76689e90a19c0bc37fa28cf14dba9539fb0de0e19bf45d240f1b8d88" + "153a7cdbadceb3c96cba392c457d24115426300d0dff47ea0307e5e4665d2c7b" + "9d1da910fa1cb074f24f696b9ea92484daed96a0df73a4ef6a1aac4b629ef17c" + "c0147f48cd4db244f9f03c936d42d8e87ce617a09b68680928f90297ef1103ba" + "6752adc1e9b373a6d263cd4ae23ee4f34efdffa1e0bb02133b5d20de553fa3ae" + "9040313875285e04a9466de6f57a7940bd1fcde845d5aee25d3ef575c7e66663" + "60ccd59a84878d2430f7ef34d0631db142674a0e4bbf3a0eefb6953aa738e425" + "9208a68866823100").HexToByteArray(); public static byte[] StoreSavedAsCerData = ( "308201e530820152a0030201020210d5b5bc1c458a558845bff51cb4dff31c30" + "0906052b0e03021d05003011310f300d060355040313064d794e616d65301e17" + "0d3130303430313038303030305a170d3131303430313038303030305a301131" + "0f300d060355040313064d794e616d6530819f300d06092a864886f70d010101" + "050003818d0030818902818100b11e30ea87424a371e30227e933ce6be0e65ff" + "1c189d0d888ec8ff13aa7b42b68056128322b21f2b6976609b62b6bc4cf2e55f" + "f5ae64e9b68c78a3c2dacc916a1bc7322dd353b32898675cfb5b298b176d978b" + "1f12313e3d865bc53465a11cca106870a4b5d50a2c410938240e92b64902baea" + "23eb093d9599e9e372e48336730203010001a346304430420603551d01043b30" + "39801024859ebf125e76af3f0d7979b4ac7a96a1133011310f300d0603550403" + "13064d794e616d658210d5b5bc1c458a558845bff51cb4dff31c300906052b0e" + "03021d0500038181009bf6e2cf830ed485b86d6b9e8dffdcd65efc7ec145cb93" + "48923710666791fcfa3ab59d689ffd7234b7872611c5c23e5e0714531abadb5d" + "e492d2c736e1c929e648a65cc9eb63cd84e57b5909dd5ddf5dbbba4a6498b9ca" + "225b6e368b94913bfc24de6b2bd9a26b192b957304b89531e902ffc91b54b237" + "bb228be8afcda26476").HexToByteArray(); public static byte[] StoreSavedAsSerializedCerData = ( "0200000001000000bc0000001c0000006c000000010000000000000000000000" + "00000000020000007b00370037004500420044003000320044002d0044003800" + "440045002d0034003700350041002d0038003800360037002d00440032003000" + "4200300030003600340045003400390046007d00000000004d00690063007200" + "6f0073006f006600740020005300740072006f006e0067002000430072007900" + "700074006f0067007200610070006800690063002000500072006f0076006900" + "64006500720000002000000001000000e9010000308201e530820152a0030201" + "020210d5b5bc1c458a558845bff51cb4dff31c300906052b0e03021d05003011" + "310f300d060355040313064d794e616d65301e170d3130303430313038303030" + "305a170d3131303430313038303030305a3011310f300d060355040313064d79" + "4e616d6530819f300d06092a864886f70d010101050003818d00308189028181" + "00b11e30ea87424a371e30227e933ce6be0e65ff1c189d0d888ec8ff13aa7b42" + "b68056128322b21f2b6976609b62b6bc4cf2e55ff5ae64e9b68c78a3c2dacc91" + "6a1bc7322dd353b32898675cfb5b298b176d978b1f12313e3d865bc53465a11c" + "ca106870a4b5d50a2c410938240e92b64902baea23eb093d9599e9e372e48336" + "730203010001a346304430420603551d01043b3039801024859ebf125e76af3f" + "0d7979b4ac7a96a1133011310f300d060355040313064d794e616d658210d5b5" + "bc1c458a558845bff51cb4dff31c300906052b0e03021d0500038181009bf6e2" + "cf830ed485b86d6b9e8dffdcd65efc7ec145cb9348923710666791fcfa3ab59d" + "689ffd7234b7872611c5c23e5e0714531abadb5de492d2c736e1c929e648a65c" + "c9eb63cd84e57b5909dd5ddf5dbbba4a6498b9ca225b6e368b94913bfc24de6b" + "2bd9a26b192b957304b89531e902ffc91b54b237bb228be8afcda26476").HexToByteArray(); public static byte[] StoreSavedAsSerializedStoreData = ( "00000000434552540200000001000000bc0000001c0000006c00000001000000" + "000000000000000000000000020000007b003700370045004200440030003200" + "44002d0044003800440045002d0034003700350041002d003800380036003700" + "2d004400320030004200300030003600340045003400390046007d0000000000" + "4d006900630072006f0073006f006600740020005300740072006f006e006700" + "2000430072007900700074006f00670072006100700068006900630020005000" + "72006f007600690064006500720000002000000001000000e9010000308201e5" + "30820152a0030201020210d5b5bc1c458a558845bff51cb4dff31c300906052b" + "0e03021d05003011310f300d060355040313064d794e616d65301e170d313030" + "3430313038303030305a170d3131303430313038303030305a3011310f300d06" + "0355040313064d794e616d6530819f300d06092a864886f70d01010105000381" + "8d0030818902818100b11e30ea87424a371e30227e933ce6be0e65ff1c189d0d" + "888ec8ff13aa7b42b68056128322b21f2b6976609b62b6bc4cf2e55ff5ae64e9" + "b68c78a3c2dacc916a1bc7322dd353b32898675cfb5b298b176d978b1f12313e" + "3d865bc53465a11cca106870a4b5d50a2c410938240e92b64902baea23eb093d" + "9599e9e372e48336730203010001a346304430420603551d01043b3039801024" + "859ebf125e76af3f0d7979b4ac7a96a1133011310f300d060355040313064d79" + "4e616d658210d5b5bc1c458a558845bff51cb4dff31c300906052b0e03021d05" + "00038181009bf6e2cf830ed485b86d6b9e8dffdcd65efc7ec145cb9348923710" + "666791fcfa3ab59d689ffd7234b7872611c5c23e5e0714531abadb5de492d2c7" + "36e1c929e648a65cc9eb63cd84e57b5909dd5ddf5dbbba4a6498b9ca225b6e36" + "8b94913bfc24de6b2bd9a26b192b957304b89531e902ffc91b54b237bb228be8" + "afcda264762000000001000000f0040000308204ec308203d4a0030201020213" + "33000000b011af0a8bd03b9fdd0001000000b0300d06092a864886f70d010105" + "05003079310b3009060355040613025553311330110603550408130a57617368" + "696e67746f6e3110300e060355040713075265646d6f6e64311e301c06035504" + "0a13154d6963726f736f667420436f72706f726174696f6e3123302106035504" + "03131a4d6963726f736f667420436f6465205369676e696e6720504341301e17" + "0d3133303132343232333333395a170d3134303432343232333333395a308183" + "310b3009060355040613025553311330110603550408130a57617368696e6774" + "6f6e3110300e060355040713075265646d6f6e64311e301c060355040a13154d" + "6963726f736f667420436f72706f726174696f6e310d300b060355040b13044d" + "4f5052311e301c060355040313154d6963726f736f667420436f72706f726174" + "696f6e30820122300d06092a864886f70d01010105000382010f003082010a02" + "82010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb407db38e33" + "e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb137688b02c" + "f0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bbab95c759316" + "524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1109d772285" + "847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd2f826a8103" + "f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c4252e2aae9d18" + "1f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b280184b82a29cf" + "bfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec6430b950005b1" + "4f6571c50203010001a38201603082015c30130603551d25040c300a06082b06" + "010505070303301d0603551d0e041604145971a65a334dda980780ff841ebe87" + "f9723241f230510603551d11044a3048a4463044310d300b060355040b13044d" + "4f5052313330310603550405132a33313539352b34666166306237312d616433" + "372d346161332d613637312d373662633035323334346164301f0603551d2304" + "1830168014cb11e8cad2b4165801c9372e331616b94c9a0a1f30560603551d1f" + "044f304d304ba049a0478645687474703a2f2f63726c2e6d6963726f736f6674" + "2e636f6d2f706b692f63726c2f70726f64756374732f4d6963436f6453696750" + "43415f30382d33312d323031302e63726c305a06082b06010505070101044e30" + "4c304a06082b06010505073002863e687474703a2f2f7777772e6d6963726f73" + "6f66742e636f6d2f706b692f63657274732f4d6963436f645369675043415f30" + "382d33312d323031302e637274300d06092a864886f70d010105050003820101" + "0031d76e2a12573381d59dc6ebf93ad4444d089eee5edf6a5bb779cf029cbc76" + "689e90a19c0bc37fa28cf14dba9539fb0de0e19bf45d240f1b8d88153a7cdbad" + "ceb3c96cba392c457d24115426300d0dff47ea0307e5e4665d2c7b9d1da910fa" + "1cb074f24f696b9ea92484daed96a0df73a4ef6a1aac4b629ef17cc0147f48cd" + "4db244f9f03c936d42d8e87ce617a09b68680928f90297ef1103ba6752adc1e9" + "b373a6d263cd4ae23ee4f34efdffa1e0bb02133b5d20de553fa3ae9040313875" + "285e04a9466de6f57a7940bd1fcde845d5aee25d3ef575c7e6666360ccd59a84" + "878d2430f7ef34d0631db142674a0e4bbf3a0eefb6953aa738e4259208a68866" + "82000000000000000000000000").HexToByteArray(); public static byte[] DssCer = ( "3082025d3082021da00302010202101e9ae1e91e07de8640ac7af21ac22e8030" + "0906072a8648ce380403300e310c300a06035504031303466f6f301e170d3135" + "303232343232313734375a170d3136303232343232313734375a300e310c300a" + "06035504031303466f6f308201b73082012c06072a8648ce3804013082011f02" + "818100871018cc42552d14a5a9286af283f3cfba959b8835ec2180511d0dceb8" + "b979285708c800fc10cb15337a4ac1a48ed31394072015a7a6b525986b49e5e1" + "139737a794833c1aa1e0eaaa7e9d4efeb1e37a65dbc79f51269ba41e8f0763aa" + "613e29c81c3b977aeeb3d3c3f6feb25c270cdcb6aee8cd205928dfb33c44d2f2" + "dbe819021500e241edcf37c1c0e20aadb7b4e8ff7aa8fde4e75d02818100859b" + "5aeb351cf8ad3fabac22ae0350148fd1d55128472691709ec08481584413e9e5" + "e2f61345043b05d3519d88c021582ccef808af8f4b15bd901a310fefd518af90" + "aba6f85f6563db47ae214a84d0b7740c9394aa8e3c7bfef1beedd0dafda079bf" + "75b2ae4edb7480c18b9cdfa22e68a06c0685785f5cfb09c2b80b1d05431d0381" + "8400028180089a43f439b924bef3529d8d6206d1fca56a55caf52b41d6ce371e" + "bf07bda132c8eadc040007fcf4da06c1f30504ebd8a77d301f5a4702f01f0d2a" + "0707ac1da38dd3251883286e12456234da62eda0df5fe2fa07cd5b16f3638bec" + "ca7786312da7d3594a4bb14e353884da0e9aecb86e3c9bdb66fca78ea85e1cc3" + "f2f8bf0963300906072a8648ce380403032f00302c021461f6d143a47a4f7e0e" + "0ef9848b7f83eacbf83ffd021420e2ac47e656874633e01b0d207a99280c1127" + "01").HexToByteArray(); public static byte[] CertWithPolicies = ( "308201f33082015ca0030201020210134fb7082cf69bbb4930bfc8e1ca446130" + "0d06092a864886f70d0101050500300e310c300a06035504031303466f6f301e" + "170d3135303330313232343735385a170d3136303330313034343735385a300e" + "310c300a06035504031303466f6f30819f300d06092a864886f70d0101010500" + "03818d0030818902818100c252d52fb96658ddbb7d19dd9caaf203ec0376f77c" + "3012bd93e14bb22a6ff2b5ce8060a197e3fd8289fbff826746baae0db8d68b47" + "a1cf13678717d7db9a16dab028927173a3e843b3a7df8c5a4ff675957ea20703" + "6389a60a83d643108bd1293e2135a672a1cff10b7d5b3c78ab44d35e20ca6a5c" + "5b6f714c5bfd66ed4307070203010001a3523050301b06092b06010401823714" + "02040e1e0c00480065006c006c006f0000301a06092b0601040182371507040d" + "300b060357080902010302010230150603551d20040e300c3004060262133004" + "06027021300d06092a864886f70d0101050500038181001be04e59fbea63acfb" + "c8b6fd3d02dd7442532344cfbc124e924c0bacf23865e4ce2f442ad60ae457d8" + "4f7a1f05d50fb867c20e778e412a25237054555669ced01c1ce1ba8e8e57510f" + "73e1167c920f78aa5415dc5281f0c761fb25bb1ebc707bc003dd90911e649915" + "918cfe4f3176972f8afdc1cccd9705e7fb307a0c17d273").HexToByteArray(); public static byte[] CertWithTemplateData = ( "308201dc30820145a00302010202105101b8242daf6cae4c53bac68a948b0130" + "0d06092a864886f70d0101050500300e310c300a06035504031303466f6f301e" + "170d3135303330313232333133395a170d3136303330313034333133395a300e" + "310c300a06035504031303466f6f30819f300d06092a864886f70d0101010500" + "03818d0030818902818100a6dcff50bd1fe420301fea5fa56be93a7a53f2599c" + "e453cf3422bec797bac0ed78a03090a3754569e6494bcd585ac16a5ea5086344" + "3f25521085ca09580579cf0b46bd6e50015319fba5d2bd3724c53b20cdddf604" + "74bd7ef426aead9ca5ffea275a4b2b1b6f87c203ab8783559b75e319722886fb" + "eb784f5f06823906b2a9950203010001a33b3039301b06092b06010401823714" + "02040e1e0c00480065006c006c006f0000301a06092b0601040182371507040d" + "300b0603570809020103020102300d06092a864886f70d010105050003818100" + "962594da079523c26e2d3fc573fd17189ca33bedbeb2c38c92508fc2a865973b" + "e85ba686f765101aea0a0391b22fcfa6c0760eece91a0eb75501bf6871553f8d" + "6b089cf2ea63c872e0b4a178795b71826c4569857b45994977895e506dfb8075" + "ed1b1096987f2c8f65f2d6bbc788b1847b6ba13bee17ef6cb9c6a3392e13003f").HexToByteArray(); public static byte[] ComplexNameInfoCert = ( "308204BE30820427A00302010202080123456789ABCDEF300D06092A864886F70" + "D01010505003081A43110300E06035504061307436F756E747279310E300C0603" + "550408130553746174653111300F060355040713084C6F63616C6974793111300" + "F060355040A13084578616D706C654F31123010060355040B13094578616D706C" + "654F55311E301C06035504031315636E2E6973737565722E6578616D706C652E6" + "F72673126302406092A864886F70D0109011617697373756572656D61696C4065" + "78616D706C652E6F7267301E170D3133313131323134313531365A170D3134313" + "231333135313631375A3081A63110300E06035504061307436F756E747279310E" + "300C0603550408130553746174653111300F060355040713084C6F63616C69747" + "93111300F060355040A13084578616D706C654F31123010060355040B13094578" + "616D706C654F55311F301D06035504031316636E2E7375626A6563742E6578616" + "D706C652E6F72673127302506092A864886F70D01090116187375626A65637465" + "6D61696C406578616D706C652E6F7267305C300D06092A864886F70D010101050" + "0034B003048024100DC6FBBDA0300520DFBC9F046CC865D8876AEAC353807EA84" + "F58F92FE45EE03C22E970CAF41031D47F97C8A5117C62718482911A8A31B58D92" + "328BA3CF9E605230203010001A382023730820233300B0603551D0F0404030200" + "B0301D0603551D250416301406082B0601050507030106082B060105050703023" + "081FD0603551D120481F53081F28217646E73312E6973737565722E6578616D70" + "6C652E6F72678217646E73322E6973737565722E6578616D706C652E6F7267811" + "569616E656D61696C31406578616D706C652E6F7267811569616E656D61696C32" + "406578616D706C652E6F7267A026060A2B060104018237140203A0180C1669737" + "375657275706E31406578616D706C652E6F7267A026060A2B0601040182371402" + "03A0180C1669737375657275706E32406578616D706C652E6F7267861F6874747" + "03A2F2F757269312E6973737565722E6578616D706C652E6F72672F861F687474" + "703A2F2F757269322E6973737565722E6578616D706C652E6F72672F308201030" + "603551D110481FB3081F88218646E73312E7375626A6563742E6578616D706C65" + "2E6F72678218646E73322E7375626A6563742E6578616D706C652E6F726781157" + "3616E656D61696C31406578616D706C652E6F7267811573616E656D61696C3240" + "6578616D706C652E6F7267A027060A2B060104018237140203A0190C177375626" + "A65637475706E31406578616D706C652E6F7267A027060A2B0601040182371402" + "03A0190C177375626A65637475706E32406578616D706C652E6F7267862068747" + "4703A2F2F757269312E7375626A6563742E6578616D706C652E6F72672F862068" + "7474703A2F2F757269322E7375626A6563742E6578616D706C652E6F72672F300" + "D06092A864886F70D0101050500038181005CD44A247FF4DFBF2246CC04D7D57C" + "EF2B6D3A4BC83FF685F6B5196B65AFC8F992BE19B688E53E353EEA8B63951EC40" + "29008DE8B851E2C30B6BF73F219BCE651E5972E62D651BA171D1DA9831A449D99" + "AF4E2F4B9EE3FD0991EF305ADDA633C44EB5E4979751280B3F54F9CCD561AC27D" + "3426BC6FF32E8E1AAF9F7C0150A726B").HexToByteArray(); internal static readonly byte[] MultiPrivateKeyPfx = ( "30820F1602010330820ED606092A864886F70D010701A0820EC704820EC33082" + "0EBF308206A806092A864886F70D010701A08206990482069530820691308203" + "4C060B2A864886F70D010C0A0102A08202B6308202B2301C060A2A864886F70D" + "010C0103300E0408ED42EEFCD77BB2EB020207D00482029048F341D409492D23" + "D89C0C01DEE7EFFB6715B15D2BB558E9045D635CADFFFEC85C10A4849AB0657D" + "A17FE7EC578F779BA2DC129FA959664DC7E85DFD13CAC673E487208FE457223A" + "75732915FFCF3FF70F557B0846D62AD507300EA1770EDED82F7D8E6E75075728" + "A29D3BF829E75F09EF283A9DDEDDFBABC2E25698DA8C24E4FE34CD43C87554BF" + "55B1D4B2B0979F399AEC95B781C62CBE9E412329F9A9BCABF20F716A95F1D795" + "7C379A27587F6BBFA44A0B75FAAC15CA3730629C55E87990EE521BC4657EE2A4" + "41AF099A226D31707685A89A28EB27CA65512B70DEC09231369AA1A265D4F5C3" + "C5D17CB11DB54C70AB83EA28F4740D1F79D490F46F926FB267D5F0E4B2FE096D" + "F161A4FF9E9AC068EFCA999B3ED0A3BD05D8D1E3B67CF51E6A478154B427D87D" + "C861D0FE2A7A42600483D7B979DC71E8A00D0E805E3BB86E8673234DC1D14987" + "99272754A5FD5FEC118CF1E2B2A539B604FED5486A4E4D73FAAFF69023263B84" + "6870D6B8DB01E31CB3A1E4BA3588C1FA81C786745A33B95573D5381AB307827A" + "549A36AF535FD05E1247BB92C6C6FCB0E76E87F2E4C8136F37C9C19BE3001F59" + "FC5CB459C620B8E73711BF102D78F665F40E4D1A341370BC1FB7A5567C29359C" + "FFB938237002904BE59F5605AF96E8A670E2248AB71D27FE63E327077144F095" + "4CA815E0284E2FF5E1A11B2946276A99B91BF138A79B057436798AF72FD86842" + "881C5A5ECDA8A961A21553CC930703047F1F45699CEFEF26AAB6B7DBC65C8C62" + "4CA3286094596F2AA48268B9F5411058613185507332833AFB312D5780CEFF96" + "6DD05A2CB6E1B252D9656D8E92E63E6C0360F119232E954E11DE777D2DE1C208" + "F704DDB16E1351F49B42A859E3B6B2D94E1E2B3CD97F06B1123E9CCA049201E6" + "DB7273C0BDE63CC9318182301306092A864886F70D0109153106040401000000" + "306B06092B0601040182371101315E1E5C004D006900630072006F0073006F00" + "66007400200045006E00680061006E0063006500640020004300720079007000" + "74006F0067007200610070006800690063002000500072006F00760069006400" + "650072002000760031002E00303082033D060B2A864886F70D010C0A0102A082" + "02B6308202B2301C060A2A864886F70D010C0103300E04081F85B7ED57F6F934" + "020207D00482029051A5ADA683AAE06A699761CCF05CB081A4398A7B1256A250" + "84DBE1115BFAB07A5A9146BC22F2E4223FF25BCA1836AE218691815F20A27A1B" + "98D1FC78F84AFA7E90A55954EE5BEA47FFA35928A990CB47346767F6F4212DBC" + "D03FFF1E4D137979006B46B19A9FC3BC9B5036ED6F8582E2007D08DB94B2B576" + "E154719CAC90DFB6F238CA875FCBEBCF9E9F933E4451E6A2B60C2A0A8A35B5FD" + "20E5DDA000008DCCE95BBDF604A8F93001F594E402FF8649A6582DE5901EDF9D" + "ED7D6F9657C5A184D82690EFCFB2F25BFCE02BC56F0FF00595996EBF1BA25475" + "AB613461280DD641186237D8A3AB257BD6FB1BDC3768B00719D233E0D5FD26D0" + "8BA6EAB29D732B990FB9423E643E4663ABBA0D8885DD2A276EE02C92778261C7" + "853F708E2B9AF8D2E96416F676D0191BD24D0C8430BD419049F43C8E2A0C32F8" + "62207B3DA661577CE5933460D0EF69FAD7323098B55FEF3A9955FE632FBCE845" + "2BB5F3430AE2A9021EBF756CC7FDFC3E63581C8B0D7AB77760F447F868B59236" + "14DAA9C36AEBC67DC854B93C38E8A6D3AC11B1EE1D02855CE96ADEB840B626BF" + "C4B3BFD6487C9073F8A15F55BA945D58AD1636A7AED476EBDB5227A71144BF87" + "45192EF5CD177818F61836717ED9EB0A83BEEE582ADEDD407035E453083B17E7" + "C237009D9F04F355CEAB0C0E9AD6F13A3B54459FA05B19E02275FE2588258B63" + "A125F549D1B44C827CDC94260A02F4A1B42A30E675B9760D876685D6CA05C258" + "03BDE1F33D325CF6020A662B0F5DCCC8D77B941B273AC462F0D3E050CEB5AEF7" + "107C45372F7063EF1AB420CA555A6C9BE6E1067966755584346CDDE7C05B6132" + "E553B11C374DB90B54E5C096062349A1F6CB78A1A2D995C483541750CFA956DE" + "A0EB3667DE7AD78931C65B6E039B5DE461810B68C344D2723174301306092A86" + "4886F70D0109153106040402000000305D06092B060104018237110131501E4E" + "004D006900630072006F0073006F006600740020005300740072006F006E0067" + "002000430072007900700074006F006700720061007000680069006300200050" + "0072006F007600690064006500723082080F06092A864886F70D010706A08208" + "00308207FC020100308207F506092A864886F70D010701301C060A2A864886F7" + "0D010C0106300E04089ADEE71816BCD023020207D0808207C851AA1EA533FECA" + "BB26D3846FAEE8DEDB919C29F8B98BBBF785BC306C12A8ACB1437786C4689161" + "683718BB7E40EB60D9BE0C87056B5ECF20ACCB8BF7F36033B8FCB84ED1474E97" + "DE0A8709B563B6CF8E69DF4B3F970C92324946723C32D08B7C3A76C871C6B6C8" + "C56F2D3C4C00B8A809E65A4EB5EFECC011E2B10F0E44ECDA07B325417B249240" + "80844F6D7F1F6E420346EA85825EB830C7E05A5383412A9502A51F1AC07F315A" + "DE357F1F9FB2E6427976E78B8FF9CD6C2F9841F2D84658AC8747694EFD0C451B" + "7AC5B83D5F0780808417501666BB452B53CEB0698162D94541DE181A7968DB13" + "9F17A1076EDEB70B38B8881DBC6DE2B694070A5A1AA71E4CDFBF7F4D5DBCF166" + "46768364D3C74FA212E40CBE3BE7C51A74D271164D00E89F997FD418C51A7C2D" + "73130D7C6FCAA2CA65082CE38BFB753BB30CC71656529E8DBA4C4D0B7E1A79CF" + "2A052FFEFA2DEE3373115472AFD1F40A80B23AA6141D5CDE0A378FE6210D4EE6" + "9B8771D3E192FD989AEC14C26EA4845D261B8A45ABC1C8FA305449DCDEDA9882" + "DD4DDC69B2DE315645FBC3EE52090907E7687A22A63F538E030AB5A5413CA415" + "F1D70E70CB567261FB892A8B3BAFC72D632CD2FDCC0559E01D5C246CC27C9348" + "63CCFA52490E1F01D8D2D0AF2587E4D04011140A494FFA3CA42C5F645B94EE30" + "100DE019B27F66FFC035E49A65B2A3F6CB14EB1E2FFF1F25B5C87481BD8506F3" + "07E0B042A2C85B99ECA520B4AAC7DFF2B11C1213E4128A01765DDB27B867336B" + "8CCF148CE738465D46E7A0BEA466CD8BBCCE2E11B16E0F9D24FF2F2D7C9F8527" + "79ADBB818F87E4AFF7C21A9C2BC20D38209322A34B0B393B187C96583D3D73D9" + "440F994B2F320D3274848AB7167942179CFF725C2C7556CCC289A5E788C5B863" + "E6FCDD5E4B87E41458BEB3F43D14C7E5196C38CA36322F8B83064862178D5892" + "5AEF34F444A31A4FB18431D7D37C65ED519643BC7BD025F801390430022253AA" + "FCEA670726512C3532EA9F410DB8AA6628CC455E4AB3F478A6981DB9180B7A2A" + "24B365F37554CE04B08F22B3539D98BF9A1AC623BBF9A08DBEC951E9730C1318" + "02B2C40750AAE6A791B3219A96A5BAC7AE17A2F7EA02FF66D6FB36C2E6B6AB90" + "D821A6322BF3E8D82969756A474551DB9EAA8C587FC878F996F5FA1E1C39E983" + "F164B0A67897EB3755C378807FFDFE964C5C0F290784A08E8C925E85775A9B89" + "2E278F68C3C1DE72622AC10EA56D88C909EF4AC9F47ED61376737C1E43DBF0F8" + "9337F0684FA0B96E7A993EC328A6A5FBCDCB809ACBFDAE4ECE192A45480104ED" + "12820238AB6AC9C88CC9A82585FD29A81A7BC5BC591738A4D49A86D06B4E18BD" + "C83DFFAA60D8A0D4F70CC63D4E83812CB6753F3744545592D04223793E5B3051" + "25AAD8807A753D235769BD0280E2DE808B0CEE2B98B0F5562FF9EF68161A6B7E" + "08C8B105766EBCFC44AC858B1A89E34C099B194A8B24D1DBABC13909EFAF5B9A" + "9E77AEAF7DD9BE772FA01AB9518EB8864AE6D07D7DD7451797541D2F723BC71A" + "9C14ED1D811594E2C4A57017D4CB90FD82C195FA9B823DF1E2FFD965E3139F9A" + "6E8AAC36FA39CFA4C52E85D2A661F9D0D466720C5AB7ECDE968FF51B535B019A" + "3E9C76058E6F673A49CDD89EA7EC998BDADE71186EA084020A897A328753B72E" + "213A9D82443F7E34D94508199A2A63E71A12BD441C132201E9A3829B2727F23E" + "65C519F4DA2C40162A3A501B1BD57568ED75447FEAF8B42988CE25407644BFA0" + "B76059D275EC994BB336055E271751B32233D79A6E5E3AA700F3803CCA50586D" + "28934E3D4135FA043AF7DFAB977477283602B1739C4AF40E3856E75C34EB98C6" + "9A928ADE05B67A679630EFA14E64B2957EDD1AB4EC0B0E7BC38D4851EBF67928" + "33EACB62FB6C862B089E3066AE5EAAFD2A8B7FC712DE9BD2F488222EEB1FB91B" + "4E57C2D24092818965621C123280453EDCFA2EC9D9B50AFA437D1ED09EC36FD2" + "32B169ED301E0DB0BABE562B67130F90EBC85D325A90931A5B5A94736A4B3AAD" + "B8CA295F59AF7FF08CCFADE5AFBBC2346BC6D78D9E5F470E9BDFF547F2574B10" + "A48DD9D56B5B03E9E24D65C367B6E342A26A344111A66B1908EDAECD0834930D" + "A74E1CFE2E4B0636A7C18E51A27AD21992A2DCF466BAACAC227B90B5E61BED79" + "9C97DEE7EDB33CCAF5DAD7AAD3CACCDE59478CF69AE64B9065FCB436E1993514" + "C42872DD486ABB75A07A4ED46CDF0E12C0D73FAB83564CF1A814791971EC9C7C" + "6A08A13CE0453C2C3236C8B2E146D242E3D37A3ECF6C350D0B2AB956CB21057F" + "DC630750A71C61C66DE3D4A6DB187BEE2F86DEB93E723C5943EA17E699E93555" + "756920416BD6B267A4CFAC4EE90E96A6419302B4C0A3B9705509CA09EE92F184" + "FD2817BA09BE29E465909DB6C93E3C1CAF6DC29E1A5838F3C32CCB220235EF82" + "9CD21D1B3E960518A80D08AE7FF08D3AFB7451C823E9B8D49DAF66F503E4AE53" + "99FECFC958429D758C06EFF8338BC02457F6FE5053AA3C2F27D360058FD93566" + "3B55F026B504E39D86E7CE15F04B1C62BBFA0B1CA5E64FF0BD088D94FB1518E0" + "5B2F40BF9D71C61FC43E3AF8440570C44030F59D14B8858B7B8506B136E7E39B" + "B04F9AFEAF2FA292D28A8822046CEFDE381F2399370BDE9B97BC700418585C31" + "E9C353635ADAA6A00A833899D0EDA8F5FFC558D822AEB99C7E35526F5297F333" + "F9E758D4CD53277316608B1F7DB6AC71309A8542A356D407531BA1D3071BA9DC" + "02AE91C7DF2561AEBC3845A118B00D21913B4A401DDDC40CE983178EF26C4A41" + "343037301F300706052B0E03021A041454F0864331D9415EBA750C62FA93C97D" + "3402E1A40414B610EC75D16EA23BF253AAD061FAC376E1EAF684").HexToByteArray(); internal static readonly byte[] EmptyPfx = ( "304F020103301106092A864886F70D010701A004040230003037301F30070605" + "2B0E03021A0414822078BC83E955E314BDA908D76D4C5177CC94EB0414711018" + "F2897A44A90E92779CB655EA11814EC598").HexToByteArray(); internal const string ChainPfxPassword = "test"; internal static readonly byte[] ChainPfxBytes = ( "308213790201033082133506092A864886F70D010701A0821326048213223082" + "131E3082036706092A864886F70D010701A08203580482035430820350308203" + "4C060B2A864886F70D010C0A0102A08202B6308202B2301C060A2A864886F70D" + "010C0103300E040811E8B9808BA6E96C020207D004820290D11DA8713602105C" + "95792D65BCDFC1B7E3708483BF6CD83008082F89DAE4D003F86081B153BD4D4A" + "C122E802752DEA29F07D0B7E8F0FB8A762B4CAA63360F9F72CA5846771980A6F" + "AE2643CD412E6E4A101625371BBD48CC6E2D25191D256B531B06DB7CDAC04DF3" + "E10C6DC556D5FE907ABF32F2966A561C988A544C19B46DF1BE531906F2CC2263" + "A301302A857075C7A9C48A395241925C6A369B60D176419D75E320008D5EFD91" + "5257B160F6CD643953E85F19EBE4E4F72B9B787CF93E95F819D1E43EF01CCFA7" + "48F0E7260734EA9BC6039BA7557BE6328C0149718A1D9ECF3355082DE697B6CD" + "630A9C224D831B7786C7E904F1EF2D9D004E0E825DD74AC4A576CDFCA7CECD14" + "D8E2E6CCAA3A302871AE0BA979BB25559215D771FAE647905878E797BBA9FC62" + "50F30F518A8008F5A12B35CE526E31032B56EFE5A4121E1E39DC7339A0CE8023" + "24CDDB7E9497BA37D8B9F8D826F901C52708935B4CA5B0D4D760A9FB33B0442D" + "008444D5AEB16E5C32187C7038F29160DD1A2D4DB1F9E9A6C035CF5BCED45287" + "C5DEBAB18743AAF90E77201FEA67485BA3BBCE90CEA4180C447EE588AC19C855" + "638B9552D47933D2760351174D9C3493DCCE9708B3EFE4BE398BA64051BF52B7" + "C1DCA44D2D0ED5A6CFB116DDA41995FA99373C254F3F3EBF0F0049F1159A8A76" + "4CFE9F9CC56C5489DD0F4E924158C9B1B626030CB492489F6AD0A9DCAF3E141D" + "B4D4821B2D8A384110B6B0B522F62A9DC0C1315A2A73A7F25F96C530E2F700F9" + "86829A839B944AE6758B8DD1A1E9257F91C160878A255E299C18424EB9983EDE" + "6DD1C5F4D5453DD5A56AC87DB1EFA0806E3DBFF10A9623FBAA0BAF352F50AB5D" + "B16AB1171145860D21E2AB20B45C8865B48390A66057DE3A1ABE45EA65376EF6" + "A96FE36285C2328C318182301306092A864886F70D0109153106040401000000" + "306B06092B0601040182371101315E1E5C004D006900630072006F0073006F00" + "66007400200045006E00680061006E0063006500640020004300720079007000" + "74006F0067007200610070006800690063002000500072006F00760069006400" + "650072002000760031002E003030820FAF06092A864886F70D010706A0820FA0" + "30820F9C02010030820F9506092A864886F70D010701301C060A2A864886F70D" + "010C0106300E0408FFCC41FD8C8414F6020207D080820F68092C6010873CF9EC" + "54D4676BCFB5FA5F523D03C981CB4A3DC096074E7D04365DDD1E80BF366B8F9E" + "C4BC056E8CE0CAB516B9C28D17B55E1EB744C43829D0E06217852FA99CCF5496" + "176DEF9A48967C1EEB4A384DB7783E643E35B5B9A50533B76B8D53581F02086B" + "782895097860D6CA512514E10D004165C85E561DF5F9AEFD2D89B64F178A7385" + "C7FA40ECCA899B4B09AE40EE60DAE65B31FF2D1EE204669EFF309A1C7C8D7B07" + "51AE57276D1D0FB3E8344A801AC5226EA4ED97FCD9399A4EB2E778918B81B17F" + "E4F65B502595195C79E6B0E37EB8BA36DB12435587E10037D31173285D45304F" + "6B0056512B3E147D7B5C397709A64E1D74F505D2BD72ED99055161BC57B6200F" + "2F48CF128229EFBEBFC2707678C0A8C51E3C373271CB4FD8EF34A1345696BF39" + "50E8CE9831F667D68184F67FE4D30332E24E5C429957694AF23620EA7742F08A" + "38C9A517A7491083A367B31C60748D697DFA29635548C605F898B64551A48311" + "CB2A05B1ACA8033128D48E4A5AA263D970FE59FBA49017F29049CF80FFDBD192" + "95B421FEFF6036B37D2F8DC8A6E36C4F5D707FB05274CC0D8D94AFCC8C6AF546" + "A0CF49FBD3A67FB6D20B9FE6FDA6321E8ABF5F7CC794CFCC46005DC57A7BAFA8" + "9954E43230402C8100789F11277D9F05C78DF0509ECFBF3A85114FD35F4F17E7" + "98D60C0008064E2557BA7BF0B6F8663A6C014E0220693AE29E2AB4BDE5418B61" + "0889EC02FF5480BD1B344C87D73E6E4DB98C73F881B22C7D298059FE9D7ADA21" + "92BB6C87F8D25F323A70D234E382F6C332FEF31BB11C37E41903B9A59ADEA5E0" + "CBAB06DFB835257ABC179A897DEAD9F19B7DF861BE94C655DC73F628E065F921" + "E5DE98FFCBDF2A54AC01E677E365DD8B932B5BDA761A0032CE2127AB2A2B9DCB" + "63F1EA8A51FC360AB5BC0AD435F21F9B6842980D795A6734FDB27A4FA8209F73" + "62DD632FC5FB1F6DE762473D6EA68BFC4BCF983865E66E6D93159EFACC40AB31" + "AA178806CF893A76CAAA3279C988824A33AF734FAF8E21020D988640FAB6DB10" + "DF21D93D01776EEA5DAECF695E0C690ED27AD386E6F2D9C9482EA38946008CCB" + "8F0BD08F9D5058CF8057CA3AD50BB537116A110F3B3ACD9360322DB4D242CC1A" + "6E15FA2A95192FC65886BE2672031D04A4FB0B1F43AE8476CF82638B61B416AA" + "97925A0110B736B4D83D7977456F35D947B3D6C9571D8E2DA0E9DEE1E665A844" + "259C17E01E044FAB898AA170F99157F7B525D524B01BD0710D23A7689A615703" + "8A0697BD48FFE0253ABD6F862093574B2FC9BA38E1A6EC60AF187F10D79FF71F" + "7C50E87A07CC0A51099899F7336FE742ADEF25E720B8E0F8781EC7957D414CF5" + "D44D6998E7E35D2433AFD86442CCA637A1513BE3020B5334614277B3101ED7AD" + "22AFE50DE99A2AD0E690596C93B881E2962D7E52EE0A770FAF6917106A8FF029" + "8DF38D6DE926C30834C5D96854FFD053BDB020F7827FB81AD04C8BC2C773B2A5" + "9FDD6DDF7298A052B3486E03FECA5AA909479DDC7FED972192792888F49C40F3" + "910140C5BE264D3D07BEBF3275117AF51A80C9F66C7028A2C3155414CF939997" + "268A1F0AA9059CC3AA7C8BBEF880187E3D1BA8978CBB046E43289A020CAE11B2" + "5140E2247C15A32CF70C7AA186CBB68B258CF2397D2971F1632F6EBC4846444D" + "E445673B942F1F110C7D586B6728ECA5B0A62D77696BF25E21ED9196226E5BDA" + "5A80ECCC785BEEDE917EBC6FFDC2F7124FE8F719B0A937E35E9A720BB9ED72D2" + "1213E68F058D80E9F8D7162625B35CEC4863BD47BC2D8D80E9B9048811BDD8CB" + "B70AB215962CD9C40D56AE50B7003630AE26341C6E243B3D12D5933F73F78F15" + "B014C5B1C36B6C9F410A77CA997931C8BD5CCB94C332F6723D53A4CCC630BFC9" + "DE96EFA7FDB66FA519F967D6A2DB1B4898BB188DEB98A41FFA7907AE7601DDE2" + "30E241779A0FDF551FB84D80AAEE3D979F0510CD026D4AE2ED2EFB7468418CCD" + "B3BD2A29CD7C7DC6419B4637412304D5DA2DC178C0B4669CA8330B9713A812E6" + "52E812135D807E361167F2A6814CEF2A8A9591EFE2C18216A517473B9C3BF2B7" + "51E47844893DA30F7DCD4222D1A55D570C1B6F6A99AD1F9213BA8F84C0B14A6D" + "ED6A26EAFF8F89DF733EEB44117DF0FD357186BA4A15BD5C669F60D6D4C34028" + "322D4DDF035302131AB6FD08683804CC90C1791182F1AE3281EE69DDBBCC12B8" + "1E60942FD082286B16BE27DC11E3BB0F18C281E02F3BA66E48C5FD8E8EA3B731" + "BDB12A4A3F2D9E1F833DD204372003532E1BB11298BDF5092F2959FC439E6BD2" + "DC6C37E3E775DCBE821B9CBB02E95D84C15E736CEA2FDDAD63F5CD47115B4AD5" + "5227C2A02886CD2700540EBFD5BF18DC5F94C5874972FD5424FE62B30500B1A8" + "7521EA3798D11970220B2BE7EFC915FCB7A6B8962F09ABA005861E839813EDA3" + "E59F70D1F9C277B73928DFFC84A1B7B0F78A8B001164EB0824F2510885CA269F" + "DCBB2C3AE91BDE91A8BBC648299A3EB626E6F4236CCE79E14C803498562BAD60" + "28F5B619125F80925A2D3B1A56790795D04F417003A8E9E53320B89D3A3109B1" + "9BB17B34CC9700DA138FABB5997EC34D0A44A26553153DBCFF8F6A1B5432B150" + "58F7AD87C6B37537796C95369DAD53BE5543D86D940892F93983153B4031D4FA" + "B25DAB02C1091ACC1DAE2118ABD26D19435CD4F1A02BDE1896236C174743BCA6" + "A33FB5429E627EB3FD9F513E81F7BD205B81AAE627C69CF227B043722FA05141" + "39347D202C9B7B4E55612FC27164F3B5F287F29C443793E22F6ED6D2F353ED82" + "A9F33EDBA8F5F1B2958F1D6A3943A9614E7411FDBCA597965CD08A8042307081" + "BAC5A070B467E52D5B91CA58F986C5A33502236B5BAE6DB613B1A408D16B29D3" + "560F1E94AD840CFA93E83412937A115ABF68322538DA8082F0192D19EAAA41C9" + "299729D487A9404ECDB6396DDA1534841EAE1E7884FA43574E213AE656116D9E" + "F7591AA7BDE2B44733DFE27AA59949E5DC0EE00FDF42130A748DDD0FB0053C1A" + "55986983C8B9CEAC023CAD7EDFFA1C20D3C437C0EF0FC9868D845484D8BE6538" + "EAADA6365D48BA776EE239ED045667B101E3798FE53E1D4B9A2ACBBE6AF1E5C8" + "8A3FB03AD616404013E249EC34458F3A7C9363E7772151119FE058BD0939BAB7" + "64A2E545B0B2FDAA650B7E849C8DD4033922B2CAE46D0461C04A2C87657CB4C0" + "FFBA23DED69D097109EC8BFDC25BB64417FEEB32842DE3EFEF2BF4A47F08B9FC" + "D1907BC899CA9DA604F5132FB420C8D142D132E7E7B5A4BD0EF4A56D9E9B0ACD" + "88F0E862D3F8F0440954879FFE3AA7AA90573C6BFDC6D6474C606ACA1CD94C1C" + "3404349DD83A639B786AFCDEA1779860C05400E0479708F4A9A0DD51429A3F35" + "FBD5FB9B68CECC1D585F3E35B7BBFC469F3EAEEB8020A6F0C8E4D1804A3EB32E" + "B3909E80B0A41571B23931E164E0E1D0D05379F9FD3BF51AF04D2BE78BDB84BD" + "787D419E85626297CB35FCFB6ED64042EAD2EBC17BB65677A1A33A5C48ADD280" + "237FB2451D0EFB3A3C32354222C7AB77A3C92F7A45B5FB10092698D88725864A" + "3685FBDD0DC741424FCCD8A00B928F3638150892CAAB535CC2813D13026615B9" + "9977F7B8240E914ACA0FF2DCB1A9274BA1F55DF0D24CCD2BAB7741C9EA8B1ECD" + "E97477C45F88F034FDF73023502944AEE1FF370260C576992826C4B2E5CE9924" + "84E3B85170FCCAC3413DC0FF6F093593219E637F699A98BD29E8EE4550C128CA" + "182680FDA3B10BC07625734EE8A8274B43B170FC3AEC9AA58CD92709D388E166" + "AB4ADFD5A4876DC47C17DE51FDD42A32AF672515B6A81E7ABECFE748912B321A" + "FD0CBF4880298DD79403900A4002B5B436230EB6E49192DF49FAE0F6B60EBA75" + "A54592587C141AD3B319129006367E9532861C2893E7A2D0D2832DF4377C3184" + "5CB02A1D020282C3D2B7F77221F71FEA7FF0A988FEF15C4B2F6637159EEC5752" + "D8A7F4AB971117666A977370E754A4EB0DC52D6E8901DC60FCD87B5B6EF9A91A" + "F8D9A4E11E2FFDAB55FC11AF6EEB5B36557FC8945A1E291B7FF8931BE4A57B8E" + "68F04B9D4A9A02FC61AE913F2E2DDBEE42C065F4D30F568834D5BB15FDAF691F" + "197EF6C25AE87D8E968C6D15351093AAC4813A8E7B191F77E6B19146F839A43E" + "2F40DE8BE28EB22C0272545BADF3BD396D383B8DA8388147100B347999DDC412" + "5AB0AA1159BC6776BD2BF51534C1B40522D41466F414BDE333226973BAD1E6D5" + "7639D30AD94BEA1F6A98C047F1CE1294F0067B771778D59E7C722C73C2FF100E" + "13603206A694BF0ED07303BE0655DC984CA29893FD0A088B122B67AABDC803E7" + "3E5729E868B1CA26F5D05C818D9832C70F5992E7D15E14F9775C6AD24907CF2F" + "211CF87167861F94DCF9E3D365CB600B336D93AD44B8B89CA24E59C1F7812C84" + "DBE3EE57A536ED0D4BF948F7662E5BCBBB388C72243CFCEB720852D5A4A52F01" + "8C2C087E4DB43410FE9ABA3A8EF737B6E8FFDB1AB9832EBF606ED5E4BD62A86B" + "BCAE115C67682EDEA93E7845D0D6962C146B411F7784545851D2F327BEC7E434" + "4D68F137CDA217A3F0FF3B752A34C3B5339C79CB8E1AC690C038E85D6FC13379" + "090198D3555394D7A2159A23BD5EEF06EB0BCC729BB29B5BE911D02DA78FDA56" + "F035E508C722139AD6F25A6C84BED0E98893370164B033A2B52BC40D9BF5163A" + "F9650AB55EABB23370492A7D3A87E17C11B4D07A7296273F33069C835FD208BA" + "8F989A3CF8659054E2CCCFB0C983531DC6590F27C4A1D2C3A780FE945F7E52BB" + "9FFD2E324640E3E348541A620CD62605BBDB284AF97C621A00D5D1D2C31D6BD6" + "1149137B8A0250BC426417A92445A52574E999FB9102C16671914A1542E92DDE" + "541B2A0457112AF936DA84707CADFEA43BFEDAE5F58859908640420948086E57" + "FFD1B867C241D40197CB0D4AD58BB69B3724772E0079406A1272858AAA620668" + "F696955102639F3E95CFFC637EAF8AB54F0B5B2131AB292438D06E15F3826352" + "DEDC653DA5A4AACE2BB97061A498F3B6789A2310471B32F91A6B7A9944DDBB70" + "31525B3AE387214DC85A1C7749E9168F41272680D0B3C331D61175F23B623EEC" + "40F984C35C831268036680DE0821E5DEE5BB250C6984775D49B7AF94057371DB" + "72F81D2B0295FC6A51BCD00A697649D4346FDD59AC0DFAF21BFCC942C23C6134" + "FFBA2ABABC141FF700B52C5B26496BF3F42665A5B71BAC7F0C19870BD9873890" + "239C578CDDD8E08A1B0A429312FB24F151A11E4D180359A7FA043E8155453F67" + "265CB2812B1C98C144E7675CFC86413B40E35445AE7710227D13DC0B5550C870" + "10B363C492DA316FB40D3928570BF71BF47638F1401549369B1255DB080E5DFA" + "18EA666B9ECBE5C9768C06B3FF125D0E94B98BB24B4FD44E770B78D7B336E021" + "4FD72E77C1D0BE9F313EDCD147957E3463C62E753C10BB98584C85871AAEA9D1" + "F397FE9F1A639ADE31D40EAB391B03B588B8B031BCAC6C837C61B06E4B745052" + "474D33531086519C39EDD6310F3079EB5AC83289A6EDCBA3DC97E36E837134F7" + "303B301F300706052B0E03021A0414725663844329F8BF6DECA5873DDD8C96AA" + "8CA5D40414DF1D90CD18B3FBC72226B3C66EC2CB1AB351D4D2020207D0").HexToByteArray(); internal static readonly byte[] Pkcs7ChainDerBytes = ( "30820E1606092A864886F70D010702A0820E0730820E030201013100300B0609" + "2A864886F70D010701A0820DEB3082050B30820474A003020102020A15EAA83A" + "000100009291300D06092A864886F70D010105050030818131133011060A0992" + "268993F22C6401191603636F6D31193017060A0992268993F22C64011916096D" + "6963726F736F667431143012060A0992268993F22C6401191604636F72703117" + "3015060A0992268993F22C64011916077265646D6F6E643120301E0603550403" + "13174D532050617373706F7274205465737420537562204341301E170D313330" + "3131303231333931325A170D3331313231333232323630375A308185310B3009" + "060355040613025553310B30090603550408130257413110300E060355040713" + "075265646D6F6E64310D300B060355040A130454455354310D300B060355040B" + "130454455354311330110603550403130A746573742E6C6F63616C3124302206" + "092A864886F70D010901161563726973706F70406D6963726F736F66742E636F" + "6D30819F300D06092A864886F70D010101050003818D0030818902818100B406" + "851089E9CF7CDB438DD77BEBD819197BEEFF579C35EF9C4652DF9E6330AA7E2E" + "24B181C59DA4AF10E97220C1DF99F66CE6E97247E9126A016AC647BD2EFD136C" + "31470C7BE01A20E381243BEEC8530B7F6466C50A051DCE37274ED7FF2AFFF4E5" + "8AABA61D5A448F4A8A9B3765D1D769F627ED2F2DE9EE67B1A7ECA3D288C90203" + "010001A38202823082027E300E0603551D0F0101FF0404030204F0301D060355" + "1D250416301406082B0601050507030106082B06010505070302301D0603551D" + "0E04160414FB3485708CBF6188F720EF948489405C8D0413A7301F0603551D23" + "0418301680146A6678620A4FF49CA8B75FD566348F3371E42B133081D0060355" + "1D1F0481C83081C53081C2A081BFA081BC865F687474703A2F2F707074657374" + "73756263612E7265646D6F6E642E636F72702E6D6963726F736F66742E636F6D" + "2F43657274456E726F6C6C2F4D5325323050617373706F727425323054657374" + "25323053756225323043412831292E63726C865966696C653A2F2F5C5C707074" + "65737473756263612E7265646D6F6E642E636F72702E6D6963726F736F66742E" + "636F6D5C43657274456E726F6C6C5C4D532050617373706F7274205465737420" + "5375622043412831292E63726C3082013806082B060105050701010482012A30" + "82012630819306082B06010505073002868186687474703A2F2F707074657374" + "73756263612E7265646D6F6E642E636F72702E6D6963726F736F66742E636F6D" + "2F43657274456E726F6C6C2F70707465737473756263612E7265646D6F6E642E" + "636F72702E6D6963726F736F66742E636F6D5F4D5325323050617373706F7274" + "2532305465737425323053756225323043412831292E63727430818D06082B06" + "01050507300286818066696C653A2F2F5C5C70707465737473756263612E7265" + "646D6F6E642E636F72702E6D6963726F736F66742E636F6D5C43657274456E72" + "6F6C6C5C70707465737473756263612E7265646D6F6E642E636F72702E6D6963" + "726F736F66742E636F6D5F4D532050617373706F727420546573742053756220" + "43412831292E637274300D06092A864886F70D0101050500038181009DEBB8B5" + "A41ED54859795F68EF767A98A61EF7B07AAC190FCC0275228E4CAD360C9BA98B" + "0AE153C75522EEF42D400E813B4E49E7ACEB963EEE7B61D3C8DA05C183471544" + "725B2EBD1889877F62134827FB5993B8FDF618BD421ABA18D70D1C5B41ECDD11" + "695A48CB42EB501F96DA905471830C612B609126559120F6E18EA44830820358" + "308202C1A00302010202101B9671A4BC128B8341B0E314EAD9A191300D06092A" + "864886F70D01010505003081A13124302206092A864886F70D01090116156173" + "6D656D6F6E406D6963726F736F66742E636F6D310B3009060355040613025553" + "310B30090603550408130257413110300E060355040713075265646D6F6E6431" + "123010060355040A13094D6963726F736F667431163014060355040B130D5061" + "7373706F727420546573743121301F060355040313184D532050617373706F72" + "74205465737420526F6F74204341301E170D3035303132363031333933325A17" + "0D3331313231333232323630375A3081A13124302206092A864886F70D010901" + "161561736D656D6F6E406D6963726F736F66742E636F6D310B30090603550406" + "13025553310B30090603550408130257413110300E060355040713075265646D" + "6F6E6431123010060355040A13094D6963726F736F667431163014060355040B" + "130D50617373706F727420546573743121301F060355040313184D5320506173" + "73706F7274205465737420526F6F7420434130819F300D06092A864886F70D01" + "0101050003818D0030818902818100C4673C1226254F6BBD01B01D21BB05264A" + "9AA5B77AC51748EAC52048706DA6B890DCE043C6426FC44E76D70F9FE3A4AC85" + "5F533E3D08E140853DB769EE24DBDB7269FABEC0FDFF6ADE0AA85F0085B78864" + "58E7585E433B0924E81600433CB1177CE6AD5F2477B2A0E2D1A34B41F6C6F5AD" + "E4A9DD7D565C65F02C2AAA01C8E0C10203010001A3818E30818B301306092B06" + "0104018237140204061E0400430041300B0603551D0F040403020186300F0603" + "551D130101FF040530030101FF301D0603551D0E04160414F509C1D6267FC39F" + "CA1DE648C969C74FB111FE10301206092B060104018237150104050203010002" + "302306092B0601040182371502041604147F7A5208411D4607C0057C98F0C473" + "07010CB3DE300D06092A864886F70D0101050500038181004A8EAC73D8EA6D7E" + "893D5880945E0E3ABFC79C40BFA60A680CF8A8BF63EDC3AD9C11C081F1F44408" + "9581F5C8DCB23C0AEFA27571D971DBEB2AA9A1B3F7B9B0877E9311D36098A65B" + "7D03FC69A835F6C3096DEE135A864065F9779C82DEB0C777B9C4DB49F0DD11A0" + "EAB287B6E352F7ECA467D0D3CA2A8081119388BAFCDD25573082057C308204E5" + "A003020102020A6187C7F200020000001B300D06092A864886F70D0101050500" + "3081A13124302206092A864886F70D010901161561736D656D6F6E406D696372" + "6F736F66742E636F6D310B3009060355040613025553310B3009060355040813" + "0257413110300E060355040713075265646D6F6E6431123010060355040A1309" + "4D6963726F736F667431163014060355040B130D50617373706F727420546573" + "743121301F060355040313184D532050617373706F7274205465737420526F6F" + "74204341301E170D3039313032373231333133395A170D333131323133323232" + "3630375A30818131133011060A0992268993F22C6401191603636F6D31193017" + "060A0992268993F22C64011916096D6963726F736F667431143012060A099226" + "8993F22C6401191604636F727031173015060A0992268993F22C640119160772" + "65646D6F6E643120301E060355040313174D532050617373706F727420546573" + "742053756220434130819F300D06092A864886F70D010101050003818D003081" + "8902818100A6A4918F93C5D23B3C3A325AD8EC77043D207A0DDC294AD3F5BDE0" + "4033FADD4097BB1DB042B1D3B2F26A42CC3CB88FA9357710147AB4E1020A0DFB" + "2597AB8031DB62ABDC48398067EB79E4E2BBE5762F6B4C5EA7629BAC23F70269" + "06D46EC106CC6FBB4D143F7D5ADADEDE19B021EEF4A6BCB9D01DAEBB9A947703" + "40B748A3490203010001A38202D7308202D3300F0603551D130101FF04053003" + "0101FF301D0603551D0E041604146A6678620A4FF49CA8B75FD566348F3371E4" + "2B13300B0603551D0F040403020186301206092B060104018237150104050203" + "010001302306092B060104018237150204160414A0A485AE8296EA4944C6F6F3" + "886A8603FD07472C301906092B0601040182371402040C1E0A00530075006200" + "430041301F0603551D23041830168014F509C1D6267FC39FCA1DE648C969C74F" + "B111FE103081D60603551D1F0481CE3081CB3081C8A081C5A081C28663687474" + "703A2F2F70617373706F72747465737463612E7265646D6F6E642E636F72702E" + "6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F4D532532305061" + "7373706F727425323054657374253230526F6F7425323043412831292E63726C" + "865B66696C653A2F2F50415353504F52545445535443412E7265646D6F6E642E" + "636F72702E6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F4D53" + "2050617373706F7274205465737420526F6F742043412831292E63726C308201" + "4406082B06010505070101048201363082013230819A06082B06010505073002" + "86818D687474703A2F2F70617373706F72747465737463612E7265646D6F6E64" + "2E636F72702E6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F50" + "415353504F52545445535443412E7265646D6F6E642E636F72702E6D6963726F" + "736F66742E636F6D5F4D5325323050617373706F727425323054657374253230" + "526F6F7425323043412832292E63727430819206082B06010505073002868185" + "66696C653A2F2F50415353504F52545445535443412E7265646D6F6E642E636F" + "72702E6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F50415353" + "504F52545445535443412E7265646D6F6E642E636F72702E6D6963726F736F66" + "742E636F6D5F4D532050617373706F7274205465737420526F6F742043412832" + "292E637274300D06092A864886F70D010105050003818100C44788F8C4F5C2DC" + "84976F66417CBAE19FBFA82C257DA4C7FED6267BC711D113C78B1C097154A62A" + "B462ADC84A434AEBAE38DEB9605FAB534A3CAF7B72C199448E58640388911296" + "115ED6B3478D0E741D990F2D59D66F12E58669D8983489AB0406E37462164B56" + "6AA1D9B273C406FA694A2556D1D3ACE723382C19871B8C143100").HexToByteArray(); internal static readonly byte[] Pkcs7ChainPemBytes = ByteUtils.AsciiBytes( @"-----BEGIN PKCS7----- MIIOFgYJKoZIhvcNAQcCoIIOBzCCDgMCAQExADALBgkqhkiG9w0BBwGggg3rMIIF CzCCBHSgAwIBAgIKFeqoOgABAACSkTANBgkqhkiG9w0BAQUFADCBgTETMBEGCgmS JomT8ixkARkWA2NvbTEZMBcGCgmSJomT8ixkARkWCW1pY3Jvc29mdDEUMBIGCgmS JomT8ixkARkWBGNvcnAxFzAVBgoJkiaJk/IsZAEZFgdyZWRtb25kMSAwHgYDVQQD ExdNUyBQYXNzcG9ydCBUZXN0IFN1YiBDQTAeFw0xMzAxMTAyMTM5MTJaFw0zMTEy MTMyMjI2MDdaMIGFMQswCQYDVQQGEwJVUzELMAkGA1UECBMCV0ExEDAOBgNVBAcT B1JlZG1vbmQxDTALBgNVBAoTBFRFU1QxDTALBgNVBAsTBFRFU1QxEzARBgNVBAMT CnRlc3QubG9jYWwxJDAiBgkqhkiG9w0BCQEWFWNyaXNwb3BAbWljcm9zb2Z0LmNv bTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAtAaFEInpz3zbQ43Xe+vYGRl7 7v9XnDXvnEZS355jMKp+LiSxgcWdpK8Q6XIgwd+Z9mzm6XJH6RJqAWrGR70u/RNs MUcMe+AaIOOBJDvuyFMLf2RmxQoFHc43J07X/yr/9OWKq6YdWkSPSoqbN2XR12n2 J+0vLenuZ7Gn7KPSiMkCAwEAAaOCAoIwggJ+MA4GA1UdDwEB/wQEAwIE8DAdBgNV HSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwHQYDVR0OBBYEFPs0hXCMv2GI9yDv lISJQFyNBBOnMB8GA1UdIwQYMBaAFGpmeGIKT/ScqLdf1WY0jzNx5CsTMIHQBgNV HR8EgcgwgcUwgcKggb+ggbyGX2h0dHA6Ly9wcHRlc3RzdWJjYS5yZWRtb25kLmNv cnAubWljcm9zb2Z0LmNvbS9DZXJ0RW5yb2xsL01TJTIwUGFzc3BvcnQlMjBUZXN0 JTIwU3ViJTIwQ0EoMSkuY3JshllmaWxlOi8vXFxwcHRlc3RzdWJjYS5yZWRtb25k LmNvcnAubWljcm9zb2Z0LmNvbVxDZXJ0RW5yb2xsXE1TIFBhc3Nwb3J0IFRlc3Qg U3ViIENBKDEpLmNybDCCATgGCCsGAQUFBwEBBIIBKjCCASYwgZMGCCsGAQUFBzAC hoGGaHR0cDovL3BwdGVzdHN1YmNhLnJlZG1vbmQuY29ycC5taWNyb3NvZnQuY29t L0NlcnRFbnJvbGwvcHB0ZXN0c3ViY2EucmVkbW9uZC5jb3JwLm1pY3Jvc29mdC5j b21fTVMlMjBQYXNzcG9ydCUyMFRlc3QlMjBTdWIlMjBDQSgxKS5jcnQwgY0GCCsG AQUFBzAChoGAZmlsZTovL1xccHB0ZXN0c3ViY2EucmVkbW9uZC5jb3JwLm1pY3Jv c29mdC5jb21cQ2VydEVucm9sbFxwcHRlc3RzdWJjYS5yZWRtb25kLmNvcnAubWlj cm9zb2Z0LmNvbV9NUyBQYXNzcG9ydCBUZXN0IFN1YiBDQSgxKS5jcnQwDQYJKoZI hvcNAQEFBQADgYEAneu4taQe1UhZeV9o73Z6mKYe97B6rBkPzAJ1Io5MrTYMm6mL CuFTx1Ui7vQtQA6BO05J56zrlj7ue2HTyNoFwYNHFURyWy69GImHf2ITSCf7WZO4 /fYYvUIauhjXDRxbQezdEWlaSMtC61AfltqQVHGDDGErYJEmVZEg9uGOpEgwggNY MIICwaADAgECAhAblnGkvBKLg0Gw4xTq2aGRMA0GCSqGSIb3DQEBBQUAMIGhMSQw IgYJKoZIhvcNAQkBFhVhc21lbW9uQG1pY3Jvc29mdC5jb20xCzAJBgNVBAYTAlVT MQswCQYDVQQIEwJXQTEQMA4GA1UEBxMHUmVkbW9uZDESMBAGA1UEChMJTWljcm9z b2Z0MRYwFAYDVQQLEw1QYXNzcG9ydCBUZXN0MSEwHwYDVQQDExhNUyBQYXNzcG9y dCBUZXN0IFJvb3QgQ0EwHhcNMDUwMTI2MDEzOTMyWhcNMzExMjEzMjIyNjA3WjCB oTEkMCIGCSqGSIb3DQEJARYVYXNtZW1vbkBtaWNyb3NvZnQuY29tMQswCQYDVQQG EwJVUzELMAkGA1UECBMCV0ExEDAOBgNVBAcTB1JlZG1vbmQxEjAQBgNVBAoTCU1p Y3Jvc29mdDEWMBQGA1UECxMNUGFzc3BvcnQgVGVzdDEhMB8GA1UEAxMYTVMgUGFz c3BvcnQgVGVzdCBSb290IENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDE ZzwSJiVPa70BsB0huwUmSpqlt3rFF0jqxSBIcG2muJDc4EPGQm/ETnbXD5/jpKyF X1M+PQjhQIU9t2nuJNvbcmn6vsD9/2reCqhfAIW3iGRY51heQzsJJOgWAEM8sRd8 5q1fJHeyoOLRo0tB9sb1reSp3X1WXGXwLCqqAcjgwQIDAQABo4GOMIGLMBMGCSsG AQQBgjcUAgQGHgQAQwBBMAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0G A1UdDgQWBBT1CcHWJn/Dn8od5kjJacdPsRH+EDASBgkrBgEEAYI3FQEEBQIDAQAC MCMGCSsGAQQBgjcVAgQWBBR/elIIQR1GB8AFfJjwxHMHAQyz3jANBgkqhkiG9w0B AQUFAAOBgQBKjqxz2Optfok9WICUXg46v8ecQL+mCmgM+Ki/Y+3DrZwRwIHx9EQI lYH1yNyyPArvonVx2XHb6yqpobP3ubCHfpMR02CYplt9A/xpqDX2wwlt7hNahkBl +Xecgt6wx3e5xNtJ8N0RoOqyh7bjUvfspGfQ08oqgIERk4i6/N0lVzCCBXwwggTl oAMCAQICCmGHx/IAAgAAABswDQYJKoZIhvcNAQEFBQAwgaExJDAiBgkqhkiG9w0B CQEWFWFzbWVtb25AbWljcm9zb2Z0LmNvbTELMAkGA1UEBhMCVVMxCzAJBgNVBAgT AldBMRAwDgYDVQQHEwdSZWRtb25kMRIwEAYDVQQKEwlNaWNyb3NvZnQxFjAUBgNV BAsTDVBhc3Nwb3J0IFRlc3QxITAfBgNVBAMTGE1TIFBhc3Nwb3J0IFRlc3QgUm9v dCBDQTAeFw0wOTEwMjcyMTMxMzlaFw0zMTEyMTMyMjI2MDdaMIGBMRMwEQYKCZIm iZPyLGQBGRYDY29tMRkwFwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MRQwEgYKCZIm iZPyLGQBGRYEY29ycDEXMBUGCgmSJomT8ixkARkWB3JlZG1vbmQxIDAeBgNVBAMT F01TIFBhc3Nwb3J0IFRlc3QgU3ViIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB iQKBgQCmpJGPk8XSOzw6MlrY7HcEPSB6DdwpStP1veBAM/rdQJe7HbBCsdOy8mpC zDy4j6k1dxAUerThAgoN+yWXq4Ax22Kr3Eg5gGfreeTiu+V2L2tMXqdim6wj9wJp BtRuwQbMb7tNFD99Wtre3hmwIe70pry50B2uu5qUdwNAt0ijSQIDAQABo4IC1zCC AtMwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUamZ4YgpP9Jyot1/VZjSPM3Hk KxMwCwYDVR0PBAQDAgGGMBIGCSsGAQQBgjcVAQQFAgMBAAEwIwYJKwYBBAGCNxUC BBYEFKCkha6ClupJRMb284hqhgP9B0csMBkGCSsGAQQBgjcUAgQMHgoAUwB1AGIA QwBBMB8GA1UdIwQYMBaAFPUJwdYmf8Ofyh3mSMlpx0+xEf4QMIHWBgNVHR8Egc4w gcswgciggcWggcKGY2h0dHA6Ly9wYXNzcG9ydHRlc3RjYS5yZWRtb25kLmNvcnAu bWljcm9zb2Z0LmNvbS9DZXJ0RW5yb2xsL01TJTIwUGFzc3BvcnQlMjBUZXN0JTIw Um9vdCUyMENBKDEpLmNybIZbZmlsZTovL1BBU1NQT1JUVEVTVENBLnJlZG1vbmQu Y29ycC5taWNyb3NvZnQuY29tL0NlcnRFbnJvbGwvTVMgUGFzc3BvcnQgVGVzdCBS b290IENBKDEpLmNybDCCAUQGCCsGAQUFBwEBBIIBNjCCATIwgZoGCCsGAQUFBzAC hoGNaHR0cDovL3Bhc3Nwb3J0dGVzdGNhLnJlZG1vbmQuY29ycC5taWNyb3NvZnQu Y29tL0NlcnRFbnJvbGwvUEFTU1BPUlRURVNUQ0EucmVkbW9uZC5jb3JwLm1pY3Jv c29mdC5jb21fTVMlMjBQYXNzcG9ydCUyMFRlc3QlMjBSb290JTIwQ0EoMikuY3J0 MIGSBggrBgEFBQcwAoaBhWZpbGU6Ly9QQVNTUE9SVFRFU1RDQS5yZWRtb25kLmNv cnAubWljcm9zb2Z0LmNvbS9DZXJ0RW5yb2xsL1BBU1NQT1JUVEVTVENBLnJlZG1v bmQuY29ycC5taWNyb3NvZnQuY29tX01TIFBhc3Nwb3J0IFRlc3QgUm9vdCBDQSgy KS5jcnQwDQYJKoZIhvcNAQEFBQADgYEAxEeI+MT1wtyEl29mQXy64Z+/qCwlfaTH /tYme8cR0RPHixwJcVSmKrRirchKQ0rrrjjeuWBfq1NKPK97csGZRI5YZAOIkRKW EV7Ws0eNDnQdmQ8tWdZvEuWGadiYNImrBAbjdGIWS1Zqodmyc8QG+mlKJVbR06zn IzgsGYcbjBQxAA== -----END PKCS7-----"); internal static readonly byte[] Pkcs7EmptyPemBytes = ByteUtils.AsciiBytes( @"-----BEGIN PKCS7----- MCcGCSqGSIb3DQEHAqAaMBgCAQExADALBgkqhkiG9w0BBwGgAKEAMQA= -----END PKCS7-----"); internal static readonly byte[] Pkcs7EmptyDerBytes = ( "302706092A864886F70D010702A01A30180201013100300B06092A864886F70D" + "010701A000A1003100").HexToByteArray(); internal static readonly byte[] Pkcs7SingleDerBytes = ( "3082021406092A864886F70D010702A0820205308202010201013100300B0609" + "2A864886F70D010701A08201E9308201E530820152A0030201020210D5B5BC1C" + "458A558845BFF51CB4DFF31C300906052B0E03021D05003011310F300D060355" + "040313064D794E616D65301E170D3130303430313038303030305A170D313130" + "3430313038303030305A3011310F300D060355040313064D794E616D6530819F" + "300D06092A864886F70D010101050003818D0030818902818100B11E30EA8742" + "4A371E30227E933CE6BE0E65FF1C189D0D888EC8FF13AA7B42B68056128322B2" + "1F2B6976609B62B6BC4CF2E55FF5AE64E9B68C78A3C2DACC916A1BC7322DD353" + "B32898675CFB5B298B176D978B1F12313E3D865BC53465A11CCA106870A4B5D5" + "0A2C410938240E92B64902BAEA23EB093D9599E9E372E48336730203010001A3" + "46304430420603551D01043B3039801024859EBF125E76AF3F0D7979B4AC7A96" + "A1133011310F300D060355040313064D794E616D658210D5B5BC1C458A558845" + "BFF51CB4DFF31C300906052B0E03021D0500038181009BF6E2CF830ED485B86D" + "6B9E8DFFDCD65EFC7EC145CB9348923710666791FCFA3AB59D689FFD7234B787" + "2611C5C23E5E0714531ABADB5DE492D2C736E1C929E648A65CC9EB63CD84E57B" + "5909DD5DDF5DBBBA4A6498B9CA225B6E368B94913BFC24DE6B2BD9A26B192B95" + "7304B89531E902FFC91B54B237BB228BE8AFCDA264763100").HexToByteArray(); internal static readonly byte[] Pkcs7SinglePemBytes = ByteUtils.AsciiBytes( @"-----BEGIN PKCS7----- MIICFAYJKoZIhvcNAQcCoIICBTCCAgECAQExADALBgkqhkiG9w0BBwGgggHpMIIB 5TCCAVKgAwIBAgIQ1bW8HEWKVYhFv/UctN/zHDAJBgUrDgMCHQUAMBExDzANBgNV BAMTBk15TmFtZTAeFw0xMDA0MDEwODAwMDBaFw0xMTA0MDEwODAwMDBaMBExDzAN BgNVBAMTBk15TmFtZTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAsR4w6odC SjceMCJ+kzzmvg5l/xwYnQ2Ijsj/E6p7QraAVhKDIrIfK2l2YJtitrxM8uVf9a5k 6baMeKPC2syRahvHMi3TU7MomGdc+1spixdtl4sfEjE+PYZbxTRloRzKEGhwpLXV CixBCTgkDpK2SQK66iPrCT2VmenjcuSDNnMCAwEAAaNGMEQwQgYDVR0BBDswOYAQ JIWevxJedq8/DXl5tKx6lqETMBExDzANBgNVBAMTBk15TmFtZYIQ1bW8HEWKVYhF v/UctN/zHDAJBgUrDgMCHQUAA4GBAJv24s+DDtSFuG1rno3/3NZe/H7BRcuTSJI3 EGZnkfz6OrWdaJ/9cjS3hyYRxcI+XgcUUxq6213kktLHNuHJKeZIplzJ62PNhOV7 WQndXd9du7pKZJi5yiJbbjaLlJE7/CTeayvZomsZK5VzBLiVMekC/8kbVLI3uyKL 6K/NomR2MQA= -----END PKCS7-----"); internal static readonly byte[] MicrosoftDotComSslCertBytes = ( "308205943082047CA00302010202103DF70C5D9903F8D8868B9B8CCF20DF6930" + "0D06092A864886F70D01010B05003077310B3009060355040613025553311D30" + "1B060355040A131453796D616E74656320436F72706F726174696F6E311F301D" + "060355040B131653796D616E746563205472757374204E6574776F726B312830" + "260603550403131F53796D616E74656320436C61737320332045562053534C20" + "4341202D204733301E170D3134313031353030303030305A170D313631303135" + "3233353935395A3082010F31133011060B2B0601040182373C02010313025553" + "311B3019060B2B0601040182373C0201020C0A57617368696E67746F6E311D30" + "1B060355040F131450726976617465204F7267616E697A6174696F6E31123010" + "06035504051309363030343133343835310B3009060355040613025553310E30" + "0C06035504110C0539383035323113301106035504080C0A57617368696E6774" + "6F6E3110300E06035504070C075265646D6F6E643118301606035504090C0F31" + "204D6963726F736F667420576179311E301C060355040A0C154D6963726F736F" + "667420436F72706F726174696F6E310E300C060355040B0C054D53434F4D311A" + "301806035504030C117777772E6D6963726F736F66742E636F6D30820122300D" + "06092A864886F70D01010105000382010F003082010A0282010100A46861FA9D" + "5DB763633BF5A64EF6E7C2C2367F48D2D46643A22DFCFCCB24E58A14D0F06BDC" + "956437F2A56BA4BEF70BA361BF12964A0D665AFD84B0F7494C8FA4ABC5FCA2E0" + "17C06178AEF2CDAD1B5F18E997A14B965C074E8F564970607276B00583932240" + "FE6E2DD013026F9AE13D7C91CC07C4E1E8E87737DC06EF2B575B89D62EFE4685" + "9F8255A123692A706C68122D4DAFE11CB205A7B3DE06E553F7B95F978EF8601A" + "8DF819BF32040BDF92A0DE0DF269B4514282E17AC69934E8440A48AB9D1F5DF8" + "9A502CEF6DFDBE790045BD45E0C94E5CA8ADD76A013E9C978440FC8A9E2A9A49" + "40B2460819C3E302AA9C9F355AD754C86D3ED77DDAA3DA13810B4D0203010001" + "A38201803082017C30310603551D11042A302882117777772E6D6963726F736F" + "66742E636F6D821377777771612E6D6963726F736F66742E636F6D3009060355" + "1D1304023000300E0603551D0F0101FF0404030205A0301D0603551D25041630" + "1406082B0601050507030106082B0601050507030230660603551D20045F305D" + "305B060B6086480186F84501071706304C302306082B06010505070201161768" + "747470733A2F2F642E73796D63622E636F6D2F637073302506082B0601050507" + "020230191A1768747470733A2F2F642E73796D63622E636F6D2F727061301F06" + "03551D230418301680140159ABE7DD3A0B59A66463D6CF200757D591E76A302B" + "0603551D1F042430223020A01EA01C861A687474703A2F2F73722E73796D6362" + "2E636F6D2F73722E63726C305706082B06010505070101044B3049301F06082B" + "060105050730018613687474703A2F2F73722E73796D63642E636F6D30260608" + "2B06010505073002861A687474703A2F2F73722E73796D63622E636F6D2F7372" + "2E637274300D06092A864886F70D01010B0500038201010015F8505B627ED7F9" + "F96707097E93A51E7A7E05A3D420A5C258EC7A1CFE1843EC20ACF728AAFA7A1A" + "1BC222A7CDBF4AF90AA26DEEB3909C0B3FB5C78070DAE3D645BFCF840A4A3FDD" + "988C7B3308BFE4EB3FD66C45641E96CA3352DBE2AEB4488A64A9C5FB96932BA7" + "0059CE92BD278B41299FD213471BD8165F924285AE3ECD666C703885DCA65D24" + "DA66D3AFAE39968521995A4C398C7DF38DFA82A20372F13D4A56ADB21B582254" + "9918015647B5F8AC131CC5EB24534D172BC60218A88B65BCF71C7F388CE3E0EF" + "697B4203720483BB5794455B597D80D48CD3A1D73CBBC609C058767D1FF060A6" + "09D7E3D4317079AF0CD0A8A49251AB129157F9894A036487").HexToByteArray(); internal static readonly byte[] MicrosoftDotComIssuerBytes = ( "3082052B30820413A00302010202107EE14A6F6FEFF2D37F3FAD654D3ADAB430" + "0D06092A864886F70D01010B05003081CA310B30090603550406130255533117" + "3015060355040A130E566572695369676E2C20496E632E311F301D060355040B" + "1316566572695369676E205472757374204E6574776F726B313A303806035504" + "0B1331286329203230303620566572695369676E2C20496E632E202D20466F72" + "20617574686F72697A656420757365206F6E6C79314530430603550403133C56" + "6572695369676E20436C6173732033205075626C6963205072696D6172792043" + "657274696669636174696F6E20417574686F72697479202D204735301E170D31" + "33313033313030303030305A170D3233313033303233353935395A3077310B30" + "09060355040613025553311D301B060355040A131453796D616E74656320436F" + "72706F726174696F6E311F301D060355040B131653796D616E74656320547275" + "7374204E6574776F726B312830260603550403131F53796D616E74656320436C" + "61737320332045562053534C204341202D20473330820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100D8A1657423E82B64E232D7" + "33373D8EF5341648DD4F7F871CF84423138EFB11D8445A18718E601626929BFD" + "170BE1717042FEBFFA1CC0AAA3A7B571E8FF1883F6DF100A1362C83D9CA7DE2E" + "3F0CD91DE72EFB2ACEC89A7F87BFD84C041532C9D1CC9571A04E284F84D935FB" + "E3866F9453E6728A63672EBE69F6F76E8E9C6004EB29FAC44742D27898E3EC0B" + "A592DCB79ABD80642B387C38095B66F62D957A86B2342E859E900E5FB75DA451" + "72467013BF67F2B6A74D141E6CB953EE231A4E8D48554341B189756A4028C57D" + "DDD26ED202192F7B24944BEBF11AA99BE3239AEAFA33AB0A2CB7F46008DD9F1C" + "CDDD2D016680AFB32F291D23B88AE1A170070C340F0203010001A382015D3082" + "0159302F06082B0601050507010104233021301F06082B060105050730018613" + "687474703A2F2F73322E73796D63622E636F6D30120603551D130101FF040830" + "060101FF02010030650603551D20045E305C305A0604551D2000305230260608" + "2B06010505070201161A687474703A2F2F7777772E73796D617574682E636F6D" + "2F637073302806082B06010505070202301C1A1A687474703A2F2F7777772E73" + "796D617574682E636F6D2F72706130300603551D1F042930273025A023A02186" + "1F687474703A2F2F73312E73796D63622E636F6D2F706361332D67352E63726C" + "300E0603551D0F0101FF04040302010630290603551D1104223020A41E301C31" + "1A30180603550403131153796D616E746563504B492D312D353333301D060355" + "1D0E041604140159ABE7DD3A0B59A66463D6CF200757D591E76A301F0603551D" + "230418301680147FD365A7C2DDECBBF03009F34339FA02AF333133300D06092A" + "864886F70D01010B050003820101004201557BD0161A5D58E8BB9BA84DD7F3D7" + "EB139486D67F210B47BC579B925D4F059F38A4107CCF83BE0643468D08BC6AD7" + "10A6FAABAF2F61A863F265DF7F4C8812884FB369D9FF27C00A97918F56FB89C4" + "A8BB922D1B73B0C6AB36F4966C2008EF0A1E6624454F670040C8075474333BA6" + "ADBB239F66EDA2447034FB0EEA01FDCF7874DFA7AD55B75F4DF6D63FE086CE24" + "C742A9131444354BB6DFC960AC0C7FD993214BEE9CE4490298D3607B5CBCD530" + "2F07CE4442C40B99FEE69FFCB07886516DD12C9DC696FB8582BB042FF76280EF" + "62DA7FF60EAC90B856BD793FF2806EA3D9B90F5D3A071D9193864B294CE1DCB5" + "E1E0339DB3CB36914BFEA1B4EEF0F9").HexToByteArray(); internal static readonly byte[] MicrosoftDotComRootBytes = ( "308204D3308203BBA003020102021018DAD19E267DE8BB4A2158CDCC6B3B4A30" + "0D06092A864886F70D01010505003081CA310B30090603550406130255533117" + "3015060355040A130E566572695369676E2C20496E632E311F301D060355040B" + "1316566572695369676E205472757374204E6574776F726B313A303806035504" + "0B1331286329203230303620566572695369676E2C20496E632E202D20466F72" + "20617574686F72697A656420757365206F6E6C79314530430603550403133C56" + "6572695369676E20436C6173732033205075626C6963205072696D6172792043" + "657274696669636174696F6E20417574686F72697479202D204735301E170D30" + "36313130383030303030305A170D3336303731363233353935395A3081CA310B" + "300906035504061302555331173015060355040A130E566572695369676E2C20" + "496E632E311F301D060355040B1316566572695369676E205472757374204E65" + "74776F726B313A3038060355040B133128632920323030362056657269536967" + "6E2C20496E632E202D20466F7220617574686F72697A656420757365206F6E6C" + "79314530430603550403133C566572695369676E20436C617373203320507562" + "6C6963205072696D6172792043657274696669636174696F6E20417574686F72" + "697479202D20473530820122300D06092A864886F70D01010105000382010F00" + "3082010A0282010100AF240808297A359E600CAAE74B3B4EDC7CBC3C451CBB2B" + "E0FE2902F95708A364851527F5F1ADC831895D22E82AAAA642B38FF8B955B7B1" + "B74BB3FE8F7E0757ECEF43DB66621561CF600DA4D8DEF8E0C362083D5413EB49" + "CA59548526E52B8F1B9FEBF5A191C23349D843636A524BD28FE870514DD18969" + "7BC770F6B3DC1274DB7B5D4B56D396BF1577A1B0F4A225F2AF1C926718E5F406" + "04EF90B9E400E4DD3AB519FF02BAF43CEEE08BEB378BECF4D7ACF2F6F03DAFDD" + "759133191D1C40CB7424192193D914FEAC2A52C78FD50449E48D6347883C6983" + "CBFE47BD2B7E4FC595AE0E9DD4D143C06773E314087EE53F9F73B8330ACF5D3F" + "3487968AEE53E825150203010001A381B23081AF300F0603551D130101FF0405" + "30030101FF300E0603551D0F0101FF040403020106306D06082B060105050701" + "0C0461305FA15DA05B3059305730551609696D6167652F6769663021301F3007" + "06052B0E03021A04148FE5D31A86AC8D8E6BC3CF806AD448182C7B192E302516" + "23687474703A2F2F6C6F676F2E766572697369676E2E636F6D2F76736C6F676F" + "2E676966301D0603551D0E041604147FD365A7C2DDECBBF03009F34339FA02AF" + "333133300D06092A864886F70D0101050500038201010093244A305F62CFD81A" + "982F3DEADC992DBD77F6A5792238ECC4A7A07812AD620E457064C5E797662D98" + "097E5FAFD6CC2865F201AA081A47DEF9F97C925A0869200DD93E6D6E3C0D6ED8" + "E606914018B9F8C1EDDFDB41AAE09620C9CD64153881C994EEA284290B136F8E" + "DB0CDD2502DBA48B1944D2417A05694A584F60CA7E826A0B02AA251739B5DB7F" + "E784652A958ABD86DE5E8116832D10CCDEFDA8822A6D281F0D0BC4E5E71A2619" + "E1F4116F10B595FCE7420532DBCE9D515E28B69E85D35BEFA57D4540728EB70E" + "6B0E06FB33354871B89D278BC4655F0D86769C447AF6955CF65D320833A454B6" + "183F685CF2424A853854835FD1E82CF2AC11D6A8ED636A").HexToByteArray(); internal static readonly byte[] Rsa384CertificatePemBytes = ByteUtils.AsciiBytes( @"-----BEGIN CERTIFICATE----- MIICTzCCAgmgAwIBAgIJAMQtYhFJ0+5jMA0GCSqGSIb3DQEBBQUAMIGSMQswCQYD VQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3RvbjEQMA4GA1UEBwwHUmVkbW9uZDEY MBYGA1UECgwPTWljcm9zb2Z0IENvcnAuMSAwHgYDVQQLDBcuTkVUIEZyYW1ld29y ayAoQ29yZUZ4KTEgMB4GA1UEAwwXUlNBIDM4NC1iaXQgQ2VydGlmaWNhdGUwHhcN MTYwMzAyMTY1OTA0WhcNMTYwNDAxMTY1OTA0WjCBkjELMAkGA1UEBhMCVVMxEzAR BgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1JlZG1vbmQxGDAWBgNVBAoMD01p Y3Jvc29mdCBDb3JwLjEgMB4GA1UECwwXLk5FVCBGcmFtZXdvcmsgKENvcmVGeCkx IDAeBgNVBAMMF1JTQSAzODQtYml0IENlcnRpZmljYXRlMEwwDQYJKoZIhvcNAQEB BQADOwAwOAIxANrMIthuZxV1Ay4x8gbc/BksZeLVEInlES0JbyiCr9tbeM22Vy/S 9h2zkEciMuPZ9QIDAQABo1AwTjAdBgNVHQ4EFgQU5FG2Fmi86hJOCf4KnjaxOGWV dRUwHwYDVR0jBBgwFoAU5FG2Fmi86hJOCf4KnjaxOGWVdRUwDAYDVR0TBAUwAwEB /zANBgkqhkiG9w0BAQUFAAMxAEzDg/u8TlApCnE8qxhcbTXk2MbX+2n5PCn+MVrW wggvPj3b2WMXsVWiPr4S1Y/nBA== -----END CERTIFICATE-----"); internal static readonly byte[] ECDsabrainpoolP160r1_Pfx = ( "308203D00201033082039606092A864886F70D010701A0820387048203833082" + "037F3082029F06092A864886F70D010706A08202903082028C02010030820285" + "06092A864886F70D010701301C060A2A864886F70D010C0106300E0408E4D7F5" + "F71CA4D5380202080080820258F19503250C93322C81CCC92C57AD76AD4DDF79" + "10DBAB6A63D6AAF3F470AC5283BDEB532086D3379B7A3D68D17FAC483EBEA029" + "1D2B5F862885E048A3034580A41F238AA836B9E94C12B0656B51C72355AED1DD" + "19FE771E3768095D6467FC8742BE0BC5D65360CD875D35C23D272842F64791A1" + "53F96AFBD3D7660EC016BF9D59B2B68C2A34D93B133697D6B77DB27649BEEABC" + "0B68D35DB3779DD4C871C9C26799E6ABB5E9048DDC44C6E6310F3A023AD09E97" + "1AB1DF38FDF3091FB35125EA3A14F5D72A00EC4C637951F026DE79C0E30E0244" + "808FB46EFD4EA9C67411DC2B13842B273F405F6D58D45D1D2D47BC1362ED9884" + "C2C44EA334A3B02C7E661F489DED798B63D64F90916596BADC87C68C868FCECB" + "6F246410186BBB2F2DC2ED24BF215AA54570072E21970CF856398BB1FD8C2F61" + "0788231C51D45CE471A235464147A405799F8CBE39AA30A8BFD2534C738AE330" + "8771394D871429EF2D6AB6381F793D7CBC0374D4E529B8B6AA37BE04FBE71A9A" + "A7954814C0C8841740539ED97DB56C3CBE5851C9D875E4B6023AE095B62C9DC5" + "36E06DA40C4B874776CBABDDAB50BDD5ECF9D997EEB1483D3AC23E6F37DD4CBD" + "64163E7A115BCE44554C53DD860B83CBE3B35F1E26B87185C602E4FFB3A99458" + "0D6A9334F74AA29B3609926FE86F197C955CBAEC2A41EE1572A4295F62D4D9CA" + "050CD933BC0BA43D7744EAFA9D6B8253241EB36C605DC334A6470BC709F13985" + "8AC238FD7F3C14EDDAB6E29996FE966A96EAC23CF17063C89315734D76CCB21F" + "94A7E4A44A5F6DCB93CEEEFB539664296F8F609CFE293200FE4B5EE57AB3A1E7" + "A3483DC6243081D906092A864886F70D010701A081CB0481C83081C53081C206" + "0B2A864886F70D010C0A0102A0818B308188301C060A2A864886F70D010C0103" + "300E0408CD30F3C5A9918832020208000468BF29F33058622BA159CDD3DE2B49" + "CBDD736BF1483FF4D43BACCC93B544A513D5E47DB4FECADBB4E3277A6B90345D" + "7E73F507924A615D968F807834D3796EFB0A3EF214A75883E3AB90086DA2418B" + "0B2D657DEA39A8600172B6975FFB39E88863DB11283A5CEA1FCB312530230609" + "2A864886F70D01091531160414472193B362B056F6D6928EFF4C43FF1EFEB173" + "4E30313021300906052B0E03021A05000414B703685D5039D8EEF1A46F772F31" + "F177FDE874EC0408B4EF89F18902CE9502020800").HexToByteArray(); internal static readonly byte[] ECDsabrainpoolP160r1_Explicit_Pfx = ( "30820501020103308204C706092A864886F70D010701A08204B8048204B43082" + "04B03082032F06092A864886F70D010706A08203203082031C02010030820315" + "06092A864886F70D010701301C060A2A864886F70D010C0106300E0408C55E7D" + "72B26355D202020800808202E8B8BCB9180C8751F860C5F77C04CC921A89D836" + "E8BC06DA99238EF8D65FB3473AF97D930B93471B28F08F483062BCEDB44287FA" + "E813B6CA812393475F50BB2D0AD233A8CE0832DECE54EF78A1F289A7802A9900" + "BAA2B7392BCF6C963D54D8DD63898D5D2FA472E77194763822157664417D93D8" + "BF740A4A5683FFFDF8B4CC7E074C6DCFF73E21368D743F0A1CE33484B02A4502" + "F7340A853F82F606B10DEA7239EF56C8DBDAED8DD3C956DD4D3E42CA517318E6" + "0DF70721469C512E120C500956D960A59EEB4A3A6541891319ACA68AB99462EA" + "CB59B52F6C6BFCF24EEA4E19BDDC5DDE1B6F36549DD589E1B10CAA02D4A53C36" + "1F1B9F101F9375394CF9BC8D941F94CC4F128EC861AA6B4182E1F81D2C0BADEA" + "2E6596BAC8819DE293ECEEC7C54BE97CD3917E0497F2559D44EF3484618DCB9B" + "85820762F392925BB36BD482DF544B614CDF9C6728BD92E858C1DF61435E7A03" + "DED27DA460603A61BE7DB93870E9530EB51384663E42A49C342891B8E757ED49" + "18A590D59734EA1C95E992CD93B80EBD3C246999305C204A813E0DCF26E64446" + "15A79E74042C7EAD4FEF0E68AA9DF627B5F4C037BF728015B6BBFA046CAA805C" + "BE7B1867262B36172E8759FAE7B965FF9B98D3539A48525E10A57A84C55AEFAC" + "3ED9025AB8B0680E0896DDD776C0AFC1A95BDD5DBE0ECCEB860B3CD3D6A2A493" + "2BC7774246A6936AFABA9BA8292841F9D6417AFFB00872E9B4ADF11889AEF20A" + "FCB8EAEBADAF38A2A240D36940B1585B37F7CA6A887EE1FBA199990FC104CD1F" + "A983CC2CE91156559EFCFC0F25B7C24B161DF4B4436F14428C4AE06F49FCC328" + "D00891A44AFAE5412FD330E23CFAE6107B4C965DFDB6335E8EFDF2C40767846B" + "C95ABF784DE155EED92DAB7A265DC17BC3ADA68D04E378D2E4E8924B05937092" + "E779EB04899E4FB19AAE7AA5FCF8D7A33BA464E4BB1FFB4E4D4CD71152F42B68" + "F5AB298B10DEB653C7F77F66B761DFD61E4E2DDD13B0B15639473BF5C3B8A31D" + "3D2334287F61E1A06F44CD3F2E74F59F43876F0D923082017906092A864886F7" + "0D010701A082016A04820166308201623082015E060B2A864886F70D010C0A01" + "02A082012630820122301C060A2A864886F70D010C0103300E0408A92CDE5D9A" + "F5278D0202080004820100A302E03B1BDF59D4ECD6F0FE7745F7C0DCE2CCEF0E" + "B26A7B92839B60288B05445BA1C91109D7E632E0C7B742E2D7D0947573AFEF1F" + "FAFCF8135DA3B5EE26A8E3AB7F415A8A19112724F850F024D3527F1FE2A303B1" + "34A644307AC6816E59E08540FA782351B27E37775AF3CD904E50A1A76C7C4F34" + "7EE78A1ED51FF71D00954130369012750746A280983E883E59AFDBBCCC7D1AA0" + "ECDCF2079ECFA4645E156ACC5FD6913763FC93C2E0C572042D00FE4EEB5E75DE" + "28C21FA1A7356C4071572DF23CC23833EA26705C0AA080636E27512B5F5755FE" + "A0514A31833D52C48A743BCDC0B58257FEDD23EE4EDBC06B574019E792B44BD6" + "3F3770875A25075183AF2C3125302306092A864886F70D01091531160414141C" + "1C8591A700DDE70FAC750C1539B2DFECAA3C30313021300906052B0E03021A05" + "0004143706E218219A899C700BD7AE3E8650FD1B2885AB0408E77FDD798BCADE" + "3C02020800").HexToByteArray(); internal static readonly byte[] ECDsabrainpoolP160r1_CertificatePemBytes = ByteUtils.AsciiBytes( @"-----BEGIN CERTIFICATE----- MIIB+TCCAbagAwIBAgIJAIJ8gBL6U36GMAoGCCqGSM49BAMCMHAxCzAJBgNVBAYT AlVTMRUwEwYDVQQIDAxOb3J0aCBEYWtvdGExDjAMBgNVBAcMBUZhcmdvMRgwFgYD VQQKDA9NaWNyb3NvZnQgQ29ycC4xIDAeBgNVBAsMFy5ORVQgRnJhbWV3b3JrIChD b3JlRngpMB4XDTE2MDYxMDE0NTYzOFoXDTE2MDcxMDE0NTYzOFowcDELMAkGA1UE BhMCVVMxFTATBgNVBAgMDE5vcnRoIERha290YTEOMAwGA1UEBwwFRmFyZ28xGDAW BgNVBAoMD01pY3Jvc29mdCBDb3JwLjEgMB4GA1UECwwXLk5FVCBGcmFtZXdvcmsg KENvcmVGeCkwQjAUBgcqhkjOPQIBBgkrJAMDAggBAQEDKgAEQk2dep8HoNJcbCal ie5QIMYsNnphtOo9WUCgrrzEG3wfrxz39HcAXaNQME4wHQYDVR0OBBYEFPprBFD9 qDQynQJmJUpVKv9WR8z5MB8GA1UdIwQYMBaAFPprBFD9qDQynQJmJUpVKv9WR8z5 MAwGA1UdEwQFMAMBAf8wCgYIKoZIzj0EAwIDMQAwLgIVAN3U12PFcEe4HHi+Rio+ xk3lf6EbAhUAqdeGDOXgpHEoWEmzOQ6nWWQik1k= -----END CERTIFICATE-----"); internal static readonly byte[] ECDsabrainpoolP160r1_ExplicitCertificatePemBytes = ByteUtils.AsciiBytes( @"-----BEGIN CERTIFICATE----- MIICijCCAkigAwIBAgIJAJVtMTsUqcjsMAoGCCqGSM49BAMCMHAxCzAJBgNVBAYT AlVTMRUwEwYDVQQIDAxOb3J0aCBEYWtvdGExDjAMBgNVBAcMBUZhcmdvMRgwFgYD VQQKDA9NaWNyb3NvZnQgQ29ycC4xIDAeBgNVBAsMFy5ORVQgRnJhbWV3b3JrIChD b3JlRngpMB4XDTE2MDYxMDE1MDg1NVoXDTE2MDcxMDE1MDg1NVowcDELMAkGA1UE BhMCVVMxFTATBgNVBAgMDE5vcnRoIERha290YTEOMAwGA1UEBwwFRmFyZ28xGDAW BgNVBAoMD01pY3Jvc29mdCBDb3JwLjEgMB4GA1UECwwXLk5FVCBGcmFtZXdvcmsg KENvcmVGeCkwgdMwgaQGByqGSM49AgEwgZgCAQEwIAYHKoZIzj0BAQIVAOleSl9z cFncYN/HrZWz2BOVFWIPMCwEFDQOe+KigOt04r5hutp0XZfo98MABBQeWJqFlUI0 EhNPqi297JXI2GdeWAQpBL7VrxbqP2pPYpOMRjHrWve9vNvDFmfLR3oajsM4+UdB ZpyXYxbaYyECFQDpXkpfc3BZ3GDfWZHUUClAnmD8CQIBAQMqAARz9ueEHonciPIW lTsd673ZaNpP9GMoFfHns3DnUC0pC1Grh+6sZcPIo1AwTjAdBgNVHQ4EFgQU65OI c9u4x/ZfIRyjcSaZTUKSsuIwHwYDVR0jBBgwFoAU65OIc9u4x/ZfIRyjcSaZTUKS suIwDAYDVR0TBAUwAwEB/zAKBggqhkjOPQQDAgMwADAtAhUAxMT7z8lLv7hgWmGh 5siYmHkAExoCFFaaS2r7/kdkXsauyr37q6ewD6s+ -----END CERTIFICATE-----"); internal static readonly ECDsaCngKeyValues ECDsaCng256PublicKey = new ECDsaCngKeyValues() { QX = "448d98ee08aeba0d8b40f3c6dbd500e8b69f07c70c661771655228ea5a178a91".HexToByteArray(), QY = "0ef5cb1759f6f2e062021d4f973f5bb62031be87ae915cff121586809e3219af".HexToByteArray(), D = "692837e9cf613c0e290462a6f08faadcc7002398f75598d5554698a0cb51cf47".HexToByteArray(), }; internal static readonly byte[] ECDsa256Certificate = ("308201223081c9a00302010202106a3c9e85ba6af1ac4f08111d8bdda340300906072a8648ce3d0401301431123010060355" + "04031309456332353655736572301e170d3135303931303231333533305a170d3136303931303033333533305a3014311230" + "10060355040313094563323536557365723059301306072a8648ce3d020106082a8648ce3d03010703420004448d98ee08ae" + "ba0d8b40f3c6dbd500e8b69f07c70c661771655228ea5a178a910ef5cb1759f6f2e062021d4f973f5bb62031be87ae915cff" + "121586809e3219af300906072a8648ce3d04010349003046022100f221063dca71955d17c8f0e0f63a144c4065578fd9f68e" + "1ae6a7683e209ea742022100ed1db6a8be27cfb20ab43e0ca061622ceff26f7249a0f791e4d6be1a4e52adfa").HexToByteArray(); internal static readonly ECDsaCngKeyValues ECDsaCng384PublicKey = new ECDsaCngKeyValues() { QX = "c59eca607aa5559e6b2f8ac2eeb12d9ab47f420feabeb444c3f71520d7f2280439979323ab5a67344811d296fef6d1bd".HexToByteArray(), QY = "d15f307cc6cc6c8baeeeb168bfb02c34d6eb0621efb3d06ad31c06b29eaf6ec2ec67bf288455e729d82e5a6439f70901".HexToByteArray(), D = "f55ba33e28cea32a014e2fe1213bb4d41cef361f1fee022116b15be50feb96bc946b10a46a9a7a94176787e0928a3e1d".HexToByteArray(), }; internal static readonly byte[] ECDsa384Certificate = ("3082015f3081e6a00302010202101e78eb573e70a2a64744672296988ad7300906072a8648ce3d0401301431123010060355" + "04031309456333383455736572301e170d3135303931303231333634365a170d3136303931303033333634365a3014311230" + "10060355040313094563333834557365723076301006072a8648ce3d020106052b8104002203620004c59eca607aa5559e6b" + "2f8ac2eeb12d9ab47f420feabeb444c3f71520d7f2280439979323ab5a67344811d296fef6d1bdd15f307cc6cc6c8baeeeb1" + "68bfb02c34d6eb0621efb3d06ad31c06b29eaf6ec2ec67bf288455e729d82e5a6439f70901300906072a8648ce3d04010369" + "003066023100a8fbaeeae61953897eae5f0beeeffaca48e89bc0cb782145f39f4ba5b03390ce6a28e432e664adf5ebc6a802" + "040b238b023100dcc19109383b9482fdda68f40a63ee41797dbb8f25c0284155cc4238d682fbb3fb6e86ea0933297e850a26" + "16f6c39bbf").HexToByteArray(); internal static readonly ECDsaCngKeyValues ECDsaCng521PublicKey = new ECDsaCngKeyValues() { QX = "0134af29d1fe5e581fd2ff6194263abcb6f8cb4d9c08bdb384ede9b8663ae2f4e1af6c85eacc69dc768fbfcd856630792e05484cefb1fefb693081dc6490dac579c0".HexToByteArray(), QY = "00bfe103f53cbcb039873b1a3e81a9da9abd71995e722318367281d30b35a338bf356662342b653eff38e85881863b7128ddbb856d8ae158365550bb6330b93d4ef0".HexToByteArray(), D = "0153603164bcef5c9f62388d06dcbf5681479be4397c07ff6f44bb848465e3397537d5f61abc7bc9266d4df6bae1df4847fcfd3dabdda37a2fe549b821ea858d088d".HexToByteArray(), }; internal static readonly ECDsaCngKeyValues ECDsabrainpoolP160r1_PublicKey = new ECDsaCngKeyValues() { QX = "424D9D7A9F07A0D25C6C26A589EE5020C62C367A".HexToByteArray(), QY = "61B4EA3D5940A0AEBCC41B7C1FAF1CF7F477005D".HexToByteArray(), }; internal static readonly byte[] ECDsa521Certificate = ("308201a93082010ca00302010202102c3134fe79bb9daa48df6431f4c1e4f3300906072a8648ce3d04013014311230100603" + "5504031309456335323155736572301e170d3135303931303231333832305a170d3136303931303033333832305a30143112" + "30100603550403130945633532315573657230819b301006072a8648ce3d020106052b8104002303818600040134af29d1fe" + "5e581fd2ff6194263abcb6f8cb4d9c08bdb384ede9b8663ae2f4e1af6c85eacc69dc768fbfcd856630792e05484cefb1fefb" + "693081dc6490dac579c000bfe103f53cbcb039873b1a3e81a9da9abd71995e722318367281d30b35a338bf356662342b653e" + "ff38e85881863b7128ddbb856d8ae158365550bb6330b93d4ef0300906072a8648ce3d040103818b0030818702420090bdf5" + "dfb328501910da4b02ba3ccd41f2bb073608c55f0f2b2e1198496c59b44db9e516a6a63ba7841d22cf590e39d3f09636d0eb" + "cd59a92c105f499e1329615602414285111634719b9bbd10eb7d08655b2fa7d7eb5e225bfdafef15562ae2f9f0c6a943a7bd" + "f0e39223d807b5e2e617a8e424294d90869567326531bcad0f893a0f3a").HexToByteArray(); internal static readonly byte[] EccCert_KeyAgreement = ( "308201553081FDA00302010202105A1C956450FFED894E85DC61E11CD968300A" + "06082A8648CE3D04030230143112301006035504030C09454344482054657374" + "301E170D3135303433303138303131325A170D3136303433303138323131325A" + "30143112301006035504030C094543444820546573743059301306072A8648CE" + "3D020106082A8648CE3D0301070342000477DE73EA00A82250B69E3F24A14CDD" + "C4C47C83993056DD0A2C6C17D5C8E7A054216B9253533D12C082E0C8B91B3B10" + "CDAB564820D417E6D056E4E34BCCA87301A331302F300E0603551D0F0101FF04" + "0403020009301D0603551D0E0416041472DE05F588BF2741C8A28FF99EA399F7" + "AAB2C1B3300A06082A8648CE3D040302034700304402203CDF0CC71C63747BDA" + "2D2D563115AE68D34867E74BCA02738086C316B846CDF2022079F3990E5DCCEE" + "627B2E6E42317D4D279181EE695EE239D0C8516DD53A896EC3").HexToByteArray(); internal static readonly byte[] ECDsa224Certificate = ( "3082026630820214A003020102020900B94BCCE3179BAA21300A06082A8648CE" + "3D040302308198310B30090603550406130255533113301106035504080C0A57" + "617368696E67746F6E3110300E06035504070C075265646D6F6E64311E301C06" + "0355040A0C154D6963726F736F667420436F72706F726174696F6E3120301E06" + "0355040B0C172E4E4554204672616D65776F726B2028436F7265465829312030" + "1E06035504030C174E4953542F53454320502D3232342054657374204B657930" + "1E170D3135313233313232353532345A170D3136303133303232353532345A30" + "8198310B30090603550406130255533113301106035504080C0A57617368696E" + "67746F6E3110300E06035504070C075265646D6F6E64311E301C060355040A0C" + "154D6963726F736F667420436F72706F726174696F6E3120301E060355040B0C" + "172E4E4554204672616D65776F726B2028436F72654658293120301E06035504" + "030C174E4953542F53454320502D3232342054657374204B6579304E30100607" + "2A8648CE3D020106052B81040021033A000452FF02B55AE35AA7FFF1B0A82DC2" + "260083DD7D5893E85FBAD1D663B718176F7D5D9A04B8AEA968E9FECFEE348CDB" + "49A938401783BADAC484A350304E301D0603551D0E041604140EA9C5C4681A6E" + "48CE64E47EE8BBB0BA5FF8AB3E301F0603551D230418301680140EA9C5C4681A" + "6E48CE64E47EE8BBB0BA5FF8AB3E300C0603551D13040530030101FF300A0608" + "2A8648CE3D040302034000303D021D00AC10B79B6FD6BEE113573A1B68A3B771" + "3B9DA2719A9588376E334811021C1AAC3CA829DA79CE223FA83283E6F0A5A59D" + "2399E140D957C1C9DDAF").HexToByteArray(); internal static readonly byte[] ECDsaP256_DigitalSignature_Pfx_Windows = ( "308204470201033082040306092A864886F70D010701A08203F4048203F03082" + "03EC3082016D06092A864886F70D010701A082015E0482015A30820156308201" + "52060B2A864886F70D010C0A0102A081CC3081C9301C060A2A864886F70D010C" + "0103300E0408EC154269C5878209020207D00481A80BAA4AF8660E6FAB7B050B" + "8EF604CFC378652B54FE005DC3C7E2F12E5EFC7FE2BB0E1B3828CAFE752FD64C" + "7CA04AF9FBC5A1F36E30D7D299C52BF6AE65B54B9240CC37C04E7E06330C24E9" + "6D19A67B7015A6BF52C172FFEA719B930DBE310EEBC756BDFF2DF2846EE973A6" + "6C63F4E9130083D64487B35C1941E98B02B6D5A92972293742383C62CCAFB996" + "EAD71A1DF5D0380EFFF25BA60B233A39210FD7D55A9B95CD8A440DF666317430" + "1306092A864886F70D0109153106040401000000305D06092B06010401823711" + "0131501E4E004D006900630072006F0073006F0066007400200053006F006600" + "7400770061007200650020004B00650079002000530074006F00720061006700" + "65002000500072006F007600690064006500723082027706092A864886F70D01" + "0706A0820268308202640201003082025D06092A864886F70D010701301C060A" + "2A864886F70D010C0106300E0408175CCB1790C48584020207D080820230E956" + "E38768A035D8EA911283A63F2E5B6E5B73231CFC4FFD386481DE24B7BB1B0995" + "D614A0D1BD086215CE0054E01EF9CF91B7D80A4ACB6B596F1DFD6CBCA71476F6" + "10C0D6DD24A301E4B79BA6993F15D34A8ADB7115A8605E797A2C6826A4379B65" + "90B56CA29F7C36997119257A827C3CA0EC7F8F819536208C650E324C8F884794" + "78705F833155463A4EFC02B5D5E2608B83F3CAF6C9BB97C1BBBFC6C5584BDCD3" + "9C46A3944915B3845C41429C7792EB4FA3A7EDECCD801F31A4B6EF57D808AEEA" + "AF3D1F55F378EF8EF9632CED16EDA3EFBE4A9D5C5F608CA90A9AC8D3F86462AC" + "219BFFD0B8A87DDD22CF029230369B33FC2B488B5F82702EFC3F270F912EAD2E" + "2402D99F8324164C5CD5959F22DEC0D1D212345B4B3F62848E7D9CFCE2224B61" + "976C107E1B218B4B7614FF65BCCA388F85D6920270D4C588DEED323C416D014F" + "5F648CC2EE941855EB3C889DCB9A345ED11CAE94041A86ED23E5789137A3DE22" + "5F4023D260BB686901F2149B5D7E37102FFF5282995892BDC2EAB48BD5DA155F" + "72B1BD05EE3EDD32160AC852E5B47CA9AEACE24946062E9D7DCDA642F945C9E7" + "C98640DFAC7A2B88E76A560A0B4156611F9BE8B3613C71870F035062BD4E3D9F" + "D896CF373CBFBFD31410972CDE50739FFB8EC9180A52D7F5415EBC997E5A4221" + "349B4BB7D53614630EEEA729A74E0C0D20726FDE5814321D6C265A7DC6BA24CA" + "F2FCE8C8C162733D58E02E08921E70EF838B95C96A5818489782563AE8A2A85F" + "64A95EB350FF8EF6D625AD031BCD303B301F300706052B0E03021A0414C8D96C" + "ED140F5CA3CB92BEFCA32C690804576ABF0414B59D4FECA9944D40EEFDE7FB96" + "196D167B0FA511020207D0").HexToByteArray(); // The PFX in ECDsaP256_DigitalSignature_Pfx_Windows washed through OpenSSL internal static readonly byte[] ECDsaP256_DigitalSignature_Pfx_OpenSsl = ( "308203BE0201033082038406092A864886F70D010701A0820375048203713082" + "036D308201FF06092A864886F70D010706A08201F0308201EC020100308201E5" + "06092A864886F70D010701301C060A2A864886F70D010C0106300E040888F579" + "00302DB63A02020800808201B8F5EDB44F8B2572E85E52946B233A47F03DF776" + "BC3A05CB74B4145A9D3AE3C7FD61B330194E1E154B89929F3FA3908FEE95512A" + "052FDDE8E1913E2CCFD803EE6D868696D86934DCF5300DC951F36BE93E3F4AA2" + "096B926CF8410AF77FFA087213F84F17EB1D36B61AF4AAD87288301569239B9A" + "B66392ADA3D468DC33F42FCEC3BEE78148CA72686BB733DB89FC951AE92FD0F7" + "D5937DE78B1AF984BD13E5127F73A91D40097976AEF00157DCC34B16C1724E5B" + "88090A1A2DA7337C72720A7ED8F1A89C09AB4143C3F6D80B1925AB8F744069F6" + "399D997827F7D0931DCB5E3B09783D1D8555910906B33AD03759D292021C21A2" + "9EA2F29CF9BA4D66E4E69AA9FDCCCB4D49A806DBB804EBEBAED7AE0DD4AD2133" + "1482A3CC5DB246CE59998824B7E46F337F8887D990FA1756D6A039D293B243BB" + "DCFB19AD613A42C5778E7094EA43C3136EF359209790462A36CF87D89B6D76CF" + "BD8C34B8C41D96C83683751B8B067F42017A37D05B599B82B70830B5A93499A0" + "A4791F5DAB2143C8DF35EC7E88B71A0990E7F6FEA304CE594C9280D7B9120816" + "45C87112B1ED85124533792ABEF8B4946F811FB9FE922F6F786E5BFD7D7C43F6" + "48AB43C43F3082016606092A864886F70D010701A0820157048201533082014F" + "3082014B060B2A864886F70D010C0A0102A081B43081B1301C060A2A864886F7" + "0D010C0103300E0408F58B95D6E307213C02020800048190E0FB35890FFB6F30" + "7DD0BD8B10EB10488EAB18702E5AC9F67C557409DF8E3F382D06060FB3B5A08D" + "1EA31313E80A0488B4034C8906BD873A5308E412783684A35DBD9EEACF5D090D" + "AE7390E3309D016C41133946A6CF70E32BE8002CD4F06A90F5BBCE6BF932EC71" + "F634312D315310CE2015B30C51FCC54B60FB3D6E7B734C1ADEBE37056A46AB3C" + "23276B16603FC50C318184302306092A864886F70D01091531160414F20D17B7" + "9B898999F0AA1D5EA333FAEF2BDB2A29305D06092B060104018237110131501E" + "4E004D006900630072006F0073006F0066007400200053006F00660074007700" + "61007200650020004B00650079002000530074006F0072006100670065002000" + "500072006F0076006900640065007230313021300906052B0E03021A05000414" + "96C2244022AB2B809E0F97270F7F4EA7769DD26F04084C0E2946D65F8F220202" + "0800").HexToByteArray(); internal struct ECDsaCngKeyValues { public byte[] QX; public byte[] QY; public byte[] D; } } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using System; namespace MatterHackers.Agg.Image { //==================================================pixfmt_amask_adaptor public sealed class AlphaMaskAdaptor : ImageProxy { private IAlphaMask m_mask; private ArrayPOD<byte> m_span; private enum span_extra_tail_e { span_extra_tail = 256 }; private static readonly byte cover_full = 255; private void realloc_span(int len) { if (len > m_span.Size()) { m_span.Resize(len + (int)span_extra_tail_e.span_extra_tail); } } private void init_span(int len) { init_span(len, cover_full); } private void init_span(int len, byte cover) { realloc_span(len); agg_basics.memset(m_span.Array, 0, cover, len); } private void init_span(int len, byte[] covers, int coversIndex) { realloc_span(len); byte[] array = m_span.Array; for (int i = 0; i < (int)len; i++) { array[i] = covers[coversIndex + i]; } } public AlphaMaskAdaptor(IImageByte image, IAlphaMask mask) : base(image) { linkedImage = image; m_mask = mask; m_span = new ArrayPOD<byte>(255); } public void AttachImage(IImageByte image) { linkedImage = image; } public void attach_alpha_mask(IAlphaMask mask) { m_mask = mask; } public void copy_pixel(int x, int y, Color c) { linkedImage.BlendPixel(x, y, c, m_mask.pixel(x, y)); } public override void copy_hline(int x, int y, int len, Color c) { throw new NotImplementedException(); /* realloc_span((int)len); unsafe { fixed (byte* pBuffer = m_span.Array) { m_mask.fill_hspan(x, y, pBuffer, (int)len); m_LinkedImage.blend_solid_hspan(x, y, len, c, pBuffer); } } */ } public override void blend_hline(int x1, int y, int x2, Color c, byte cover) { int len = x2 - x1 + 1; if (cover == cover_full) { realloc_span(len); m_mask.combine_hspanFullCover(x1, y, m_span.Array, 0, (int)len); linkedImage.blend_solid_hspan(x1, y, (int)len, c, m_span.Array, 0); } else { init_span(len, cover); m_mask.combine_hspan(x1, y, m_span.Array, 0, (int)len); linkedImage.blend_solid_hspan(x1, y, (int)len, c, m_span.Array, 0); } } public override void copy_vline(int x, int y, int len, Color c) { throw new NotImplementedException(); /* realloc_span((int)len); unsafe { fixed (byte* pBuffer = m_span.Array) { m_mask.fill_vspan(x, y, pBuffer, (int)len); m_LinkedImage.blend_solid_vspan(x, y, len, c, pBuffer); } } */ } public override void blend_vline(int x, int y1, int y2, Color c, byte cover) { throw new NotImplementedException(); /* int len = y2 - y1 + 1; init_span(len, cover); unsafe { fixed (byte* pBuffer = m_span.Array) { m_mask.combine_vspan(x, y1, pBuffer, len); throw new System.NotImplementedException("blend_solid_vspan does not take a y2 yet"); //m_pixf.blend_solid_vspan(x, y1, y2, c, pBuffer); } } */ } public override void blend_solid_hspan(int x, int y, int len, Color color, byte[] covers, int coversIndex) { byte[] buffer = m_span.Array; m_mask.combine_hspan(x, y, covers, coversIndex, len); linkedImage.blend_solid_hspan(x, y, len, color, covers, coversIndex); } public override void blend_solid_vspan(int x, int y, int len, Color c, byte[] covers, int coversIndex) { throw new System.NotImplementedException(); #if false init_span((int)len, covers); unsafe { fixed (byte* pBuffer = m_span.Array) { m_mask.combine_vspan(x, y, pBuffer, (int)len); m_LinkedImage.blend_solid_vspan(x, y, len, c, pBuffer); } } #endif } public override void copy_color_hspan(int x, int y, int len, Color[] colors, int colorsIndex) { throw new System.NotImplementedException(); #if false realloc_span((int)len); unsafe { fixed (byte* pBuffer = m_span.GetArray()) { m_mask.fill_hspan(x, y, pBuffer, (int)len); m_pixf.blend_color_hspan(x, y, len, colors, pBuffer, cover_full); } } #endif } public override void copy_color_vspan(int x, int y, int len, Color[] colors, int colorsIndex) { throw new System.NotImplementedException(); #if false realloc_span((int)len); unsafe { fixed (byte* pBuffer = m_span.GetArray()) { m_mask.fill_vspan(x, y, pBuffer, (int)len); m_pixf.blend_color_vspan(x, y, len, colors, pBuffer, cover_full); } } #endif } public override void blend_color_hspan(int x, int y, int len, Color[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { throw new System.NotImplementedException(); #if false unsafe { fixed (byte* pBuffer = m_span.GetArray()) { if (covers != null) { init_span((int)len, covers); m_mask.combine_hspan(x, y, pBuffer, (int)len); } else { realloc_span((int)len); m_mask.fill_hspan(x, y, pBuffer, (int)len); } m_pixf.blend_color_hspan(x, y, len, colors, pBuffer, cover); } } #endif } public override void blend_color_vspan(int x, int y, int len, Color[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { throw new System.NotImplementedException(); #if false unsafe { fixed (byte* pBuffer = m_span.GetArray()) { if (covers != null) { init_span((int)len, covers); m_mask.combine_vspan(x, y, pBuffer, (int)len); } else { realloc_span((int)len); m_mask.fill_vspan(x, y, pBuffer, (int)len); } m_pixf.blend_color_vspan(x, y, len, colors, pBuffer, cover); } } #endif } }; }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Globalization; using System.Drawing.Drawing2D; using XenAdmin.Wlb; using XenAdmin.Model; using XenAdmin.Network; using XenAdmin.Core; using XenAPI; namespace XenAdmin.Dialogs.Wlb { public partial class WlbReportCustomFilter : XenAdmin.Dialogs.XenDialogBase { #region Private Fields private IXenConnection _connection; private Host[] _hosts; private VM[] _vms; private string[] _tags; private List<string> _filters; private WlbReportCustomFilterType _filterType; private Dictionary<string, List<IXenObject>> _tagDictionary; #endregion #region Public Properties public enum WlbReportCustomFilterType { host, vm, tags } #endregion #region Public Methods public List<string> GetSelectedFilters() { return _filters; } #endregion #region Constructors public WlbReportCustomFilter(IXenConnection connection) { InitializeComponent(); this.listViewFilterItem.Columns.Clear(); this.listViewFilterItem.Columns.Add(String.Empty, 25); this.listViewFilterItem.Columns.Add(Messages.WLB_REPORT_VIEW_TAG_COLUMN_HEADER, 250); this.panelListView.Enabled = false; this.panelListView.Visible = false; this.panelTags.Enabled = false; this.panelTags.Visible = false; _connection = connection; } public void InitializeFilterTypeIndex() { this.comboFilterType.SelectedIndex = 0; } #endregion #region Private Methods private void PopulateListViewFilterItem() { this.panelListView.Enabled = false; this.panelListView.Visible = false; this.panelTags.Enabled = true; this.panelTags.Visible = true; this.comboBoxTags.Items.Clear(); if (_connection != null) { _hosts = _connection.Cache.Hosts; _vms = _connection.Cache.VMs; _tags = Tags.GetAllTags(); } switch(_filterType) { case WlbReportCustomFilterType.host: this.labelHost.Enabled = true; this.labelHost.Visible = true; this.labelTags.Enabled = false; this.labelTags.Visible = false; foreach(Host host in _hosts) { this.comboBoxTags.Items.Add(host.Name()); } this.comboBoxTags.SelectedIndex = 0; break; case WlbReportCustomFilterType.vm: this.panelListView.Visible = true; this.panelListView.Enabled = true; this.panelTags.Enabled = false; this.panelTags.Visible = false; this.listViewFilterItem.Items.Clear(); foreach (VM vm in _vms) { ListViewItem lvItem = new ListViewItem(); lvItem.Tag = vm; lvItem.SubItems.Add(vm.Name()); if (this.checkBoxCheckAll.Checked) { lvItem.Checked = true; } this.listViewFilterItem.Items.Add(lvItem); } break; case WlbReportCustomFilterType.tags: this.labelHost.Enabled = false; this.labelHost.Visible = false; this.labelTags.Enabled = true; this.labelTags.Visible = true; _tagDictionary = new Dictionary<string, List<IXenObject>>(); foreach(string tag in _tags) { // Disable invalid tags that contains vms and hosts List<IXenObject> tagUsers = Tags.Users(tag); bool hasHost = false; bool hasVM = false; foreach (IXenObject tagUser in tagUsers) { if (tagUser is VM) { hasVM = true; } if(tagUser is Host) { hasHost = true; } } if (!(hasHost && hasVM)) { _tagDictionary.Add(tag, tagUsers); this.comboBoxTags.Items.Add(tag); } } this.comboBoxTags.SelectedIndex = 0; break; } } #endregion #region Control Event Handlers private void listViewFilterItem_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e) { e.DrawDefault = true; } private void listViewFilterItem_DrawItem(object sender, DrawListViewItemEventArgs e) { if ((WlbReportCustomFilterType)this.comboFilterType.SelectedIndex == WlbReportCustomFilterType.vm) { if (e.Item.Checked) ControlPaint.DrawCheckBox(e.Graphics, e.Bounds.Left + 3, e.Bounds.Top + 1, 15, 15, ButtonState.Checked); else ControlPaint.DrawCheckBox(e.Graphics, e.Bounds.Left + 3, e.Bounds.Top + 1, 15, 15, ButtonState.Normal); } } private void listViewFilterItem_DrawSubItem(object sender, DrawListViewSubItemEventArgs e) { e.DrawText(); } private void comboFilterType_SelectedIndexChanged(object sender, EventArgs e) { _filterType = (WlbReportCustomFilterType)this.comboFilterType.SelectedIndex; PopulateListViewFilterItem(); } private void buttonOK_Click(object sender, EventArgs e) { _filters = new List<string>(); if ((WlbReportCustomFilterType)this.comboFilterType.SelectedIndex == WlbReportCustomFilterType.tags) { List<IXenObject> objLst = new List<IXenObject>(); _tagDictionary.TryGetValue(this.comboBoxTags.SelectedItem.ToString(), out objLst); foreach (IXenObject obj in objLst) { if (obj is VM) { _filters.Add(((VM)obj).uuid); } } } else if ((WlbReportCustomFilterType)this.comboFilterType.SelectedIndex == WlbReportCustomFilterType.host) { Object host = _hosts.GetValue(this.comboBoxTags.SelectedIndex); List<VM> vms = ((Host)host).Connection.ResolveAll(((Host)host).resident_VMs); foreach (VM vm in vms) { _filters.Add(vm.uuid); } } else { foreach (ListViewItem item in this.listViewFilterItem.Items) { if (item.Checked) { /*if (item.Tag is Host) { _filters.Add(((Host)item.Tag).uuid); } else */ if (item.Tag is VM) { _filters.Add(((VM)item.Tag).uuid); } } } } DialogResult = DialogResult.OK; this.Close(); } private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; this.Close(); } private void checkBoxCheckAll_CheckedChanged(object sender, EventArgs e) { foreach (ListViewItem item in this.listViewFilterItem.Items) { if (this.checkBoxCheckAll.Checked) { item.Checked = true; } else { item.Checked = false; } } } #endregion } }
using System; using System.IO; using System.Collections.Generic; using System.Reflection; using Microsoft.CSharp; using System.Text; using System.CodeDom.Compiler; using System.Text.RegularExpressions; using FmbLib.TypeHandlers.Xna; #if XNA using Microsoft.Xna.Framework; #endif #if FEZENGINE using FezEngine.Structure; #endif #if UNITY using UnityEngine; #endif namespace FmbLib { public delegate ILzxDecompressor CreateLzxDecompressor(int window); public static class FmbUtil { public static class Setup { public static CreateLzxDecompressor CreateLzxDecompressor; #if UNITY public static Action<string> Log = null; #else public static Action<string> Log = FmbHelper.DefaultLog; #endif #if XNA public static Microsoft.Xna.Framework.Graphics.GraphicsDevice GraphicsDevice; #endif #if UNITY public static bool TexturesLinear = false; public static bool TexturesWriteOnly = false; #endif } private readonly static Regex GenericSplitRegex = new Regex(@"(\[.*?\])"); private readonly static char[] XNBMagic = { 'X', 'N', 'B' }; private readonly static char[] FMBMagic = { 'F', 'M', 'B' }; private readonly static Dictionary<string, TypeHandler> TypeHandlerReaderMap = new Dictionary<string, TypeHandler>(); private readonly static Dictionary<Type, TypeHandler> TypeHandlerTypeMap = new Dictionary<Type, TypeHandler>(); private static string[] ManifestResourceNames; #if XNA public static bool IsXNA = true; #else public static bool IsXNA = false; #endif #if UNITY public static bool IsUNITY = true; #else public static bool IsUNITY = false; #endif #if FEZENGINE public static bool IsFEZENGINE = true; #else public static bool IsFEZENGINE = false; #endif public static bool IsTEST = false; static FmbUtil() { #if XNA || UNITY ____dotnetassembliesneedtobereferenced____.Add(typeof(Vector3)); #endif #if FEZENGINE ____dotnetassembliesneedtobereferenced____.Add(typeof(TrileSet)); #endif #if XNA GeneratedTypeHandlerAssemblies.Add("MonoGame.Framework"); #endif #if FEZENGINE GeneratedTypeHandlerAssemblies.Add("FezEngine"); GeneratedTypeHandlerAssemblies.Add("ContentSerialization"); #endif GeneratedTypeHandlerSpecialTypes.Add("Matrix"); GeneratedTypeHandlerSpecialTypes.Add("Quaternion"); GeneratedTypeHandlerSpecialTypes.Add("Vector2"); GeneratedTypeHandlerSpecialTypes.Add("Vector3"); GeneratedTypeHandlerSpecialTypes.Add("Vector4"); GeneratedTypeHandlerSpecialTypes.Add("Color"); GeneratedTypeHandlerSpecialTypes.Add("BoundingSphere"); #if UNITY NamespaceRemap.Add(new KeyValuePair<string, string>("Microsoft.Xna.Framework.Content", "UnityEngine")); NamespaceRemap.Add(new KeyValuePair<string, string>("Microsoft.Xna.Framework.Graphics", "UnityEngine")); NamespaceRemap.Add(new KeyValuePair<string, string>("Microsoft.Xna.Framework", "UnityEngine")); #endif } /// <summary> /// List of types that need to be accessed so that the assembly containing them gets referenced /// </summary> private static List<Type> ____dotnetassembliesneedtobereferenced____ = new List<Type>(); /// <summary> /// List of assemblies required for the generated typehandlers. /// </summary> public static List<string> GeneratedTypeHandlerAssemblies = new List<string>(); /// <summary> /// List of types that are not found in BinaryReader, but in XNA's ContentReader /// </summary> public static List<string> GeneratedTypeHandlerSpecialTypes = new List<string>(); /// <summary> /// List of remappings regarding the usings of generated type handlers and other pieces of namespace-sensitive code, f.e. XNA to Unity. /// </summary> public static List<KeyValuePair<string, string>> NamespaceRemap = new List<KeyValuePair<string, string>>(); public static T ReadObject<T>(string input) { return (T) ReadObject(input); } public static object ReadObject(string input) { using (FileStream fis = new FileStream(input, FileMode.Open)) { using (BinaryReader reader = new BinaryReader(fis)) { return ReadObject(reader); } } } public static object ReadObject(BinaryReader reader) { char[] magic = reader.ReadChars(3); return ReadObject(reader, magic[0] == XNBMagic[0] && magic[1] == XNBMagic[1] && magic[2] == XNBMagic[2]); } public static object ReadObject(BinaryReader reader, bool xnb) { BinaryReader origReader = reader; TypeHandler handler; //string[] readerNames = null; TypeHandler[] handlers = null; //object[] sharedResources = null; //FmbHelper.Log("Position pre xnb: " + reader.BaseStream.Position); if (xnb && reader.BaseStream.Position == 3) { object[] xnbData = readXNB(ref reader); //readerNames = (string[]) xnbData[0]; handlers = (TypeHandler[]) xnbData[1]; //sharedResources = (object[]) xnbData[2]; handler = handlers[(int) xnbData[3]]; } else if (xnb) { throw new InvalidOperationException("Can't read a non-asset object without type from a XNB stream!"); } else { handler = GetTypeHandler(reader.ReadString()); } //FmbHelper.Log("Position pre main: " + reader.BaseStream.Position); object obj = handler.Read(reader, xnb); //FmbHelper.Log("Position post main: " + reader.BaseStream.Position); if (xnb) { //TODO read shared resources } if (reader != origReader) { reader.Close(); } return obj; } public static T ReadObject<T>(BinaryReader reader, bool xnb) { return ReadObject<T>(reader, xnb, true); } public static T ReadObject<T>(BinaryReader reader, bool xnb, bool readPrependedData) { BinaryReader origReader = reader; TypeHandler handler; //string[] readerNames = null; TypeHandler[] handlers = null; //object[] sharedResources = null; if (xnb && reader.BaseStream.Position == 3) { object[] xnbData = readXNB(ref reader); //readerNames = (string[]) xnbData[0]; handlers = (TypeHandler[]) xnbData[1]; //sharedResources = (object[]) xnbData[2]; handler = handlers[(int) xnbData[3]]; } else { handler = GetTypeHandler<T>(); if (readPrependedData) { if (xnb) { int id = reader.Read7BitEncodedInt(); //FmbHelper.Log("debug: id: " + (id - 1) + ": " + handler.GetType().FullName); if (id == 0) { return handler.GetDefault<T>(); } } else { string type = reader.ReadString(); if (type == "") { return handler.GetDefault<T>(); } } } } //FmbHelper.Log("Position pre " + handler.Type.Name + ": " + reader.BaseStream.Position); T obj = handler.Read<T>(reader, xnb); //FmbHelper.Log("Position post " + handler.Type.Name + ": " + reader.BaseStream.Position); if (xnb) { //TODO read shared resources } if (reader != origReader) { reader.Close(); } return obj; } public static void WriteObject(string output, object obj_) { if (File.Exists(output)) { return; } using (FileStream fos = new FileStream(output, FileMode.Create)) { using (BinaryWriter writer = new BinaryWriter(fos)) { writer.Write(FMBMagic); WriteObject(writer, obj_); } } } public static void WriteObject(BinaryWriter writer, object obj_) { Type type = obj_.GetType(); writer.Write(type.FullName); TypeHandler handler = GetTypeHandler(type); handler.Write(writer, obj_); } public static void WriteObject<T>(string output, T obj_) { if (File.Exists(output)) { return; } using (FileStream fos = new FileStream(output, FileMode.Create)) { using (BinaryWriter writer = new BinaryWriter(fos)) { writer.Write(FMBMagic); WriteObject<T>(writer, obj_); } } } public static void WriteObject<T>(BinaryWriter writer, T obj_) { if (obj_ == null) { writer.Write(""); return; } writer.Write(typeof(T).FullName); TypeHandler handler = GetTypeHandler(typeof(T)); handler.Write(writer, obj_); } private static object[] readXNB(ref BinaryReader reader) { reader.ReadByte(); //w reader.ReadByte(); //0x05 byte flagBits = reader.ReadByte(); bool isCompressed = (flagBits & 0x80) == 0x80; int size = reader.ReadInt32(); //file size, optionally compressed size //FmbLib is currently forced to use an extension for Lzx. //Most, if not all current Lzx decompressors in C# require //FmbLib to become MSPL / LGPL, not MIT. This further would //cause other dependencies to need to change their licenses, too. if (isCompressed) { if (FmbUtil.Setup.CreateLzxDecompressor == null) { throw new InvalidOperationException("Cannot read compressed XNBs with FmbUtil.Setup.CreateLzxDecompressor == null"); } byte[] buffer = new byte[reader.ReadInt32()]; MemoryStream stream = new MemoryStream(buffer, 0, buffer.Length, true, true); ILzxDecompressor lzx = FmbUtil.Setup.CreateLzxDecompressor(16); long startPos = reader.BaseStream.Position; long pos = startPos; while (pos - startPos < (size - 14)) { int high = reader.BaseStream.ReadByte(); int low = reader.BaseStream.ReadByte(); int blockSize = (high << 8) | low; int frameSize = 0x8000; if (high == 0xFF) { high = low; low = reader.BaseStream.ReadByte(); frameSize = (high << 8) | low; high = reader.BaseStream.ReadByte(); low = reader.BaseStream.ReadByte(); blockSize = (high << 8) | low; pos += 5; } else { pos += 2; } if (blockSize == 0 || frameSize == 0) { break; } lzx.Decompress(reader.BaseStream, blockSize, stream, frameSize); pos += blockSize; reader.BaseStream.Seek(pos, SeekOrigin.Begin); } stream.Seek(0, SeekOrigin.Begin); reader.Close(); reader = new BinaryReader(stream); } string[] readerNames = new string[reader.Read7BitEncodedInt()]; TypeHandler[] handlers = new TypeHandler[readerNames.Length]; for (int i = 0; i < readerNames.Length; i++) { readerNames[i] = reader.ReadString(); reader.ReadInt32(); //reader version //FmbHelper.Log("debug: handler: " + i + ": " + readerNames[i]); handlers[i] = GetTypeHandler(readerNames[i]); } object[] sharedResources = new object[reader.Read7BitEncodedInt()]; return new object[] { readerNames, handlers, sharedResources, reader.Read7BitEncodedInt() - 1}; } public static TypeHandler GetTypeHandler(string readerName) { TypeHandler handler; if (TypeHandlerReaderMap.TryGetValue(readerName, out handler)) { return handler; } handler = getHandler(readerName, null) ?? GenerateHandler(readerName, null); TypeHandlerReaderMap[readerName] = handler; return handler; } public static TypeHandler GetTypeHandler<T>() { return GetTypeHandler(typeof(T)); } public static TypeHandler GetTypeHandler(Type type) { TypeHandler handler; if (TypeHandlerTypeMap.TryGetValue(type, out handler)) { return handler; } handler = getHandler(null, type) ?? GenerateHandler(null, type); TypeHandlerTypeMap[type] = handler; return handler; } private static TypeHandler getHandler(string readerName, Type type) { string typeName = getTypeName(readerName, type); string handlerName; //TODO check if enum, ... if (type == null) { type = FmbHelper.FindType(typeName); } if (type == null && typeName.Contains("[[")) { type = FmbHelper.FindType(typeName.Substring(0, typeName.IndexOf("[["))); } if (type != null && type.IsEnum) { return FmbHelper.GetGenericTypeHandler(typeof(EnumHandler<>), type); } if (type != null && type.IsArray) { return FmbHelper.GetGenericTypeHandler(typeof(ArrayHandler<>), type.GetElementType()); } //FmbHelper.Log("Getting TypeHandler for " + typeName); Type[] types = Assembly.GetExecutingAssembly().GetTypes(); //FmbHelper.Log("typeName: " + typeName); if (typeName.Contains("[[") || (type != null && type.IsGenericType)) { int length = typeName.IndexOf("[["); if (length < 0) { length = typeName.Length; } handlerName = typeName.Substring(0, typeName.IndexOf("`")) + "Handler" + typeName.Substring(typeName.IndexOf("`"), length - typeName.IndexOf("`")); List<Type> genericParams = FmbHelper.GetGenericParamTypes(typeName); for (int i = 0; i < types.Length; i++) { string typeName_ = getTypeName(types[i].Name, null); if (typeName_ == handlerName && types[i].GetGenericArguments().Length == genericParams.Count) { return (TypeHandler) types[i].MakeGenericType(genericParams.ToArray()).GetConstructor(new Type[0]).Invoke(new object[0]); } } return null; } handlerName = typeName + "Handler"; for (int i = 0; i < types.Length; i++) { if (getTypeName(types[i].Name, null) == handlerName) { //FmbHelper.Log("Found " + types[i].Name); return (TypeHandler) types[i].GetConstructor(new Type[0]).Invoke(new object[0]); } } return null; } public static TypeHandler GenerateHandler(string readerName, Type type) { TypeHandler handler = null; string typeName = getTypeName(readerName, type); if (type == null) { type = FmbHelper.FindType(typeName); } FmbHelper.Log("Generating TypeHandler for " + typeName); Assembly assembly = Assembly.GetExecutingAssembly(); if (ManifestResourceNames == null) { ManifestResourceNames = assembly.GetManifestResourceNames(); } string path = null; string comparisonReader = typeName + "Reader.txt"; string comparisonHandler = typeName + "Handler.txt"; for (int i = 0; i < ManifestResourceNames.Length; i++) { if ( ManifestResourceNames[i].EndsWith(comparisonReader) || ManifestResourceNames[i].EndsWith(comparisonHandler) ) { path = ManifestResourceNames[i]; break; } } FmbHelper.Log("Generating TypeHandler<" + typeName + "> from " + path); string source; using (Stream s = assembly.GetManifestResourceStream(path)) { if (s == null) { FmbHelper.Log("Resource cannot be loaded."); return null; } using (StreamReader sr = new StreamReader(s)) { source = GenerateHandlerSource(sr, typeName, type); } } CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; parameters.CompilerOptions = "/optimize"; AssemblyName[] references = assembly.GetReferencedAssemblies(); for (int i = 0; i < references.Length; i++) { parameters.ReferencedAssemblies.Add(references[i].Name); } parameters.ReferencedAssemblies.Add(assembly.Location); for (int i = 0; i < GeneratedTypeHandlerAssemblies.Count; i++) { string reference = GeneratedTypeHandlerAssemblies[i]; if (parameters.ReferencedAssemblies.Contains(reference)) { continue; } parameters.ReferencedAssemblies.Add(reference); } using (CSharpCodeProvider provider = new CSharpCodeProvider()) { try { CompilerResults results = provider.CompileAssemblyFromSource(parameters, source); if (results.Errors.HasErrors) { FmbHelper.Log("Errors while generating TypeHandler:"); foreach (CompilerError error in results.Errors) { FmbHelper.Log(error.ToString()); } FmbHelper.Log("GeneratedTypeHandler source:"); FmbHelper.Log(source); FmbHelper.Log("Referenced assemblies:"); for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++) { FmbHelper.Log(parameters.ReferencedAssemblies[i]); } } else { Type compiledType = results.CompiledAssembly.GetType("JIT" + typeName + "Handler"); handler = (TypeHandler) compiledType.GetConstructor(new Type[0]).Invoke(new object[0]); } } catch (Exception e) { FmbHelper.Log("Error while generating TypeHandler:"); FmbHelper.Log(e.ToString()); FmbHelper.Log("GeneratedTypeHandler source:"); FmbHelper.Log(source); FmbHelper.Log("Referenced assemblies:"); for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++) { FmbHelper.Log(parameters.ReferencedAssemblies[i]); } } } return handler; } public static string GenerateHandlerSource(StreamReader sr, string typeName, Type type) { return GenerateHandlerSource(sr, typeName, type, "JIT" + typeName + "Handler", null); } public static string GenerateHandlerSource(StreamReader sr, string typeName, Type type, string handlerName, string @namespace) { if (type == null) { type = FmbHelper.FindType(typeName); } if (type == null) { FmbHelper.Log("Type not found for handler to generate: " + typeName); } string tab = @namespace == null ? "" : "\t"; string usings = "using FmbLib;\nusing System;\nusing System.IO;\n"; StringBuilder readerBuilder = new StringBuilder(); StringBuilder writerBuilder = new StringBuilder(); string readerObjectConstruction = typeName + " obj = new " + typeName + "();\n"; string writerObjectCast = typeName + " obj = (" + typeName + ") obj_;\n"; bool usingsComplete = false; string line; while ((line = sr.ReadLine()) != null) { if (line.StartsWith("##")) { continue; } line = line.Trim(); if (line.Length == 0) { continue; } if (line.StartsWith("#if ")) { line = line.Substring(4); bool not = line.StartsWith("!"); if (not) { line = line.Substring(1); } if (line == "XNA") { line = "FmbUtil.IsXNA"; } else if (line == "UNITY") { line = "FmbUtil.IsUNITY"; } else if (line == "FEZENGINE") { line = "FmbUtil.IsFEZENGINE"; } else if (line == "TEST") { line = "FmbUtil.IsTEST"; } FmbHelper.AppendTo(tab, readerBuilder, writerBuilder); FmbHelper.AppendTo("\t\t", readerBuilder, writerBuilder); FmbHelper.AppendTo("if (", readerBuilder, writerBuilder); if (not) { FmbHelper.AppendTo("!", readerBuilder, writerBuilder); } FmbHelper.AppendTo(line, readerBuilder, writerBuilder); FmbHelper.AppendTo(") {\n", readerBuilder, writerBuilder); continue; } if (line == ("#endif")) { FmbHelper.AppendTo(tab, readerBuilder, writerBuilder); FmbHelper.AppendTo("\t\t}\n", readerBuilder, writerBuilder); continue; } if (!usingsComplete && line.StartsWith("using ")) { line = line.Substring(6, line.Length - 6 - 1); for (int i = 0; i < NamespaceRemap.Count; i++) { line = line.Replace(NamespaceRemap[i].Key, NamespaceRemap[i].Value); } line = "using " + line + ";\n"; if (!usings.Contains(line)) { usings += line; } continue; } usingsComplete = true; if (line.StartsWith("#rc ") || line.StartsWith("#wc ")) { bool read = !line.StartsWith("#wc "); line = line.Substring(4); if (read) { readerObjectConstruction = line + "\n"; } else { writerObjectCast = line + "\n"; } continue; } if (!line.Contains(" ") || line.StartsWith("#r ") || line.StartsWith("#w ")) { bool read = !line.StartsWith("#w "); if (line.StartsWith("#")) { line = line.Substring(3); } bool isMethod = type != null && type.GetMethod(line) != null; StringBuilder lineBuilder = read ? readerBuilder : writerBuilder; lineBuilder.Append(tab).Append("\t\t"); if (isMethod) { lineBuilder.Append("obj."); } lineBuilder.Append(line); if (isMethod) { lineBuilder.Append("();"); } lineBuilder.AppendLine(); continue; } FmbHelper.AppendTo(tab, readerBuilder, writerBuilder); FmbHelper.AppendTo("\t\t", readerBuilder, writerBuilder); int indexSplit = line.IndexOf(" "); string var = line.Substring(0, indexSplit); string binaryType = line.Substring(indexSplit + 1); readerBuilder.Append("obj.").Append(var).Append(" = "); if (binaryType.StartsWith("Object<")) { readerBuilder.Append("FmbUtil.Read").Append(binaryType).Append("(reader, xnb);"); } else if (GeneratedTypeHandlerSpecialTypes.Contains(binaryType)) { readerBuilder.Append("FmbUtil.ReadObject<").Append(binaryType).Append(">(reader, xnb, false);"); } else { readerBuilder.Append("reader.Read").Append(binaryType).Append("();"); } readerBuilder.AppendLine(); if (binaryType.StartsWith("Object<")) { writerBuilder.Append("FmbUtil.WriteObject(writer, obj.").Append(var); } else if (GeneratedTypeHandlerSpecialTypes.Contains(binaryType)) { writerBuilder.Append("FmbUtil.GetTypeHandler<").Append(binaryType).Append(">().Write(writer, obj.").Append(var); } else { writerBuilder.Append("writer.Write(obj.").Append(var); } writerBuilder.Append(");\n"); } StringBuilder builder = new StringBuilder() .AppendLine(usings); if (@namespace != null) { builder.Append("namespace ").Append(@namespace).AppendLine(" {"); } builder.Append(tab).Append("public class ").Append(handlerName).Append(" : TypeHandler<").Append(typeName).AppendLine("> {") .AppendLine() .Append(tab).AppendLine("\tpublic override object Read(BinaryReader reader, bool xnb) {") .Append(tab).Append("\t\t").AppendLine(readerObjectConstruction) .AppendLine(readerBuilder.ToString()) .Append(tab).AppendLine("\t\treturn obj;") .Append(tab).AppendLine("\t}") .AppendLine() .Append(tab).AppendLine("\tpublic override void Write(BinaryWriter writer, object obj_) {") .Append(tab).Append("\t\t").AppendLine(writerObjectCast) .Append(writerBuilder.ToString()) .Append(tab).AppendLine("\t}") .Append(tab).AppendLine("}"); if (@namespace != null) { builder.AppendLine("}"); } return builder.ToString(); } private static string getTypeName(string readerName, Type type) { string typeName; if (type != null) { typeName = type.Name; Type[] genericArgs = type.GetGenericArguments(); if (genericArgs.Length != 0) { typeName += "["; for (int i = 0; i < genericArgs.Length; i++) { typeName += "["; typeName += genericArgs[i].FullName; typeName += ", "; typeName += genericArgs[i].Assembly.GetName().Name; typeName += "]"; if (i != genericArgs.Length - 1) { typeName += ","; } } typeName += "]"; } } else { typeName = readerName; FmbHelper.Log("Input type name: " + typeName); if (typeName.Contains("Readers")) { //FmbHelper.Log("debug warning: " + typeName + " contains \"Readers\". In case of failure, debug."); typeName = typeName.Replace("Readers", "Riidars"); } if (typeName.Contains("[[")) { //generic instantiated type typeName = typeName.Substring(typeName.LastIndexOf(".", typeName.IndexOf("Reader")) + 1); typeName = typeName.Replace("Reader", ""); } else if (typeName.Contains("`")) { //generic type typeName = typeName.Substring(typeName.LastIndexOf(".") + 1); typeName = typeName.Replace("Reader", ""); } else if (typeName.Contains("Reader")) { //xna reader typeName = typeName.Substring(0, typeName.LastIndexOf("Reader")); typeName = typeName.Substring(typeName.LastIndexOf(".") + 1); } FmbHelper.Log("Got type name: " + typeName); } return typeName; } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Globalization; using System.IO; using System.Text; using NLog.MessageTemplates; namespace NLog.Internal { /// <summary> /// Helpers for <see cref="StringBuilder"/>, which is used in e.g. layout renderers. /// </summary> internal static class StringBuilderExt { /// <summary> /// Renders the specified log event context item and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">append to this</param> /// <param name="value">value to be appended</param> /// <param name="format">format string. If @, then serialize the value with the Default JsonConverter.</param> /// <param name="formatProvider">provider, for example culture</param> public static void AppendFormattedValue(this StringBuilder builder, object value, string format, IFormatProvider formatProvider) { string stringValue = value as string; if (stringValue != null && string.IsNullOrEmpty(format)) { builder.Append(value); // Avoid automatic quotes } else if (format == MessageTemplates.ValueFormatter.FormatAsJson) { ValueFormatter.Instance.FormatValue(value, null, CaptureType.Serialize, formatProvider, builder); } else if (value != null) { ValueFormatter.Instance.FormatValue(value, format, CaptureType.Normal, formatProvider, builder); } } /// <summary> /// Appends int without using culture, and most importantly without garbage /// </summary> /// <param name="builder"></param> /// <param name="value">value to append</param> public static void AppendInvariant(this StringBuilder builder, int value) { // Deal with negative numbers if (value < 0) { builder.Append('-'); uint uint_value = uint.MaxValue - ((uint)value) + 1; //< This is to deal with Int32.MinValue AppendInvariant(builder, uint_value); } else { AppendInvariant(builder, (uint)value); } } /// <summary> /// Appends uint without using culture, and most importantly without garbage /// /// Credits Gavin Pugh - https://www.gavpugh.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/ /// </summary> /// <param name="builder"></param> /// <param name="value">value to append</param> public static void AppendInvariant(this StringBuilder builder, uint value) { if (value == 0) { builder.Append('0'); return; } int digitCount = CalculateDigitCount(value); ApppendValueWithDigitCount(builder, value, digitCount); } private static int CalculateDigitCount(uint value) { // Calculate length of integer when written out int length = 0; uint length_calc = value; do { length_calc /= 10; length++; } while (length_calc > 0); return length; } private static void ApppendValueWithDigitCount(StringBuilder builder, uint value, int digitCount) { // Pad out space for writing. builder.Append('0', digitCount); int strpos = builder.Length; // We're writing backwards, one character at a time. while (digitCount > 0) { strpos--; // Lookup from static char array, to cover hex values too builder[strpos] = charToInt[value % 10]; value /= 10; digitCount--; } } private static readonly char[] charToInt = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; /// <summary> /// Convert DateTime into UTC and format to yyyy-MM-ddTHH:mm:ss.fffffffZ - ISO 6801 date (Round-Trip-Time) /// </summary> public static void AppendXmlDateTimeRoundTrip(this StringBuilder builder, DateTime dateTime) { if (dateTime.Kind == DateTimeKind.Unspecified) dateTime = new DateTime(dateTime.Ticks, DateTimeKind.Utc); else dateTime = dateTime.ToUniversalTime(); builder.Append4DigitsZeroPadded(dateTime.Year); builder.Append('-'); builder.Append2DigitsZeroPadded(dateTime.Month); builder.Append('-'); builder.Append2DigitsZeroPadded(dateTime.Day); builder.Append('T'); builder.Append2DigitsZeroPadded(dateTime.Hour); builder.Append(':'); builder.Append2DigitsZeroPadded(dateTime.Minute); builder.Append(':'); builder.Append2DigitsZeroPadded(dateTime.Second); int fraction = (int)(dateTime.Ticks % 10000000); if (fraction > 0) { builder.Append('.'); // Remove trailing zeros int max_digit_count = 7; while (fraction % 10 == 0) { --max_digit_count; fraction /= 10; } // Append the remaining fraction int digitCount = CalculateDigitCount((uint)fraction); if (max_digit_count > digitCount) builder.Append('0', max_digit_count - digitCount); ApppendValueWithDigitCount(builder, (uint)fraction, digitCount); } builder.Append('Z'); } /// <summary> /// Clears the provider StringBuilder /// </summary> /// <param name="builder"></param> public static void ClearBuilder(this StringBuilder builder) { #if !SILVERLIGHT && !NET3_5 builder.Clear(); #else builder.Length = 0; #endif } /// <summary> /// Copies the contents of the StringBuilder to the MemoryStream using the specified encoding (Without BOM/Preamble) /// </summary> /// <param name="builder">StringBuilder source</param> /// <param name="ms">MemoryStream destination</param> /// <param name="encoding">Encoding used for converter string into byte-stream</param> /// <param name="transformBuffer">Helper char-buffer to minimize memory allocations</param> public static void CopyToStream(this StringBuilder builder, MemoryStream ms, Encoding encoding, char[] transformBuffer) { #if !SILVERLIGHT || WINDOWS_PHONE if (transformBuffer != null) { int charCount; int byteCount = encoding.GetMaxByteCount(builder.Length); ms.SetLength(ms.Position + byteCount); for (int i = 0; i < builder.Length; i += transformBuffer.Length) { charCount = Math.Min(builder.Length - i, transformBuffer.Length); builder.CopyTo(i, transformBuffer, 0, charCount); byteCount = encoding.GetBytes(transformBuffer, 0, charCount, ms.GetBuffer(), (int)ms.Position); ms.Position += byteCount; } if (ms.Position != ms.Length) { ms.SetLength(ms.Position); } } else #endif { // Faster than MemoryStream, but generates garbage var str = builder.ToString(); byte[] bytes = encoding.GetBytes(str); ms.Write(bytes, 0, bytes.Length); } } public static void CopyToBuffer(this StringBuilder builder, char[] destination, int destinationIndex) { #if !SILVERLIGHT || WINDOWS_PHONE builder.CopyTo(0, destination, destinationIndex, builder.Length); #else builder.ToString().CopyTo(0, destination, destinationIndex, builder.Length); #endif } /// <summary> /// Copies the contents of the StringBuilder to the destination StringBuilder /// </summary> /// <param name="builder">StringBuilder source</param> /// <param name="destination">StringBuilder destination</param> public static void CopyTo(this StringBuilder builder, StringBuilder destination) { int sourceLength = builder.Length; if (sourceLength > 0) { destination.EnsureCapacity(sourceLength + destination.Length); if (sourceLength < 8) { // Skip char-buffer allocation for small strings for (int i = 0; i < sourceLength; ++i) destination.Append(builder[i]); } else if (sourceLength < 512) { // Single char-buffer allocation through string-object destination.Append(builder.ToString()); } else { #if !SILVERLIGHT || WINDOWS_PHONE // Reuse single char-buffer allocation for large StringBuilders char[] buffer = new char[256]; for (int i = 0; i < sourceLength; i += buffer.Length) { int charCount = Math.Min(sourceLength - i, buffer.Length); builder.CopyTo(i, buffer, 0, charCount); destination.Append(buffer, 0, charCount); } #else destination.Append(builder.ToString()); #endif } } } /// <summary> /// Scans the StringBuilder for the position of needle character /// </summary> /// <param name="builder">StringBuilder source</param> /// <param name="needle">needle character to search for</param> /// <param name="startPos"></param> /// <returns>Index of the first occurrence (Else -1)</returns> public static int IndexOf(this StringBuilder builder, char needle, int startPos = 0) { for (int i = startPos; i < builder.Length; ++i) if (builder[i] == needle) return i; return -1; } /// <summary> /// Scans the StringBuilder for the position of needle character /// </summary> /// <param name="builder">StringBuilder source</param> /// <param name="needles">needle characters to search for</param> /// <param name="startPos"></param> /// <returns>Index of the first occurrence (Else -1)</returns> public static int IndexOfAny(this StringBuilder builder, char[] needles, int startPos = 0) { for (int i = startPos; i < builder.Length; ++i) { if (CharArrayContains(builder[i], needles)) return i; } return -1; } private static bool CharArrayContains(char searchChar, char[] needles) { for (int i = 0; i < needles.Length; ++i) { if (needles[i] == searchChar) return true; } return false; } /// <summary> /// Compares the contents of two StringBuilders /// </summary> /// <remarks> /// Correct implementation of <see cref="StringBuilder.Equals(StringBuilder)" /> that also works when <see cref="StringBuilder.Capacity"/> is not the same /// </remarks> /// <returns>True when content is the same</returns> public static bool EqualTo(this StringBuilder builder, StringBuilder other) { if (builder.Length != other.Length) return false; for (int x = 0; x < builder.Length; ++x) { if (builder[x] != other[x]) { return false; } } return true; } /// <summary> /// Compares the contents of a StringBuilder and a String /// </summary> /// <returns>True when content is the same</returns> public static bool EqualTo(this StringBuilder builder, string other) { if (builder.Length != other.Length) return false; for (int i = 0; i < other.Length; ++i) { if (builder[i] != other[i]) return false; } return true; } /// <summary> /// Append a number and pad with 0 to 2 digits /// </summary> /// <param name="builder">append to this</param> /// <param name="number">the number</param> internal static void Append2DigitsZeroPadded(this StringBuilder builder, int number) { builder.Append((char)((number / 10) + '0')); builder.Append((char)((number % 10) + '0')); } /// <summary> /// Append a number and pad with 0 to 4 digits /// </summary> /// <param name="builder">append to this</param> /// <param name="number">the number</param> internal static void Append4DigitsZeroPadded(this StringBuilder builder, int number) { builder.Append((char)(((number / 1000) % 10) + '0')); builder.Append((char)(((number / 100) % 10) + '0')); builder.Append((char)(((number / 10) % 10) + '0')); builder.Append((char)(((number / 1) % 10) + '0')); } /// <summary> /// Append a int type (byte, int) as string /// </summary> internal static void AppendIntegerAsString(this StringBuilder sb, IConvertible value, TypeCode objTypeCode) { switch (objTypeCode) { case TypeCode.Byte: sb.AppendInvariant(value.ToByte(CultureInfo.InvariantCulture)); break; case TypeCode.SByte: sb.AppendInvariant(value.ToSByte(CultureInfo.InvariantCulture)); break; case TypeCode.Int16: sb.AppendInvariant(value.ToInt16(CultureInfo.InvariantCulture)); break; case TypeCode.Int32: sb.AppendInvariant(value.ToInt32(CultureInfo.InvariantCulture)); break; case TypeCode.Int64: { long int64 = value.ToInt64(CultureInfo.InvariantCulture); if (int64 < int.MaxValue && int64 > int.MinValue) sb.AppendInvariant((int)int64); else sb.Append(int64); } break; case TypeCode.UInt16: sb.AppendInvariant(value.ToUInt16(CultureInfo.InvariantCulture)); break; case TypeCode.UInt32: sb.AppendInvariant(value.ToUInt32(CultureInfo.InvariantCulture)); break; case TypeCode.UInt64: { ulong uint64 = value.ToUInt64(CultureInfo.InvariantCulture); if (uint64 < uint.MaxValue) sb.AppendInvariant((uint)uint64); else sb.Append(uint64); } break; default: sb.Append(XmlHelper.XmlConvertToString(value, objTypeCode)); break; } } public static void TrimRight(this StringBuilder sb, int startPos = 0) { int i = sb.Length - 1; for (; i >= startPos; i--) if (!char.IsWhiteSpace(sb[i])) break; if (i < sb.Length - 1) sb.Length = i + 1; } } }
using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Abp.Configuration; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Events.Bus.Entities; using Abp.Events.Bus.Handlers; using Abp.Runtime.Caching; namespace Abp.Localization { /// <summary> /// Manages host and tenant languages. /// </summary> public class ApplicationLanguageManager : IApplicationLanguageManager, IEventHandler<EntityChangedEventData<ApplicationLanguage>>, ISingletonDependency { /// <summary> /// Cache name for languages. /// </summary> public const string CacheName = "AbpZeroLanguages"; private ITypedCache<int, Dictionary<string, ApplicationLanguage>> LanguageListCache { get { return _cacheManager.GetCache<int, Dictionary<string, ApplicationLanguage>>(CacheName); } } private readonly IRepository<ApplicationLanguage> _languageRepository; private readonly ICacheManager _cacheManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly ISettingManager _settingManager; /// <summary> /// Initializes a new instance of the <see cref="ApplicationLanguageManager"/> class. /// </summary> public ApplicationLanguageManager( IRepository<ApplicationLanguage> languageRepository, ICacheManager cacheManager, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager) { _languageRepository = languageRepository; _cacheManager = cacheManager; _unitOfWorkManager = unitOfWorkManager; _settingManager = settingManager; } /// <summary> /// Gets list of all languages available to given tenant (or null for host) /// </summary> /// <param name="tenantId">TenantId or null for host</param> public async Task<IReadOnlyList<ApplicationLanguage>> GetLanguagesAsync(int? tenantId) { return (await GetLanguageDictionary(tenantId)).Values.ToImmutableList(); } /// <summary> /// Adds a new language. /// </summary> /// <param name="language">The language.</param> [UnitOfWork] public virtual async Task AddAsync(ApplicationLanguage language) { if ((await GetLanguagesAsync(language.TenantId)).Any(l => l.Name == language.Name)) { throw new AbpException("There is already a language with name = " + language.Name); //TODO: LOCALIZE? } using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant)) { await _languageRepository.InsertAsync(language); await _unitOfWorkManager.Current.SaveChangesAsync(); } } /// <summary> /// Deletes a language. /// </summary> /// <param name="tenantId">Tenant Id or null for host.</param> /// <param name="languageName">Name of the language.</param> [UnitOfWork] public virtual async Task RemoveAsync(int? tenantId, string languageName) { var currentLanguage = (await GetLanguagesAsync(tenantId)).FirstOrDefault(l => l.Name == languageName); if (currentLanguage == null) { return; } if (currentLanguage.TenantId == null && tenantId != null) { throw new AbpException("Can not delete a host language from tenant!"); //TODO: LOCALIZE? } using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant)) { await _languageRepository.DeleteAsync(currentLanguage.Id); await _unitOfWorkManager.Current.SaveChangesAsync(); } } /// <summary> /// Updates a language. /// </summary> /// <param name="language">The language to be updated</param> [UnitOfWork] public virtual async Task UpdateAsync(int? tenantId, ApplicationLanguage language) { var existingLanguageWithSameName = (await GetLanguagesAsync(language.TenantId)).FirstOrDefault(l => l.Name == language.Name); if (existingLanguageWithSameName != null) { if (existingLanguageWithSameName.Id != language.Id) { throw new AbpException("There is already a language with name = " + language.Name); //TODO: LOCALIZE } } if (language.TenantId == null && tenantId != null) { throw new AbpException("Can not update a host language from tenant"); //TODO: LOCALIZE } using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant)) { await _languageRepository.UpdateAsync(language); await _unitOfWorkManager.Current.SaveChangesAsync(); } } /// <summary> /// Gets the default language or null for a tenant or the host. /// </summary> /// <param name="tenantId">Tenant Id of null for host</param> public async Task<ApplicationLanguage> GetDefaultLanguageOrNullAsync(int? tenantId) { var defaultLanguageName = tenantId.HasValue ? await _settingManager.GetSettingValueForTenantAsync(LocalizationSettingNames.DefaultLanguage, tenantId.Value) : await _settingManager.GetSettingValueForApplicationAsync(LocalizationSettingNames.DefaultLanguage); return (await GetLanguagesAsync(tenantId)).FirstOrDefault(l => l.Name == defaultLanguageName); } /// <summary> /// Sets the default language for a tenant or the host. /// </summary> /// <param name="tenantId">Tenant Id of null for host</param> /// <param name="languageName">Name of the language.</param> public async Task SetDefaultLanguageAsync(int? tenantId, string languageName) { var cultureInfo = CultureInfo.GetCultureInfo(languageName); if (tenantId.HasValue) { await _settingManager.ChangeSettingForTenantAsync(tenantId.Value, LocalizationSettingNames.DefaultLanguage, cultureInfo.Name); } else { await _settingManager.ChangeSettingForApplicationAsync(LocalizationSettingNames.DefaultLanguage, cultureInfo.Name); } } public void HandleEvent(EntityChangedEventData<ApplicationLanguage> eventData) { LanguageListCache.Remove(eventData.Entity.TenantId ?? 0); //Also invalidate the language script cache _cacheManager.GetCache("AbpLocalizationScripts").Clear(); //TODO: CAN BE AN OPTIMIZATION? } private async Task<Dictionary<string, ApplicationLanguage>> GetLanguageDictionary(int? tenantId) { //Creates a copy of the cached dictionary (to not modify it) var languageDictionary = new Dictionary<string, ApplicationLanguage>(await GetLanguageDictionaryFromCacheAsync(null)); if (tenantId == null) { return languageDictionary; } //Override tenant languages foreach (var tenantLanguage in await GetLanguageDictionaryFromCacheAsync(tenantId.Value)) { languageDictionary[tenantLanguage.Key] = tenantLanguage.Value; } return languageDictionary; } private Task<Dictionary<string, ApplicationLanguage>> GetLanguageDictionaryFromCacheAsync(int? tenantId) { return LanguageListCache.GetAsync(tenantId ?? 0, () => GetLanguagesFromDatabaseAsync(tenantId)); } [UnitOfWork] protected virtual async Task<Dictionary<string, ApplicationLanguage>> GetLanguagesFromDatabaseAsync(int? tenantId) { using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant)) { return (await _languageRepository.GetAllListAsync(l => l.TenantId == tenantId)).ToDictionary(l => l.Name); } } } }
// // 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. // using System; using System.Collections.Generic; using System.IO; using System.Security.AccessControl; using DiscUtils.Internal; using DiscUtils.Streams; namespace DiscUtils.Registry { /// <summary> /// A registry hive. /// </summary> public sealed class RegistryHive : IDisposable { private const long BinStart = 4 * Sizes.OneKiB; private readonly List<BinHeader> _bins; private Stream _fileStream; private readonly HiveHeader _header; private readonly Ownership _ownsStream; /// <summary> /// Initializes a new instance of the RegistryHive class. /// </summary> /// <param name="hive">The stream containing the registry hive.</param> /// <remarks> /// The created object does not assume ownership of the stream. /// </remarks> public RegistryHive(Stream hive) : this(hive, Ownership.None) {} /// <summary> /// Initializes a new instance of the RegistryHive class. /// </summary> /// <param name="hive">The stream containing the registry hive.</param> /// <param name="ownership">Whether the new object assumes object of the stream.</param> public RegistryHive(Stream hive, Ownership ownership) { _fileStream = hive; _fileStream.Position = 0; _ownsStream = ownership; byte[] buffer = StreamUtilities.ReadExact(_fileStream, HiveHeader.HeaderSize); _header = new HiveHeader(); _header.ReadFrom(buffer, 0); _bins = new List<BinHeader>(); int pos = 0; while (pos < _header.Length) { _fileStream.Position = BinStart + pos; byte[] headerBuffer = StreamUtilities.ReadExact(_fileStream, BinHeader.HeaderSize); BinHeader header = new BinHeader(); header.ReadFrom(headerBuffer, 0); _bins.Add(header); pos += header.BinSize; } } /// <summary> /// Gets the root key in the registry hive. /// </summary> public RegistryKey Root { get { return new RegistryKey(this, GetCell<KeyNodeCell>(_header.RootCell)); } } /// <summary> /// Disposes of this instance, freeing any underlying stream (if any). /// </summary> public void Dispose() { if (_fileStream != null && _ownsStream == Ownership.Dispose) { _fileStream.Dispose(); _fileStream = null; } } /// <summary> /// Creates a new (empty) registry hive. /// </summary> /// <param name="stream">The stream to contain the new hive.</param> /// <returns>The new hive.</returns> /// <remarks> /// The returned object does not assume ownership of the stream. /// </remarks> public static RegistryHive Create(Stream stream) { return Create(stream, Ownership.None); } /// <summary> /// Creates a new (empty) registry hive. /// </summary> /// <param name="stream">The stream to contain the new hive.</param> /// <param name="ownership">Whether the returned object owns the stream.</param> /// <returns>The new hive.</returns> public static RegistryHive Create(Stream stream, Ownership ownership) { if (stream == null) { throw new ArgumentNullException(nameof(stream), "Attempt to create registry hive in null stream"); } // Construct a file with minimal structure - hive header, plus one (empty) bin BinHeader binHeader = new BinHeader(); binHeader.FileOffset = 0; binHeader.BinSize = (int)(4 * Sizes.OneKiB); HiveHeader hiveHeader = new HiveHeader(); hiveHeader.Length = binHeader.BinSize; stream.Position = 0; byte[] buffer = new byte[hiveHeader.Size]; hiveHeader.WriteTo(buffer, 0); stream.Write(buffer, 0, buffer.Length); buffer = new byte[binHeader.Size]; binHeader.WriteTo(buffer, 0); stream.Position = BinStart; stream.Write(buffer, 0, buffer.Length); buffer = new byte[4]; EndianUtilities.WriteBytesLittleEndian(binHeader.BinSize - binHeader.Size, buffer, 0); stream.Write(buffer, 0, buffer.Length); // Make sure the file is initialized out to the end of the firs bin stream.Position = BinStart + binHeader.BinSize - 1; stream.WriteByte(0); // Temporary hive to perform construction of higher-level structures RegistryHive newHive = new RegistryHive(stream); KeyNodeCell rootCell = new KeyNodeCell("root", -1); rootCell.Flags = RegistryKeyFlags.Normal | RegistryKeyFlags.Root; newHive.UpdateCell(rootCell, true); RegistrySecurity sd = new RegistrySecurity(); sd.SetSecurityDescriptorSddlForm("O:BAG:BAD:PAI(A;;KA;;;SY)(A;CI;KA;;;BA)", AccessControlSections.All); SecurityCell secCell = new SecurityCell(sd); newHive.UpdateCell(secCell, true); secCell.NextIndex = secCell.Index; secCell.PreviousIndex = secCell.Index; newHive.UpdateCell(secCell, false); rootCell.SecurityIndex = secCell.Index; newHive.UpdateCell(rootCell, false); // Ref the root cell from the hive header hiveHeader.RootCell = rootCell.Index; buffer = new byte[hiveHeader.Size]; hiveHeader.WriteTo(buffer, 0); stream.Position = 0; stream.Write(buffer, 0, buffer.Length); // Finally, return the new hive return new RegistryHive(stream, ownership); } /// <summary> /// Creates a new (empty) registry hive. /// </summary> /// <param name="path">The file to create the new hive in.</param> /// <returns>The new hive.</returns> public static RegistryHive Create(string path) { var locator = new LocalFileLocator(string.Empty); return Create(locator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None), Ownership.Dispose); } internal K GetCell<K>(int index) where K : Cell { Bin bin = GetBin(index); if (bin != null) { return (K)bin.TryGetCell(index); } return null; } internal void FreeCell(int index) { Bin bin = GetBin(index); if (bin != null) { bin.FreeCell(index); } } internal int UpdateCell(Cell cell, bool canRelocate) { if (cell.Index == -1 && canRelocate) { cell.Index = AllocateRawCell(cell.Size); } Bin bin = GetBin(cell.Index); if (bin != null) { if (bin.UpdateCell(cell)) { return cell.Index; } if (canRelocate) { int oldCell = cell.Index; cell.Index = AllocateRawCell(cell.Size); bin = GetBin(cell.Index); if (!bin.UpdateCell(cell)) { cell.Index = oldCell; throw new RegistryCorruptException("Failed to migrate cell to new location"); } FreeCell(oldCell); return cell.Index; } throw new ArgumentException("Can't update cell, needs relocation but relocation disabled", nameof(canRelocate)); } throw new RegistryCorruptException("No bin found containing index: " + cell.Index); } internal byte[] RawCellData(int index, int maxBytes) { Bin bin = GetBin(index); if (bin != null) { return bin.ReadRawCellData(index, maxBytes); } return null; } internal bool WriteRawCellData(int index, byte[] data, int offset, int count) { Bin bin = GetBin(index); if (bin != null) { return bin.WriteRawCellData(index, data, offset, count); } throw new RegistryCorruptException("No bin found containing index: " + index); } internal int AllocateRawCell(int capacity) { int minSize = MathUtilities.RoundUp(capacity + 4, 8); // Allow for size header and ensure multiple of 8 // Incredibly inefficient algorithm... foreach (BinHeader binHeader in _bins) { Bin bin = LoadBin(binHeader); int cellIndex = bin.AllocateCell(minSize); if (cellIndex >= 0) { return cellIndex; } } BinHeader newBinHeader = AllocateBin(minSize); Bin newBin = LoadBin(newBinHeader); return newBin.AllocateCell(minSize); } private BinHeader FindBin(int index) { int binsIdx = _bins.BinarySearch(null, new BinFinder(index)); if (binsIdx >= 0) { return _bins[binsIdx]; } return null; } private Bin GetBin(int cellIndex) { BinHeader binHeader = FindBin(cellIndex); if (binHeader != null) { return LoadBin(binHeader); } return null; } private Bin LoadBin(BinHeader binHeader) { _fileStream.Position = BinStart + binHeader.FileOffset; return new Bin(this, _fileStream); } private BinHeader AllocateBin(int minSize) { BinHeader lastBin = _bins[_bins.Count - 1]; BinHeader newBinHeader = new BinHeader(); newBinHeader.FileOffset = lastBin.FileOffset + lastBin.BinSize; newBinHeader.BinSize = MathUtilities.RoundUp(minSize + newBinHeader.Size, 4 * (int)Sizes.OneKiB); byte[] buffer = new byte[newBinHeader.Size]; newBinHeader.WriteTo(buffer, 0); _fileStream.Position = BinStart + newBinHeader.FileOffset; _fileStream.Write(buffer, 0, buffer.Length); byte[] cellHeader = new byte[4]; EndianUtilities.WriteBytesLittleEndian(newBinHeader.BinSize - newBinHeader.Size, cellHeader, 0); _fileStream.Write(cellHeader, 0, 4); // Update hive with new length _header.Length = newBinHeader.FileOffset + newBinHeader.BinSize; _header.Timestamp = DateTime.UtcNow; _header.Sequence1++; _header.Sequence2++; _fileStream.Position = 0; byte[] hiveHeader = StreamUtilities.ReadExact(_fileStream, _header.Size); _header.WriteTo(hiveHeader, 0); _fileStream.Position = 0; _fileStream.Write(hiveHeader, 0, hiveHeader.Length); // Make sure the file is initialized to desired position _fileStream.Position = BinStart + _header.Length - 1; _fileStream.WriteByte(0); _bins.Add(newBinHeader); return newBinHeader; } private class BinFinder : IComparer<BinHeader> { private readonly int _index; public BinFinder(int index) { _index = index; } #region IComparer<BinHeader> Members public int Compare(BinHeader x, BinHeader y) { if (x.FileOffset + x.BinSize < _index) { return -1; } if (x.FileOffset > _index) { return 1; } return 0; } #endregion } } }
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ 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 names of Bas Geertsema or Xih Solutions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; namespace MSNPSharp { using MSNPSharp.Apps; using MSNPSharp.Core; using MSNPSharp.P2P; using MSNPSharp.LiveConnectAPI.Atom; using MSNPSharp.MSNWS.MSNABSharingService; /// <summary> /// Used for the relationship with your friend on your social network. /// </summary> [Serializable] public class FriendshipStatusChangedEventArgs : EventArgs { private readonly RoleId oldStatus; private readonly RoleId newStatus; private readonly Contact contact; public RoleId OldStatus { get { return oldStatus; } } public RoleId NewStatus { get { return newStatus; } } public Contact Contact { get { return contact; } } public FriendshipStatusChangedEventArgs(Contact contact, RoleId oldStatus, RoleId newStatus) { this.contact = contact; this.oldStatus = oldStatus; this.newStatus = newStatus; } } /// <summary> /// Used when a contact changed its status. /// </summary> [Serializable] public class StatusChangedEventArgs : EventArgs { private PresenceStatus oldStatus; private PresenceStatus newStatus; public PresenceStatus OldStatus { get { return oldStatus; } } public PresenceStatus NewStatus { get { return newStatus; } } public StatusChangedEventArgs(PresenceStatus oldStatus, PresenceStatus newStatus) { this.oldStatus = oldStatus; this.newStatus = newStatus; } } /// <summary> /// Used when contact changed its status. /// </summary> [Serializable] public class ContactStatusChangedEventArgs : StatusChangedEventArgs { private Contact contact; private Contact via; /// <summary> /// The contact who changed its status. /// </summary> public Contact Contact { get { return contact; } } /// <summary> /// Circle, temporary group or external network if it isn't null. /// </summary> public Contact Via { get { return via; } } public ContactStatusChangedEventArgs(Contact contact, Contact via, PresenceStatus oldStatus, PresenceStatus newStatus) : base(oldStatus, newStatus) { this.contact = contact; this.via = via; if (via == null && contact != null) via = contact.Via; } public ContactStatusChangedEventArgs(Contact contact, PresenceStatus oldStatus, PresenceStatus newStatus) : base(oldStatus, newStatus) { this.contact = contact; this.via = contact.Via; } } /// <summary> /// Used when any contect event occured. /// </summary> [Serializable] public class BaseContactEventArgs : EventArgs { protected Contact contact = null; public BaseContactEventArgs(Contact contact) { this.contact = contact; } } [Serializable()] public class ContactEventArgs : BaseContactEventArgs { /// <summary> /// The contact raise the event. /// </summary> public Contact Contact { get { return contact; } set { contact = value; } } public ContactEventArgs(Contact contact) : base(contact) { } } [Serializable] public class GroupChatParticipationEventArgs : EventArgs { private Contact contact; private Contact via; /// <summary> /// The contact joined/left. Use this contact to chat 1 on 1. /// </summary> public Contact Contact { get { return contact; } } /// <summary> /// Circle or temporary group. Use this contact for multiparty chat. /// </summary> public Contact Via { get { return via; } } public GroupChatParticipationEventArgs(Contact contact, Contact via) { this.contact = contact; this.via = via; } } /// <summary> /// Use when user's sign in places changed. /// </summary> public class PlaceChangedEventArgs : EventArgs { private PlaceChangedReason reason = PlaceChangedReason.None; private EndPointData epData; public PlaceChangedReason Reason { get { return reason; } } public EndPointData EndPointData { get { return epData; } } public string PlaceName { get { PrivateEndPointData pep = epData as PrivateEndPointData; if (pep != null) { return pep.Name; } return String.Empty; } } private PlaceChangedEventArgs() : base() { } public PlaceChangedEventArgs(EndPointData ep, PlaceChangedReason action) : base() { this.epData = ep; this.reason = action; } } /// <summary> /// Used in events where a exception is raised. Via these events the client programmer /// can react on these exceptions. /// </summary> [Serializable()] public class ExceptionEventArgs : EventArgs { /// <summary> /// </summary> private Exception _exception; /// <summary> /// The exception that was raised /// </summary> public Exception Exception { get { return _exception; } set { _exception = value; } } /// <summary> /// Constructor. /// </summary> /// <param name="e"></param> public ExceptionEventArgs(Exception e) { _exception = e; } } /// <summary> /// Used as event argument when a emoticon definition is send. /// </summary> [Serializable()] public class EmoticonDefinitionEventArgs : MessageArrivedEventArgs { /// <summary> /// </summary> private Emoticon emoticon; /// <summary> /// The emoticon which is defined /// </summary> public Emoticon Emoticon { get { return emoticon; } set { emoticon = value; } } public EmoticonDefinitionEventArgs(Contact contact, Contact originalSender, RoutingInfo routingInfo, Emoticon emoticon) : base(contact, originalSender, routingInfo) { this.emoticon = emoticon; } } /// <summary> /// Used when a list (FL, Al, BL, RE) is received via synchronize or on request. /// </summary> [Serializable()] public class ListReceivedEventArgs : EventArgs { /// <summary> /// </summary> private RoleLists affectedList = RoleLists.None; /// <summary> /// The list which was send by the server /// </summary> public RoleLists AffectedList { get { return affectedList; } set { affectedList = value; } } /// <summary> /// Constructory. /// </summary> /// <param name="affectedList"></param> public ListReceivedEventArgs(RoleLists affectedList) { AffectedList = affectedList; } } /// <summary> /// Used when the local user is signed off. /// </summary> [Serializable()] public class SignedOffEventArgs : EventArgs { /// <summary> /// </summary> private SignedOffReason signedOffReason; /// <summary> /// The list which was send by the server /// </summary> public SignedOffReason SignedOffReason { get { return signedOffReason; } set { signedOffReason = value; } } /// <summary> /// Constructor. /// </summary> /// <param name="signedOffReason"></param> public SignedOffEventArgs(SignedOffReason signedOffReason) { this.signedOffReason = signedOffReason; } } /// <summary> /// Used as event argument when any contact list mutates. /// </summary> [Serializable()] public class ListMutateEventArgs : ContactEventArgs { /// <summary> /// </summary> private RoleLists affectedList = RoleLists.None; /// <summary> /// The list which mutated. /// </summary> public RoleLists AffectedList { get { return affectedList; } set { affectedList = value; } } /// <summary> /// Constructor /// </summary> /// <param name="contact"></param> /// <param name="affectedList"></param> public ListMutateEventArgs(Contact contact, RoleLists affectedList) : base(contact) { AffectedList = affectedList; } } /// <summary> /// Used as event argument when msn sends us an error. /// </summary> [Serializable()] public class MSNErrorEventArgs : EventArgs { private MSNError msnError; private string description = string.Empty; /// <summary> /// The error description /// </summary> public string Description { get { return description; } } /// <summary> /// The error that occurred /// </summary> public MSNError MSNError { get { return msnError; } } /// <summary> /// Constructor. /// </summary> public MSNErrorEventArgs(MSNError msnError, string description) { this.msnError = msnError; this.description = description; } } [Serializable] public class MultipartyCreatedEventArgs : EventArgs { private Contact group; public Contact Group { get { return group; } } public MultipartyCreatedEventArgs(Contact group) { this.group = group; } } [Serializable] public abstract class MessageArrivedEventArgs : EventArgs { private Contact sender; private Contact originalSender; private RoutingInfo routingInfo; /// <summary> /// The sender of message (type can be contact, circle or temporary group) /// </summary> public Contact Sender { get { return sender; } } /// <summary> /// The original sender of message (client type is contact and can chat invidually) /// </summary> public Contact OriginalSender { get { return originalSender; } } public RoutingInfo RoutingInfo { get { return routingInfo; } } protected MessageArrivedEventArgs(Contact contact, Contact originalSender, RoutingInfo routingInfo) { this.sender = contact; this.originalSender = originalSender; this.routingInfo = routingInfo; } } [Serializable] public class NudgeArrivedEventArgs : MessageArrivedEventArgs { public NudgeArrivedEventArgs(Contact contact, Contact originalSender, RoutingInfo routingInfo) : base(contact, originalSender, routingInfo) { } } [Serializable] public class TypingArrivedEventArgs : MessageArrivedEventArgs { public TypingArrivedEventArgs(Contact contact, Contact originalSender, RoutingInfo routingInfo) : base(contact, originalSender, routingInfo) { } } [Serializable] public class TextMessageArrivedEventArgs : MessageArrivedEventArgs { private TextMessage textMessage = null; /// <summary> /// The text message received. /// </summary> public TextMessage TextMessage { get { return textMessage; } } public TextMessageArrivedEventArgs(Contact sender, TextMessage textMessage, Contact originalSender, RoutingInfo routingInfo) : base(sender, originalSender, routingInfo) { this.textMessage = textMessage; } } [Serializable] public class EmoticonArrivedEventArgs : MessageArrivedEventArgs { private Emoticon emoticon; /// <summary> /// The emoticon data received. /// </summary> public Emoticon Emoticon { get { return emoticon; } } public EmoticonArrivedEventArgs(Contact sender, Emoticon emoticon, Contact circle, RoutingInfo routingInfo) : base(sender, circle, routingInfo) { this.emoticon = emoticon; } } public class WinkEventArgs : MessageArrivedEventArgs { private Wink wink; public Wink Wink { get { return wink; } } public WinkEventArgs(Contact contact, Wink wink, RoutingInfo routingInfo) : base(contact, null, routingInfo) { this.wink = wink; } } /// <summary> /// Base class for circle event arg. /// </summary> public class BaseCircleEventArgs : EventArgs { protected Contact circle = null; internal BaseCircleEventArgs(Contact circle) { this.circle = circle; } } /// <summary> /// Used as event argument when a <see cref="Circle"/> is affected. /// </summary> [Serializable()] public class CircleEventArgs : BaseCircleEventArgs { protected Contact remoteMember = null; /// <summary> /// The affected contact group /// </summary> public Contact Circle { get { return circle; } } /// <summary> /// Constructor, mostly used internal by the library. /// </summary> /// <param name="circle"></param> internal CircleEventArgs(Contact circle) : base(circle) { } /// <summary> /// Constructor, mostly used internal by the library. /// </summary> /// <param name="circle"></param> /// <param name="remote">The affected Contact.</param> internal CircleEventArgs(Contact circle, Contact remote) : base(circle) { remoteMember = remote; } } /// <summary> /// Used when a event related to circle member operaion fired. /// </summary> [Serializable()] public class CircleMemberEventArgs : CircleEventArgs { /// <summary> /// The contact member raise the event. /// </summary> public Contact Member { get { return remoteMember; } } internal CircleMemberEventArgs(Contact circle, Contact member) : base(circle, member) { } } /// <summary> /// Event argument used when a user's <see cref="DisplayImage"/> property has been changed. /// </summary> public class DisplayImageChangedEventArgs : EventArgs { private bool callFromContactManager = false; private DisplayImageChangedType status = DisplayImageChangedType.None; private DisplayImage newDisplayImage = null; public DisplayImage NewDisplayImage { get { return newDisplayImage; } } /// <summary> /// The reason that fires <see cref="Contact.DisplayImageChanged"/> event. /// </summary> public DisplayImageChangedType Status { get { return status; } } /// <summary> /// Whether we need to do display image synchronize. /// </summary> internal bool CallFromContactManager { get { return callFromContactManager; } } private DisplayImageChangedEventArgs() { } internal DisplayImageChangedEventArgs(DisplayImage dispImage, DisplayImageChangedType type, bool needSync) { status = type; callFromContactManager = needSync; newDisplayImage = dispImage; } internal DisplayImageChangedEventArgs(DisplayImageChangedEventArgs arg, bool needSync) { status = arg.Status; callFromContactManager = needSync; newDisplayImage = arg.NewDisplayImage; } public DisplayImageChangedEventArgs(DisplayImage dispImage, DisplayImageChangedType type) { status = type; callFromContactManager = false; newDisplayImage = dispImage; } } /// <summary> /// Event argument used when a user's <see cref="SceneImage"/> property has been changed. /// </summary> public class SceneImageChangedEventArgs : EventArgs { private bool callFromContactManager = false; private bool isDefault = false; private DisplayImageChangedType status = DisplayImageChangedType.None; private SceneImage newSceneImage = null; public SceneImage NewSceneImage { get { return newSceneImage; } } /// <summary> /// The reason that fires <see cref="Contact.SceneImageChanged"/> event. /// </summary> public DisplayImageChangedType Status { get { return status; } } /// <summary> /// If the user has chosen to set his scene image to default. /// </summary> public bool IsDefault { get { return isDefault; } } /// <summary> /// Whether we need to synchronize the scene image. /// </summary> internal bool CallFromContactManager { get { return callFromContactManager; } } private SceneImageChangedEventArgs() { } internal SceneImageChangedEventArgs(SceneImage sceneImage, DisplayImageChangedType type, bool needSync) { status = type; callFromContactManager = needSync; newSceneImage = sceneImage; } public SceneImageChangedEventArgs(DisplayImageChangedType type, bool isDefault) { status = type; callFromContactManager = false; newSceneImage = null; this.isDefault = isDefault; } } public class CloseIMWindowEventArgs : EventArgs { private Contact sender = null; private EndPointData senderEndPoint = null; private Contact receiver = null; private EndPointData receiverEndPoint = null; private Contact[] parties = null; public Contact[] Parties { get { return this.parties; } private set { parties = value; } } public Contact Receiver { get { return this.receiver; } private set { receiver = value; } } public EndPointData ReceiverEndPoint { get { return this.receiverEndPoint; } private set { receiverEndPoint = value; } } public Contact Sender { get { return this.sender; } private set { sender = value; } } public EndPointData SenderEndPoint { get { return this.senderEndPoint; } private set { senderEndPoint = value; } } public CloseIMWindowEventArgs(Contact sender, EndPointData senderEndPoint, Contact receiver, EndPointData receiverEndPoint, Contact[] parties) : base() { Sender = sender; SenderEndPoint = senderEndPoint; Receiver = receiver; ReceiverEndPoint = receiverEndPoint; Parties = parties; } } internal class AtomRequestSucceedEventArgs : EventArgs { private entryType entry = null; /// <summary> /// The return entry of atom request. /// </summary> public entryType Entry { get { return entry; } private set { entry = value; } } public AtomRequestSucceedEventArgs(entryType entry) { Entry = entry; } } public class PersonalStatusChangedEventArgs : EventArgs { private string oldStatusText = string.Empty; /// <summary> /// The previous personal status. /// </summary> public string OldStatusText { get { return oldStatusText; } private set { oldStatusText = value; } } private string newStatusText = string.Empty; /// <summary> /// Current sttaus text after changed. /// </summary> public string NewStatusText { get { return newStatusText; } private set { newStatusText = value; } } public PersonalStatusChangedEventArgs(string oldText, string newText) { OldStatusText = oldText; NewStatusText = newText; } } };
/* * Copyright 2002-2015 Drew Noakes * * Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#) * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ using System.Linq; using Com.Drew.Lang; using Com.Drew.Metadata; using JetBrains.Annotations; using Sharpen; namespace Com.Drew.Metadata.Iptc { /// <summary> /// Provides human-readable string representations of tag values stored in a /// <see cref="IptcDirectory"/> /// . /// <p> /// As the IPTC directory already stores values as strings, this class simply returns the tag's value. /// </summary> /// <author>Drew Noakes https://drewnoakes.com</author> public class IptcDescriptor : TagDescriptor<IptcDirectory> { public IptcDescriptor([NotNull] IptcDirectory directory) : base(directory) { } [CanBeNull] public override string GetDescription(int tagType) { switch (tagType) { case IptcDirectory.TagFileFormat: { return GetFileFormatDescription(); } case IptcDirectory.TagKeywords: { return GetKeywordsDescription(); } case IptcDirectory.TagTimeCreated: { return GetTimeCreatedDescription(); } case IptcDirectory.TagDigitalTimeCreated: { return GetDigitalTimeCreatedDescription(); } default: { return base.GetDescription(tagType); } } } [CanBeNull] public virtual string GetFileFormatDescription() { int? value = _directory.GetInteger(IptcDirectory.TagFileFormat); if (value == null) { return null; } switch (value) { case 0: { return "No ObjectData"; } case 1: { return "IPTC-NAA Digital Newsphoto Parameter Record"; } case 2: { return "IPTC7901 Recommended Message Format"; } case 3: { return "Tagged Image File Format (Adobe/Aldus Image data)"; } case 4: { return "Illustrator (Adobe Graphics data)"; } case 5: { return "AppleSingle (Apple Computer Inc)"; } case 6: { return "NAA 89-3 (ANPA 1312)"; } case 7: { return "MacBinary II"; } case 8: { return "IPTC Unstructured Character Oriented File Format (UCOFF)"; } case 9: { return "United Press International ANPA 1312 variant"; } case 10: { return "United Press International Down-Load Message"; } case 11: { return "JPEG File Interchange (JFIF)"; } case 12: { return "Photo-CD Image-Pac (Eastman Kodak)"; } case 13: { return "Bit Mapped Graphics File [.BMP] (Microsoft)"; } case 14: { return "Digital Audio File [.WAV] (Microsoft & Creative Labs)"; } case 15: { return "Audio plus Moving Video [.AVI] (Microsoft)"; } case 16: { return "PC DOS/Windows Executable Files [.COM][.EXE]"; } case 17: { return "Compressed Binary File [.ZIP] (PKWare Inc)"; } case 18: { return "Audio Interchange File Format AIFF (Apple Computer Inc)"; } case 19: { return "RIFF Wave (Microsoft Corporation)"; } case 20: { return "Freehand (Macromedia/Aldus)"; } case 21: { return "Hypertext Markup Language [.HTML] (The Internet Society)"; } case 22: { return "MPEG 2 Audio Layer 2 (Musicom), ISO/IEC"; } case 23: { return "MPEG 2 Audio Layer 3, ISO/IEC"; } case 24: { return "Portable Document File [.PDF] Adobe"; } case 25: { return "News Industry Text Format (NITF)"; } case 26: { return "Tape Archive [.TAR]"; } case 27: { return "Tidningarnas Telegrambyra NITF version (TTNITF DTD)"; } case 28: { return "Ritzaus Bureau NITF version (RBNITF DTD)"; } case 29: { return "Corel Draw [.CDR]"; } } return Sharpen.Extensions.StringFormat("Unknown (%d)", value); } [CanBeNull] public virtual string GetByLineDescription() { return _directory.GetString(IptcDirectory.TagByLine); } [CanBeNull] public virtual string GetByLineTitleDescription() { return _directory.GetString(IptcDirectory.TagByLineTitle); } [CanBeNull] public virtual string GetCaptionDescription() { return _directory.GetString(IptcDirectory.TagCaption); } [CanBeNull] public virtual string GetCategoryDescription() { return _directory.GetString(IptcDirectory.TagCategory); } [CanBeNull] public virtual string GetCityDescription() { return _directory.GetString(IptcDirectory.TagCity); } [CanBeNull] public virtual string GetCopyrightNoticeDescription() { return _directory.GetString(IptcDirectory.TagCopyrightNotice); } [CanBeNull] public virtual string GetCountryOrPrimaryLocationDescription() { return _directory.GetString(IptcDirectory.TagCountryOrPrimaryLocationName); } [CanBeNull] public virtual string GetCreditDescription() { return _directory.GetString(IptcDirectory.TagCredit); } [CanBeNull] public virtual string GetDateCreatedDescription() { return _directory.GetString(IptcDirectory.TagDateCreated); } [CanBeNull] public virtual string GetHeadlineDescription() { return _directory.GetString(IptcDirectory.TagHeadline); } [CanBeNull] public virtual string GetKeywordsDescription() { string[] keywords = _directory.GetStringArray(IptcDirectory.TagKeywords); if (keywords == null) { return null; } return StringUtil.Join(keywords.ToCharSequence(), ";"); } [CanBeNull] public virtual string GetObjectNameDescription() { return _directory.GetString(IptcDirectory.TagObjectName); } [CanBeNull] public virtual string GetOriginalTransmissionReferenceDescription() { return _directory.GetString(IptcDirectory.TagOriginalTransmissionReference); } [CanBeNull] public virtual string GetOriginatingProgramDescription() { return _directory.GetString(IptcDirectory.TagOriginatingProgram); } [CanBeNull] public virtual string GetProvinceOrStateDescription() { return _directory.GetString(IptcDirectory.TagProvinceOrState); } [CanBeNull] public virtual string GetRecordVersionDescription() { return _directory.GetString(IptcDirectory.TagApplicationRecordVersion); } [CanBeNull] public virtual string GetReleaseDateDescription() { return _directory.GetString(IptcDirectory.TagReleaseDate); } [CanBeNull] public virtual string GetReleaseTimeDescription() { return _directory.GetString(IptcDirectory.TagReleaseTime); } [CanBeNull] public virtual string GetSourceDescription() { return _directory.GetString(IptcDirectory.TagSource); } [CanBeNull] public virtual string GetSpecialInstructionsDescription() { return _directory.GetString(IptcDirectory.TagSpecialInstructions); } [CanBeNull] public virtual string GetSupplementalCategoriesDescription() { return _directory.GetString(IptcDirectory.TagSupplementalCategories); } [CanBeNull] public virtual string GetTimeCreatedDescription() { string s = _directory.GetString(IptcDirectory.TagTimeCreated); if (s == null) { return null; } if (s.Length == 6 || s.Length == 11) { return Sharpen.Runtime.Substring(s, 0, 2) + ':' + Sharpen.Runtime.Substring(s, 2, 4) + ':' + Sharpen.Runtime.Substring(s, 4); } return s; } [CanBeNull] public virtual string GetDigitalTimeCreatedDescription() { string s = _directory.GetString(IptcDirectory.TagDigitalTimeCreated); if (s == null) { return null; } if (s.Length == 6 || s.Length == 11) { return Sharpen.Runtime.Substring(s, 0, 2) + ':' + Sharpen.Runtime.Substring(s, 2, 4) + ':' + Sharpen.Runtime.Substring(s, 4); } return s; } [CanBeNull] public virtual string GetUrgencyDescription() { return _directory.GetString(IptcDirectory.TagUrgency); } [CanBeNull] public virtual string GetWriterDescription() { return _directory.GetString(IptcDirectory.TagCaptionWriter); } } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface IPhoneNumberTypeOriginalData : INeo4jBaseOriginalData { string Name { get; } } public partial class PhoneNumberType : OGM<PhoneNumberType, PhoneNumberType.PhoneNumberTypeData, System.String>, INeo4jBase, IPhoneNumberTypeOriginalData { #region Initialize static PhoneNumberType() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion AdditionalGeneratedStoredQueries(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, PhoneNumberType> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.PhoneNumberTypeAlias, IWhereQuery> query) { q.PhoneNumberTypeAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.PhoneNumberType.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"PhoneNumberType => Name : {this.Name?.ToString() ?? "null"}, Uid : {this.Uid}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new PhoneNumberTypeData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class PhoneNumberTypeData : Data<System.String> { public PhoneNumberTypeData() { } public PhoneNumberTypeData(PhoneNumberTypeData data) { Name = data.Name; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "PhoneNumberType"; } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("Name", Name); dictionary.Add("Uid", Uid); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("Name", out value)) Name = (string)value; if (properties.TryGetValue("Uid", out value)) Uid = (string)value; } #endregion #region Members for interface IPhoneNumberType public string Name { get; set; } #endregion #region Members for interface INeo4jBase public string Uid { get; set; } #endregion } #endregion #region Outer Data #region Members for interface IPhoneNumberType public string Name { get { LazyGet(); return InnerData.Name; } set { if (LazySet(Members.Name, InnerData.Name, value)) InnerData.Name = value; } } #endregion #region Members for interface INeo4jBase public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static PhoneNumberTypeMembers members = null; public static PhoneNumberTypeMembers Members { get { if (members == null) { lock (typeof(PhoneNumberType)) { if (members == null) members = new PhoneNumberTypeMembers(); } } return members; } } public class PhoneNumberTypeMembers { internal PhoneNumberTypeMembers() { } #region Members for interface IPhoneNumberType public Property Name { get; } = Datastore.AdventureWorks.Model.Entities["PhoneNumberType"].Properties["Name"]; #endregion #region Members for interface INeo4jBase public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]; #endregion } private static PhoneNumberTypeFullTextMembers fullTextMembers = null; public static PhoneNumberTypeFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(PhoneNumberType)) { if (fullTextMembers == null) fullTextMembers = new PhoneNumberTypeFullTextMembers(); } } return fullTextMembers; } } public class PhoneNumberTypeFullTextMembers { internal PhoneNumberTypeFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(PhoneNumberType)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["PhoneNumberType"]; } } return entity; } private static PhoneNumberTypeEvents events = null; public static PhoneNumberTypeEvents Events { get { if (events == null) { lock (typeof(PhoneNumberType)) { if (events == null) events = new PhoneNumberTypeEvents(); } } return events; } } public class PhoneNumberTypeEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<PhoneNumberType, EntityEventArgs> onNew; public event EventHandler<PhoneNumberType, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<PhoneNumberType, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((PhoneNumberType)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<PhoneNumberType, EntityEventArgs> onDelete; public event EventHandler<PhoneNumberType, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<PhoneNumberType, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((PhoneNumberType)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<PhoneNumberType, EntityEventArgs> onSave; public event EventHandler<PhoneNumberType, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<PhoneNumberType, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((PhoneNumberType)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnName private static bool onNameIsRegistered = false; private static EventHandler<PhoneNumberType, PropertyEventArgs> onName; public static event EventHandler<PhoneNumberType, PropertyEventArgs> OnName { add { lock (typeof(OnPropertyChange)) { if (!onNameIsRegistered) { Members.Name.Events.OnChange -= onNameProxy; Members.Name.Events.OnChange += onNameProxy; onNameIsRegistered = true; } onName += value; } } remove { lock (typeof(OnPropertyChange)) { onName -= value; if (onName == null && onNameIsRegistered) { Members.Name.Events.OnChange -= onNameProxy; onNameIsRegistered = false; } } } } private static void onNameProxy(object sender, PropertyEventArgs args) { EventHandler<PhoneNumberType, PropertyEventArgs> handler = onName; if ((object)handler != null) handler.Invoke((PhoneNumberType)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<PhoneNumberType, PropertyEventArgs> onUid; public static event EventHandler<PhoneNumberType, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<PhoneNumberType, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((PhoneNumberType)sender, args); } #endregion } #endregion } #endregion #region IPhoneNumberTypeOriginalData public IPhoneNumberTypeOriginalData OriginalVersion { get { return this; } } #region Members for interface IPhoneNumberType string IPhoneNumberTypeOriginalData.Name { get { return OriginalData.Name; } } #endregion #region Members for interface INeo4jBase INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } } string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } } #endregion #endregion } }
//----------------------------------------------------------------------------- // <copyright file="Application.cs" company="WheelMUD Development Team"> // Copyright (c) WheelMUD Development Team. See LICENSE.txt. This file is // subject to the Microsoft Public License. All other rights reserved. // </copyright> // <summary> // The core application, which can be housed in a console, service, etc. // </summary> //----------------------------------------------------------------------------- namespace WheelMUD.Main { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Data; using System.IO; using System.Linq; using System.Reflection; using WheelMUD.Core; using WheelMUD.Data; using WheelMUD.Interfaces; using WheelMUD.Utilities; /// <summary>The core application, which can be housed in a console, service, etc.</summary> public class Application : ISuperSystem, ISuperSystemSubscriber { /// <summary>The singleton instance of this class.</summary> private static Application instance = new Application(); /// <summary>A list of subscribers of this super system.</summary> private readonly List<ISuperSystemSubscriber> subscribers = new List<ISuperSystemSubscriber>(); /// <summary>The view engine.</summary> private ViewEngine viewEngine; /// <summary>Prevents a default instance of the <see cref="Application"/> class from being created.</summary> private Application() { UnhandledExceptionHandler.Register(this.Notify); } /// <summary>Gets the singleton instance of this <see cref="Application"/>.</summary> public static Application Instance { get { return instance; } } /// <summary>Gets or sets the available systems.</summary> /// <value>The available systems.</value> [ImportMany] private List<SystemExporter> AvailableSystems { get; set; } /// <summary>Dispose of any resources consumed by Application.</summary> public void Dispose() { } /// <summary>Subscribe to the specified super system subscriber.</summary> /// <param name="sender">The subscribing system; generally use 'this'.</param> public void SubscribeToSystem(ISuperSystemSubscriber sender) { if (this.subscribers.Contains(sender)) { throw new DuplicateNameException("The subscriber is already subscribed to Super System events."); } this.subscribers.Add(sender); } /// <summary>Unsubscribe from the specified super system subscriber.</summary> /// <param name="sender">The unsubscribing system; generally use 'this'.</param> public void UnSubscribeFromSystem(ISuperSystemSubscriber sender) { this.subscribers.Remove(sender); } /// <summary>Start the application.</summary> public void Start() { #if DEBUG EnsureFilesArePresent(); EnsureDataIsPresent(); #endif this.InitializeSystems(); } private void EnsureFilesArePresent() { string appPath = Assembly.GetExecutingAssembly().Location; var appFile = new FileInfo(appPath); if (appFile.Directory == null || string.IsNullOrEmpty(appFile.Directory.FullName)) { throw new DirectoryNotFoundException("Could not find the application directory."); } string appDir = appFile.Directory.FullName; string destDir = Configuration.GetDataStoragePath(); if (!Directory.Exists(destDir)) { // If the database file doesn't exist, try to copy the original source. string sourcePath = null; int i = appDir.IndexOf("\\systemdata\\", System.StringComparison.Ordinal); if (i > 0) { sourcePath = appDir.Substring(0, i) + "\\systemdata\\Files\\"; } else { sourcePath = Path.GetDirectoryName(appDir); sourcePath = Path.Combine(sourcePath + "\\systemdata\\Files\\"); } DirectoryCopy(sourcePath, destDir, true); } } private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { DirectoryInfo dir = new DirectoryInfo(sourceDirName); DirectoryInfo[] dirs = dir.GetDirectories(); // If the source directory does not exist, throw an exception. if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } // If the destination directory does not exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the file contents of the directory to copy. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { // Create the path to the new copy of the file. string temppath = Path.Combine(destDirName, file.Name); // Copy the file. file.CopyTo(temppath, false); } // If copySubDirs is true, copy the subdirectories. if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { // Create the subdirectory. string temppath = Path.Combine(destDirName, subdir.Name); // Copy the subdirectories. DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } } /// <summary>Stop the application.</summary> public void Stop() { this.Notify("Shutting Down..."); this.Notify("Stopping Services..."); CoreManager.Instance.Stop(); this.Notify("Server is now Stopped"); } /// <summary>Send an update to the system host.</summary> /// <param name="sender">The sending system.</param> /// <param name="msg">The message to be sent.</param> public void UpdateSystemHost(ISystem sender, string msg) { this.Notify(sender.GetType().Name + " - " + msg); } /// <summary>Temporary help system just so that we have something here if the person types help at the console.</summary> public void DisplayHelp() { var path = Path.Combine(Configuration.GetDataStoragePath(), "ConsoleHelp.txt"); var help = File.ReadAllText(path); this.Notify(this.viewEngine.RenderView(help)); } /// <summary>Notify subscribers of the specified message.</summary> /// <param name="message">The message to pass along.</param> public void Notify(string message) { foreach (ISuperSystemSubscriber subscriber in this.subscribers) { subscriber.Notify(message); } } /// <summary>Ensures that the database and such are present; copies the default if not.</summary> private static void EnsureDataIsPresent() { string currentProviderName = Helpers.GetCurrentProviderName(); if (currentProviderName.ToLowerInvariant() == "system.data.sqlite") { // Only for SQLite // Make sure that the database is in the right place. const string DatabaseName = "WheelMud.net.db"; string appPath = Assembly.GetExecutingAssembly().Location; var appFile = new FileInfo(appPath); if (appFile.Directory == null || string.IsNullOrEmpty(appFile.Directory.FullName)) { throw new DirectoryNotFoundException("Could not find the application directory."); } string appDir = appFile.Directory.FullName; string destDir = Configuration.GetDataStoragePath(); string destPath = Path.Combine(destDir, DatabaseName); if (!File.Exists(destPath)) { // If the database file doesn't exist, try to copy the original source. string sourcePath = null; int i = appDir.IndexOf("\\systemdata\\", System.StringComparison.Ordinal); if (i > 0) { sourcePath = appDir.Substring(0, i) + "\\systemdata\\SQL\\SQLite"; sourcePath = Path.Combine(sourcePath, DatabaseName); } else { sourcePath = Path.GetDirectoryName(appDir); sourcePath = Path.Combine(sourcePath + "\\systemdata\\SQL\\SQLite", DatabaseName); } if (File.Exists(sourcePath)) { File.Copy(sourcePath, destPath); } else { throw new FileNotFoundException("SQLite database was not present in application files directory nor at the expected src location."); } } } } /// <summary>Initializes the systems of this application.</summary> private void InitializeSystems() { this.viewEngine = new ViewEngine { ReplaceNewLine = false }; this.viewEngine.AddContext("MudAttributes", MudEngineAttributes.Instance); this.Notify(this.DisplayStartup()); this.Notify("Starting Application."); // Add environment variables needed by the program. VariableProcessor.Set("app.path", AppDomain.CurrentDomain.BaseDirectory); // Find and prepare all the application's most recent systems from those discovered by MEF. var systemExporters = this.GetLatestSystems(); CoreManager.Instance.SubSystems = new List<ISystem>(); foreach (var systemExporter in systemExporters) { CoreManager.Instance.SubSystems.Add(systemExporter.Instance); } CoreManager.Instance.SubscribeToSystem(this); CoreManager.Instance.Start(); this.Notify("All services are started. Server is fully operational."); } /// <summary>Gets the latest versions of each of our composed systems.</summary> /// <returns>A list of SystemExporters as used to instantiate our systems.</returns> private List<SystemExporter> GetLatestSystems() { DefaultComposer.Container.ComposeParts(this); // Find the Type of each distinct available system. ToList forces LINQ to process immediately. var systems = new List<SystemExporter>(); var systemTypes = from s in this.AvailableSystems select s.SystemType; var distinctTypeNames = (from t in systemTypes select t.FullName).Distinct().ToList(); foreach (string systemTypeName in distinctTypeNames) { // Add only the single most-recent version of this type (if there were more than one found). SystemExporter systemToAdd = (from s in this.AvailableSystems where s.SystemType.FullName == systemTypeName orderby s.SystemType.Assembly.GetName().Version.Major descending, s.SystemType.Assembly.GetName().Version.Minor descending, s.SystemType.Assembly.GetName().Version.Build descending, s.SystemType.Assembly.GetName().Version.Revision descending select s).FirstOrDefault(); systems.Add(systemToAdd); } return systems; } /// <summary>Display startup texts.</summary> /// <returns>The startup splash screen text.</returns> private string DisplayStartup() { var filePath = Path.Combine(Configuration.GetDataStoragePath(), "ConsoleOpen.txt"); var splash = File.ReadAllText(filePath); return this.viewEngine.RenderView(splash); } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; //m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; //PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddSubtractDouble() { var test = new SimpleBinaryOpTest__AddSubtractDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddSubtractDouble { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Double); private const int Op2ElementCount = VectorSize / sizeof(Double); private const int RetElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable; static SimpleBinaryOpTest__AddSubtractDouble() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__AddSubtractDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.AddSubtract( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.AddSubtract( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.AddSubtract( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.AddSubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.AddSubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.AddSubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.AddSubtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.AddSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.AddSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.AddSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AddSubtractDouble(); var result = Avx.AddSubtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.AddSubtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(left[0] - right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (((i % 2 != 0) && (BitConverter.DoubleToInt64Bits(left[i] + right[i]) != BitConverter.DoubleToInt64Bits(result[i]))) || ((i % 2 == 0) && (BitConverter.DoubleToInt64Bits(left[i] - right[i]) != BitConverter.DoubleToInt64Bits(result[i])))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.AddSubtract)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }