context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Digests { /// <remarks> /// <p>Implementation of RipeMD256.</p> /// <p><b>Note:</b> this algorithm offers the same level of security as RipeMD128.</p> /// </remarks> public class RipeMD256Digest : GeneralDigest { public override string AlgorithmName { get { return "RIPEMD256"; } } public override int GetDigestSize() { return DigestLength; } private const int DigestLength = 32; private int H0, H1, H2, H3, H4, H5, H6, H7; // IV's private int[] X = new int[16]; private int xOff; /// <summary> Standard constructor</summary> public RipeMD256Digest() { Reset(); } /// <summary> Copy constructor. This will copy the state of the provided /// message digest. /// </summary> public RipeMD256Digest(RipeMD256Digest t):base(t) { CopyIn(t); } private void CopyIn(RipeMD256Digest t) { base.CopyIn(t); H0 = t.H0; H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); if (xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (int)(bitLength & 0xffffffff); X[15] = (int)((ulong)bitLength >> 32); } private void UnpackWord( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)(uint)word; outBytes[outOff + 1] = (byte)((uint)word >> 8); outBytes[outOff + 2] = (byte)((uint)word >> 16); outBytes[outOff + 3] = (byte)((uint)word >> 24); } public override int DoFinal(byte[] output, int outOff) { Finish(); UnpackWord(H0, output, outOff); UnpackWord(H1, output, outOff + 4); UnpackWord(H2, output, outOff + 8); UnpackWord(H3, output, outOff + 12); UnpackWord(H4, output, outOff + 16); UnpackWord(H5, output, outOff + 20); UnpackWord(H6, output, outOff + 24); UnpackWord(H7, output, outOff + 28); Reset(); return DigestLength; } /// <summary> reset the chaining variables to the IV values.</summary> public override void Reset() { base.Reset(); H0 = unchecked((int)0x67452301); H1 = unchecked((int)0xefcdab89); H2 = unchecked((int)0x98badcfe); H3 = unchecked((int)0x10325476); H4 = unchecked((int)0x76543210); H5 = unchecked((int)0xFEDCBA98); H6 = unchecked((int)0x89ABCDEF); H7 = unchecked((int)0x01234567); xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } /* * rotate int x left n bits. */ private int RL( int x, int n) { return (x << n) | (int)((uint)x >> (32 - n)); } /* * f1,f2,f3,f4 are the basic RipeMD128 functions. */ /* * F */ private int F1(int x, int y, int z) { return x ^ y ^ z; } /* * G */ private int F2(int x, int y, int z) { return (x & y) | (~ x & z); } /* * H */ private int F3(int x, int y, int z) { return (x | ~ y) ^ z; } /* * I */ private int F4(int x, int y, int z) { return (x & z) | (y & ~ z); } private int F1(int a, int b, int c, int d, int x, int s) { return RL(a + F1(b, c, d) + x, s); } private int F2(int a, int b, int c, int d, int x, int s) { return RL(a + F2(b, c, d) + x + unchecked((int)0x5a827999), s); } private int F3(int a, int b, int c, int d, int x, int s) { return RL(a + F3(b, c, d) + x + unchecked((int)0x6ed9eba1), s); } private int F4(int a, int b, int c, int d, int x, int s) { return RL(a + F4(b, c, d) + x + unchecked((int)0x8f1bbcdc), s); } private int FF1(int a, int b, int c, int d, int x, int s) { return RL(a + F1(b, c, d) + x, s); } private int FF2(int a, int b, int c, int d, int x, int s) { return RL(a + F2(b, c, d) + x + unchecked((int)0x6d703ef3), s); } private int FF3(int a, int b, int c, int d, int x, int s) { return RL(a + F3(b, c, d) + x + unchecked((int)0x5c4dd124), s); } private int FF4(int a, int b, int c, int d, int x, int s) { return RL(a + F4(b, c, d) + x + unchecked((int)0x50a28be6), s); } internal override void ProcessBlock() { int a, aa; int b, bb; int c, cc; int d, dd; int t; a = H0; b = H1; c = H2; d = H3; aa = H4; bb = H5; cc = H6; dd = H7; // // Round 1 // a = F1(a, b, c, d, X[0], 11); d = F1(d, a, b, c, X[1], 14); c = F1(c, d, a, b, X[2], 15); b = F1(b, c, d, a, X[3], 12); a = F1(a, b, c, d, X[4], 5); d = F1(d, a, b, c, X[5], 8); c = F1(c, d, a, b, X[6], 7); b = F1(b, c, d, a, X[7], 9); a = F1(a, b, c, d, X[8], 11); d = F1(d, a, b, c, X[9], 13); c = F1(c, d, a, b, X[10], 14); b = F1(b, c, d, a, X[11], 15); a = F1(a, b, c, d, X[12], 6); d = F1(d, a, b, c, X[13], 7); c = F1(c, d, a, b, X[14], 9); b = F1(b, c, d, a, X[15], 8); aa = FF4(aa, bb, cc, dd, X[5], 8); dd = FF4(dd, aa, bb, cc, X[14], 9); cc = FF4(cc, dd, aa, bb, X[7], 9); bb = FF4(bb, cc, dd, aa, X[0], 11); aa = FF4(aa, bb, cc, dd, X[9], 13); dd = FF4(dd, aa, bb, cc, X[2], 15); cc = FF4(cc, dd, aa, bb, X[11], 15); bb = FF4(bb, cc, dd, aa, X[4], 5); aa = FF4(aa, bb, cc, dd, X[13], 7); dd = FF4(dd, aa, bb, cc, X[6], 7); cc = FF4(cc, dd, aa, bb, X[15], 8); bb = FF4(bb, cc, dd, aa, X[8], 11); aa = FF4(aa, bb, cc, dd, X[1], 14); dd = FF4(dd, aa, bb, cc, X[10], 14); cc = FF4(cc, dd, aa, bb, X[3], 12); bb = FF4(bb, cc, dd, aa, X[12], 6); t = a; a = aa; aa = t; // // Round 2 // a = F2(a, b, c, d, X[7], 7); d = F2(d, a, b, c, X[4], 6); c = F2(c, d, a, b, X[13], 8); b = F2(b, c, d, a, X[1], 13); a = F2(a, b, c, d, X[10], 11); d = F2(d, a, b, c, X[6], 9); c = F2(c, d, a, b, X[15], 7); b = F2(b, c, d, a, X[3], 15); a = F2(a, b, c, d, X[12], 7); d = F2(d, a, b, c, X[0], 12); c = F2(c, d, a, b, X[9], 15); b = F2(b, c, d, a, X[5], 9); a = F2(a, b, c, d, X[2], 11); d = F2(d, a, b, c, X[14], 7); c = F2(c, d, a, b, X[11], 13); b = F2(b, c, d, a, X[8], 12); aa = FF3(aa, bb, cc, dd, X[6], 9); dd = FF3(dd, aa, bb, cc, X[11], 13); cc = FF3(cc, dd, aa, bb, X[3], 15); bb = FF3(bb, cc, dd, aa, X[7], 7); aa = FF3(aa, bb, cc, dd, X[0], 12); dd = FF3(dd, aa, bb, cc, X[13], 8); cc = FF3(cc, dd, aa, bb, X[5], 9); bb = FF3(bb, cc, dd, aa, X[10], 11); aa = FF3(aa, bb, cc, dd, X[14], 7); dd = FF3(dd, aa, bb, cc, X[15], 7); cc = FF3(cc, dd, aa, bb, X[8], 12); bb = FF3(bb, cc, dd, aa, X[12], 7); aa = FF3(aa, bb, cc, dd, X[4], 6); dd = FF3(dd, aa, bb, cc, X[9], 15); cc = FF3(cc, dd, aa, bb, X[1], 13); bb = FF3(bb, cc, dd, aa, X[2], 11); t = b; b = bb; bb = t; // // Round 3 // a = F3(a, b, c, d, X[3], 11); d = F3(d, a, b, c, X[10], 13); c = F3(c, d, a, b, X[14], 6); b = F3(b, c, d, a, X[4], 7); a = F3(a, b, c, d, X[9], 14); d = F3(d, a, b, c, X[15], 9); c = F3(c, d, a, b, X[8], 13); b = F3(b, c, d, a, X[1], 15); a = F3(a, b, c, d, X[2], 14); d = F3(d, a, b, c, X[7], 8); c = F3(c, d, a, b, X[0], 13); b = F3(b, c, d, a, X[6], 6); a = F3(a, b, c, d, X[13], 5); d = F3(d, a, b, c, X[11], 12); c = F3(c, d, a, b, X[5], 7); b = F3(b, c, d, a, X[12], 5); aa = FF2(aa, bb, cc, dd, X[15], 9); dd = FF2(dd, aa, bb, cc, X[5], 7); cc = FF2(cc, dd, aa, bb, X[1], 15); bb = FF2(bb, cc, dd, aa, X[3], 11); aa = FF2(aa, bb, cc, dd, X[7], 8); dd = FF2(dd, aa, bb, cc, X[14], 6); cc = FF2(cc, dd, aa, bb, X[6], 6); bb = FF2(bb, cc, dd, aa, X[9], 14); aa = FF2(aa, bb, cc, dd, X[11], 12); dd = FF2(dd, aa, bb, cc, X[8], 13); cc = FF2(cc, dd, aa, bb, X[12], 5); bb = FF2(bb, cc, dd, aa, X[2], 14); aa = FF2(aa, bb, cc, dd, X[10], 13); dd = FF2(dd, aa, bb, cc, X[0], 13); cc = FF2(cc, dd, aa, bb, X[4], 7); bb = FF2(bb, cc, dd, aa, X[13], 5); t = c; c = cc; cc = t; // // Round 4 // a = F4(a, b, c, d, X[1], 11); d = F4(d, a, b, c, X[9], 12); c = F4(c, d, a, b, X[11], 14); b = F4(b, c, d, a, X[10], 15); a = F4(a, b, c, d, X[0], 14); d = F4(d, a, b, c, X[8], 15); c = F4(c, d, a, b, X[12], 9); b = F4(b, c, d, a, X[4], 8); a = F4(a, b, c, d, X[13], 9); d = F4(d, a, b, c, X[3], 14); c = F4(c, d, a, b, X[7], 5); b = F4(b, c, d, a, X[15], 6); a = F4(a, b, c, d, X[14], 8); d = F4(d, a, b, c, X[5], 6); c = F4(c, d, a, b, X[6], 5); b = F4(b, c, d, a, X[2], 12); aa = FF1(aa, bb, cc, dd, X[8], 15); dd = FF1(dd, aa, bb, cc, X[6], 5); cc = FF1(cc, dd, aa, bb, X[4], 8); bb = FF1(bb, cc, dd, aa, X[1], 11); aa = FF1(aa, bb, cc, dd, X[3], 14); dd = FF1(dd, aa, bb, cc, X[11], 14); cc = FF1(cc, dd, aa, bb, X[15], 6); bb = FF1(bb, cc, dd, aa, X[0], 14); aa = FF1(aa, bb, cc, dd, X[5], 6); dd = FF1(dd, aa, bb, cc, X[12], 9); cc = FF1(cc, dd, aa, bb, X[2], 12); bb = FF1(bb, cc, dd, aa, X[13], 9); aa = FF1(aa, bb, cc, dd, X[9], 12); dd = FF1(dd, aa, bb, cc, X[7], 5); cc = FF1(cc, dd, aa, bb, X[10], 15); bb = FF1(bb, cc, dd, aa, X[14], 8); t = d; d = dd; dd = t; H0 += a; H1 += b; H2 += c; H3 += d; H4 += aa; H5 += bb; H6 += cc; H7 += dd; // // reset the offset and clean out the word buffer. // xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } public override IMemoable Copy() { return new RipeMD256Digest(this); } public override void Reset(IMemoable other) { RipeMD256Digest d = (RipeMD256Digest)other; CopyIn(d); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ExportJobsOperationResultsOperations operations. /// </summary> internal partial class ExportJobsOperationResultsOperations : IServiceOperations<RecoveryServicesBackupClient>, IExportJobsOperationResultsOperations { /// <summary> /// Initializes a new instance of the ExportJobsOperationResultsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ExportJobsOperationResultsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Gets the operation result of operation triggered by Export Jobs API. If the /// operation is successful, then it also contains URL of a Blob and a SAS key /// to access the same. The blob contains exported jobs in JSON serialized /// format. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='operationId'> /// OperationID which represents the export job. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<OperationResultInfoBaseResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string operationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (operationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "operationId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs/operationResults/{operationId}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<OperationResultInfoBaseResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationResultInfoBaseResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// 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. // #define StressTest // set to raise the amount of time spent in concurrency tests that stress the collections using System; using System.Collections.Generic; using System.Collections.Tests; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public abstract class ProducerConsumerCollectionTests : IEnumerable_Generic_Tests<int> { protected override IEnumerable<ModifyEnumerable> ModifyEnumerables => new List<ModifyEnumerable>(); protected override int CreateT(int seed) => new Random(seed).Next(); protected override EnumerableOrder Order => EnumerableOrder.Unspecified; protected override IEnumerable<int> GenericIEnumerableFactory(int count) => CreateProducerConsumerCollection(count); protected IProducerConsumerCollection<int> CreateProducerConsumerCollection() => CreateProducerConsumerCollection<int>(); protected IProducerConsumerCollection<int> CreateProducerConsumerCollection(int count) => CreateProducerConsumerCollection(Enumerable.Range(0, count)); protected abstract IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>(); protected abstract IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection); protected abstract bool IsEmpty(IProducerConsumerCollection<int> pcc); protected abstract bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result); protected virtual IProducerConsumerCollection<int> CreateOracle() => CreateOracle(Enumerable.Empty<int>()); protected abstract IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection); protected static TaskFactory ThreadFactory { get; } = new TaskFactory( CancellationToken.None, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, TaskScheduler.Default); private const double ConcurrencyTestSeconds = #if StressTest 8.0; #else 1.0; #endif protected virtual string CopyToNoLengthParamName => "destinationArray"; [Fact] public void Ctor_InvalidArgs_Throws() { AssertExtensions.Throws<ArgumentNullException>("collection", () => CreateProducerConsumerCollection(null)); } [Fact] public void Ctor_NoArg_ItemsAndCountMatch() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Equal(0, c.Count); Assert.True(IsEmpty(c)); Assert.Equal(Enumerable.Empty<int>(), c); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(1000)] public void Ctor_Collection_ItemsAndCountMatch(int count) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, count)); IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(1, count)); Assert.Equal(oracle.Count == 0, IsEmpty(c)); Assert.Equal(oracle.Count, c.Count); Assert.Equal<int>(oracle, c); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(3)] [InlineData(1000)] public void Ctor_InitializeFromCollection_ContainsExpectedItems(int numItems) { var expected = new HashSet<int>(Enumerable.Range(0, numItems)); IProducerConsumerCollection<int> pcc = CreateProducerConsumerCollection(expected); Assert.Equal(expected.Count, pcc.Count); int item; var actual = new HashSet<int>(); for (int i = 0; i < expected.Count; i++) { Assert.Equal(expected.Count - i, pcc.Count); Assert.True(pcc.TryTake(out item)); actual.Add(item); } Assert.False(pcc.TryTake(out item)); Assert.Equal(0, item); AssertSetsEqual(expected, actual); } [Fact] public void Add_TakeFromAnotherThread_ExpectedItemsTaken() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.True(IsEmpty(c)); Assert.Equal(0, c.Count); const int NumItems = 100000; Task producer = Task.Run(() => Parallel.For(1, NumItems + 1, i => Assert.True(c.TryAdd(i)))); var hs = new HashSet<int>(); while (hs.Count < NumItems) { int item; if (c.TryTake(out item)) hs.Add(item); } producer.GetAwaiter().GetResult(); Assert.True(IsEmpty(c)); Assert.Equal(0, c.Count); AssertSetsEqual(new HashSet<int>(Enumerable.Range(1, NumItems)), hs); } [Fact] public void AddSome_ThenInterleaveAddsAndTakes_MatchesOracle() { IProducerConsumerCollection<int> c = CreateOracle(); IProducerConsumerCollection<int> oracle = CreateProducerConsumerCollection(); Action take = () => { int item1; Assert.True(c.TryTake(out item1)); int item2; Assert.True(oracle.TryTake(out item2)); Assert.Equal(item1, item2); Assert.Equal(c.Count, oracle.Count); Assert.Equal<int>(c, oracle); }; for (int i = 0; i < 100; i++) { Assert.True(oracle.TryAdd(i)); Assert.True(c.TryAdd(i)); Assert.Equal(c.Count, oracle.Count); Assert.Equal<int>(c, oracle); // Start taking some after we've added some if (i > 50) { take(); } } // Take the rest while (c.Count > 0) { take(); } } [Fact] public void AddTake_RandomChangesMatchOracle() { const int Iters = 1000; var r = new Random(42); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IProducerConsumerCollection<int> oracle = CreateOracle(); for (int i = 0; i < Iters; i++) { if (r.NextDouble() < .5) { Assert.Equal(oracle.TryAdd(i), c.TryAdd(i)); } else { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); } } Assert.Equal(oracle.Count, c.Count); } [Theory] [InlineData(100, 1, 100, true)] [InlineData(100, 4, 10, false)] [InlineData(1000, 11, 100, true)] [InlineData(100000, 2, 50000, true)] public void Initialize_ThenTakeOrPeekInParallel_ItemsObtainedAsExpected(int numStartingItems, int threadsCount, int itemsPerThread, bool take) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, numStartingItems)); int successes = 0; using (var b = new Barrier(threadsCount)) { WaitAllOrAnyFailed(Enumerable.Range(0, threadsCount).Select(threadNum => ThreadFactory.StartNew(() => { b.SignalAndWait(); for (int j = 0; j < itemsPerThread; j++) { int data; if (take ? c.TryTake(out data) : TryPeek(c, out data)) { Interlocked.Increment(ref successes); Assert.NotEqual(0, data); // shouldn't be default(T) } } })).ToArray()); } Assert.Equal( take ? numStartingItems : threadsCount * itemsPerThread, successes); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(1000)] public void ToArray_AddAllItemsThenEnumerate_ItemsAndCountMatch(int count) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IProducerConsumerCollection<int> oracle = CreateOracle(); for (int i = 0; i < count; i++) { Assert.Equal(oracle.TryAdd(i + count), c.TryAdd(i + count)); } Assert.Equal(oracle.ToArray(), c.ToArray()); if (count > 0) { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); Assert.Equal(oracle.ToArray(), c.ToArray()); } } [Theory] [InlineData(1, 10)] [InlineData(2, 10)] [InlineData(10, 10)] [InlineData(100, 10)] public void ToArray_AddAndTakeItemsIntermixedWithEnumeration_ItemsAndCountMatch(int initialCount, int iters) { IEnumerable<int> initialItems = Enumerable.Range(1, initialCount); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems); IProducerConsumerCollection<int> oracle = CreateOracle(initialItems); for (int i = 0; i < iters; i++) { Assert.Equal<int>(oracle, c); Assert.Equal(oracle.TryAdd(initialCount + i), c.TryAdd(initialCount + i)); Assert.Equal<int>(oracle, c); int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); Assert.Equal<int>(oracle, c); } } [Fact] public void AddFromMultipleThreads_ItemsRemainAfterThreadsGoAway() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); for (int i = 0; i < 1000; i += 100) { // Create a thread that adds items to the collection ThreadFactory.StartNew(() => { for (int j = i; j < i + 100; j++) { Assert.True(c.TryAdd(j)); } }).GetAwaiter().GetResult(); // Allow threads to be collected GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } AssertSetsEqual(new HashSet<int>(Enumerable.Range(0, 1000)), new HashSet<int>(c)); } [Fact] public void AddManyItems_ThenTakeOnSameThread_ItemsOutputInExpectedOrder() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 100000)); IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(0, 100000)); for (int i = 99999; i >= 0; --i) { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); } } [Fact] public void TryPeek_SucceedsOnEmptyCollectionThatWasOnceNonEmpty() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); int item; for (int i = 0; i < 2; i++) { Assert.False(TryPeek(c, out item)); Assert.Equal(0, item); } Assert.True(c.TryAdd(42)); for (int i = 0; i < 2; i++) { Assert.True(TryPeek(c, out item)); Assert.Equal(42, item); } Assert.True(c.TryTake(out item)); Assert.Equal(42, item); Assert.False(TryPeek(c, out item)); Assert.Equal(0, item); Assert.False(c.TryTake(out item)); Assert.Equal(0, item); } [Fact] public void AddTakeWithAtLeastOneElementInCollection_IsEmpty_AlwaysFalse() { int items = 1000; IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.True(c.TryAdd(0)); // make sure it's never empty var cts = new CancellationTokenSource(); // Consumer repeatedly calls IsEmpty until it's told to stop Task consumer = Task.Run(() => { while (!cts.IsCancellationRequested) Assert.False(IsEmpty(c)); }); // Producer adds/takes a bunch of items, then tells the consumer to stop Task producer = Task.Run(() => { int ignored; for (int i = 1; i <= items; i++) { Assert.True(c.TryAdd(i)); Assert.True(c.TryTake(out ignored)); } cts.Cancel(); }); Task.WaitAll(producer, consumer); } [Fact] public void CopyTo_Empty_NothingCopied() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); c.CopyTo(new int[0], 0); c.CopyTo(new int[10], 10); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void CopyTo_SzArray_ZeroIndex_ExpectedElementsCopied(int size) { IEnumerable<int> initialItems = Enumerable.Range(1, size); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems); int[] actual = new int[size]; c.CopyTo(actual, 0); IProducerConsumerCollection<int> oracle = CreateOracle(initialItems); int[] expected = new int[size]; oracle.CopyTo(expected, 0); Assert.Equal(expected, actual); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void CopyTo_SzArray_NonZeroIndex_ExpectedElementsCopied(int size) { IEnumerable<int> initialItems = Enumerable.Range(1, size); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems); int[] actual = new int[size + 2]; c.CopyTo(actual, 1); IProducerConsumerCollection<int> oracle = CreateOracle(initialItems); int[] expected = new int[size + 2]; oracle.CopyTo(expected, 1); Assert.Equal(expected, actual); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void CopyTo_ArrayZeroLowerBound_ZeroIndex_ExpectedElementsCopied(int size) { IEnumerable<int> initialItems = Enumerable.Range(1, size); ICollection c = CreateProducerConsumerCollection(initialItems); Array actual = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 }); c.CopyTo(actual, 0); ICollection oracle = CreateOracle(initialItems); Array expected = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 }); oracle.CopyTo(expected, 0); Assert.Equal(expected.Cast<int>(), actual.Cast<int>()); } [Fact] public void CopyTo_ArrayNonZeroLowerBound_ExpectedElementsCopied() { if (!PlatformDetection.IsNonZeroLowerBoundArraySupported) return; int[] initialItems = Enumerable.Range(1, 10).ToArray(); const int LowerBound = 1; ICollection c = CreateProducerConsumerCollection(initialItems); Array actual = Array.CreateInstance(typeof(int), new int[] { initialItems.Length }, new int[] { LowerBound }); c.CopyTo(actual, LowerBound); ICollection oracle = CreateOracle(initialItems); int[] expected = new int[initialItems.Length]; oracle.CopyTo(expected, 0); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual.GetValue(i + LowerBound)); } } [Fact] public void CopyTo_InvalidArgs_Throws() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 10)); int[] dest = new int[10]; AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1)); AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length)); AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length - 2)); AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new int[7, 7], 0)); } [Fact] public void ICollectionCopyTo_InvalidArgs_Throws() { ICollection c = CreateProducerConsumerCollection(Enumerable.Range(0, 10)); Array dest = new int[10]; AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1)); AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length)); AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length - 2)); } [Theory] [InlineData(100, 1, 10)] [InlineData(4, 100000, 10)] public void BlockingCollection_WrappingCollection_ExpectedElementsTransferred(int numThreadsPerConsumerProducer, int numItemsPerThread, int producerSpin) { var bc = new BlockingCollection<int>(CreateProducerConsumerCollection()); long dummy = 0; Task[] producers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() => { for (int i = 1; i <= numItemsPerThread; i++) { for (int j = 0; j < producerSpin; j++) dummy *= j; // spin a little bc.Add(i); } })).ToArray(); Task[] consumers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() => { for (int i = 0; i < numItemsPerThread; i++) { const int TimeoutMs = 100000; int item; Assert.True(bc.TryTake(out item, TimeoutMs), $"Couldn't get {i}th item after {TimeoutMs}ms"); Assert.NotEqual(0, item); } })).ToArray(); WaitAllOrAnyFailed(producers); WaitAllOrAnyFailed(consumers); } [Fact] public void GetEnumerator_NonGeneric() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IEnumerable e = c; Assert.False(e.GetEnumerator().MoveNext()); Assert.True(c.TryAdd(42)); Assert.True(c.TryAdd(84)); var hs = new HashSet<int>(e.Cast<int>()); Assert.Equal(2, hs.Count); Assert.Contains(42, hs); Assert.Contains(84, hs); } [Fact] public void GetEnumerator_EnumerationsAreSnapshots() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Empty(c); using (IEnumerator<int> e1 = c.GetEnumerator()) { Assert.True(c.TryAdd(1)); using (IEnumerator<int> e2 = c.GetEnumerator()) { Assert.True(c.TryAdd(2)); using (IEnumerator<int> e3 = c.GetEnumerator()) { int item; Assert.True(c.TryTake(out item)); using (IEnumerator<int> e4 = c.GetEnumerator()) { Assert.False(e1.MoveNext()); Assert.True(e2.MoveNext()); Assert.False(e2.MoveNext()); Assert.True(e3.MoveNext()); Assert.True(e3.MoveNext()); Assert.False(e3.MoveNext()); Assert.True(e4.MoveNext()); Assert.False(e4.MoveNext()); } } } } } [Theory] [InlineData(0, true)] [InlineData(1, true)] [InlineData(1, false)] [InlineData(10, true)] [InlineData(100, true)] [InlineData(100, false)] public async Task GetEnumerator_Generic_ExpectedElementsYielded(int numItems, bool consumeFromSameThread) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); using (var e = c.GetEnumerator()) { Assert.False(e.MoveNext()); } // Add, and validate enumeration after each item added for (int i = 1; i <= numItems; i++) { Assert.True(c.TryAdd(i)); Assert.Equal(i, c.Count); Assert.Equal(i, c.Distinct().Count()); } // Take, and validate enumerate after each item removed. Action consume = () => { for (int i = 1; i <= numItems; i++) { int item; Assert.True(c.TryTake(out item)); Assert.Equal(numItems - i, c.Count); Assert.Equal(numItems - i, c.Distinct().Count()); } }; if (consumeFromSameThread) { consume(); } else { await ThreadFactory.StartNew(consume); } } [Fact] public void TryAdd_TryTake_ToArray() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.True(c.TryAdd(42)); Assert.Equal(new[] { 42 }, c.ToArray()); Assert.True(c.TryAdd(84)); Assert.Equal(new[] { 42, 84 }, c.ToArray().OrderBy(i => i)); int item; Assert.True(c.TryTake(out item)); int remainingItem = item == 42 ? 84 : 42; Assert.Equal(new[] { remainingItem }, c.ToArray()); Assert.True(c.TryTake(out item)); Assert.Equal(remainingItem, item); Assert.Empty(c.ToArray()); } [Fact] public void ICollection_IsSynchronized_SyncRoot() { ICollection c = CreateProducerConsumerCollection(); Assert.False(c.IsSynchronized); Assert.Throws<NotSupportedException>(() => c.SyncRoot); } [Fact] public void ToArray_ParallelInvocations_Succeed() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Empty(c.ToArray()); const int NumItems = 10000; Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i))); Assert.Equal(NumItems, c.Count); Parallel.For(0, 10, i => { var hs = new HashSet<int>(c.ToArray()); Assert.Equal(NumItems, hs.Count); }); } [Fact] public void ToArray_AddTakeSameThread_ExpectedResultsAfterAddsAndTakes() { const int Items = 20; IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IProducerConsumerCollection<int> oracle = CreateOracle(); for (int i = 0; i < Items; i++) { Assert.True(c.TryAdd(i)); Assert.True(oracle.TryAdd(i)); Assert.Equal(oracle.ToArray(), c.ToArray()); } for (int i = Items - 1; i >= 0; i--) { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); Assert.Equal(oracle.ToArray(), c.ToArray()); } } [Fact] public void GetEnumerator_ParallelInvocations_Succeed() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Empty(c.ToArray()); const int NumItems = 10000; Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i))); Assert.Equal(NumItems, c.Count); Parallel.For(0, 10, i => { var hs = new HashSet<int>(c); Assert.Equal(NumItems, hs.Count); }); } [Theory] [InlineData(1, ConcurrencyTestSeconds / 2)] [InlineData(4, ConcurrencyTestSeconds / 2)] public void ManyConcurrentAddsTakes_EnsureTrackedCountsMatchResultingCollection(int threadsPerProc, double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); DateTime end = default(DateTime); using (var b = new Barrier(Environment.ProcessorCount * threadsPerProc, _ => end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds))) { Task<int>[] tasks = Enumerable.Range(0, b.ParticipantCount).Select(_ => ThreadFactory.StartNew(() => { b.SignalAndWait(); int count = 0; var rand = new Random(); while (DateTime.UtcNow < end) { if (rand.NextDouble() < .5) { Assert.True(c.TryAdd(rand.Next())); count++; } else { int item; if (c.TryTake(out item)) count--; } } return count; })).ToArray(); Task.WaitAll(tasks); Assert.Equal(tasks.Sum(t => t.Result), c.Count); } } [Fact] [OuterLoop] public void ManyConcurrentAddsTakes_CollectionRemainsConsistent() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); const int operations = 30000; Action addAndRemove = () => { for (int i = 1; i < operations; i++) { int addCount = new Random(12354).Next(1, 100); int item; for (int j = 0; j < addCount; j++) Assert.True(c.TryAdd(i)); for (int j = 0; j < addCount; j++) Assert.True(c.TryTake(out item)); } }; const int numberOfThreads = 3; var tasks = new Task[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++) tasks[i] = ThreadFactory.StartNew(addAndRemove); // Wait for them all to finish WaitAllOrAnyFailed(tasks); Assert.Empty(c); } [Theory] [InlineData(ConcurrencyTestSeconds)] public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsTaking(double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task<long> addsTakes = ThreadFactory.StartNew(() => { long total = 0; while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(i)); total++; } int item; if (TryPeek(c, out item)) { Assert.InRange(item, 1, MaxCount); } for (int i = 1; i <= MaxCount; i++) { if (c.TryTake(out item)) { total--; Assert.InRange(item, 1, MaxCount); } } } return total; }); Task<long> takesFromOtherThread = ThreadFactory.StartNew(() => { long total = 0; int item; while (DateTime.UtcNow < end) { if (c.TryTake(out item)) { total++; Assert.InRange(item, 1, MaxCount); } } return total; }); WaitAllOrAnyFailed(addsTakes, takesFromOtherThread); long remaining = addsTakes.Result - takesFromOtherThread.Result; Assert.InRange(remaining, 0, long.MaxValue); Assert.Equal(remaining, c.Count); } [Theory] [InlineData(ConcurrencyTestSeconds)] public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsPeeking(double seconds) { IProducerConsumerCollection<LargeStruct> c = CreateProducerConsumerCollection<LargeStruct>(); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task<long> addsTakes = ThreadFactory.StartNew(() => { long total = 0; while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(new LargeStruct(i))); total++; } LargeStruct item; Assert.True(TryPeek(c, out item)); Assert.InRange(item.Value, 1, MaxCount); for (int i = 1; i <= MaxCount; i++) { if (c.TryTake(out item)) { total--; Assert.InRange(item.Value, 1, MaxCount); } } } return total; }); Task peeksFromOtherThread = ThreadFactory.StartNew(() => { LargeStruct item; while (DateTime.UtcNow < end) { if (TryPeek(c, out item)) { Assert.InRange(item.Value, 1, MaxCount); } } }); WaitAllOrAnyFailed(addsTakes, peeksFromOtherThread); Assert.Equal(0, addsTakes.Result); Assert.Equal(0, c.Count); } [Theory] [InlineData(ConcurrencyTestSeconds)] public void ManyConcurrentAddsTakes_ForceContentionWithToArray(double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task addsTakes = ThreadFactory.StartNew(() => { while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(i)); } for (int i = 1; i <= MaxCount; i++) { int item; Assert.True(c.TryTake(out item)); Assert.InRange(item, 1, MaxCount); } } }); while (DateTime.UtcNow < end) { int[] arr = c.ToArray(); Assert.InRange(arr.Length, 0, MaxCount); Assert.DoesNotContain(0, arr); // make sure we didn't get default(T) } addsTakes.GetAwaiter().GetResult(); Assert.Equal(0, c.Count); } [Theory] [InlineData(0, ConcurrencyTestSeconds / 2)] [InlineData(1, ConcurrencyTestSeconds / 2)] public void ManyConcurrentAddsTakes_ForceContentionWithGetEnumerator(int initialCount, double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, initialCount)); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task addsTakes = ThreadFactory.StartNew(() => { while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(i)); } for (int i = 1; i <= MaxCount; i++) { int item; Assert.True(c.TryTake(out item)); Assert.InRange(item, 1, MaxCount); } } }); while (DateTime.UtcNow < end) { int[] arr = c.Select(i => i).ToArray(); Assert.InRange(arr.Length, initialCount, MaxCount + initialCount); Assert.DoesNotContain(0, arr); // make sure we didn't get default(T) } addsTakes.GetAwaiter().GetResult(); Assert.Equal(initialCount, c.Count); } [Theory] [InlineData(0)] [InlineData(10)] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributes_Success(int count) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(count); DebuggerAttributes.ValidateDebuggerDisplayReferences(c); DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(c); PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden); Array items = itemProperty.GetValue(info.Instance) as Array; Assert.Equal(c, items.Cast<int>()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerTypeProxy_Ctor_NullArgument_Throws() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Type proxyType = DebuggerAttributes.GetProxyType(c); var tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, new object[] { null })); Assert.IsType<ArgumentNullException>(tie.InnerException); } protected static void AssertSetsEqual<T>(HashSet<T> expected, HashSet<T> actual) { Assert.Equal(expected.Count, actual.Count); Assert.Subset(expected, actual); Assert.Subset(actual, expected); } protected static void WaitAllOrAnyFailed(params Task[] tasks) { if (tasks.Length == 0) { return; } int remaining = tasks.Length; var mres = new ManualResetEventSlim(); foreach (Task task in tasks) { task.ContinueWith(t => { if (Interlocked.Decrement(ref remaining) == 0 || t.IsFaulted) { mres.Set(); } }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } mres.Wait(); // Either all tasks are completed or at least one failed foreach (Task t in tasks) { if (t.IsFaulted) { t.GetAwaiter().GetResult(); // propagate for the first one that failed } } } private struct LargeStruct // used to help validate that values aren't torn while being read { private readonly long _a, _b, _c, _d, _e, _f, _g, _h; public LargeStruct(long value) { _a = _b = _c = _d = _e = _f = _g = _h = value; } public long Value { get { if (_a != _b || _a != _c || _a != _d || _a != _e || _a != _f || _a != _g || _a != _h) { throw new Exception($"Inconsistent {nameof(LargeStruct)}: {_a} {_b} {_c} {_d} {_e} {_f} {_g} {_h}"); } return _a; } } } } }
using System; using System.Text; using NDatabase.Api; using NDatabase.Meta; using NDatabase.Oid; namespace NDatabase.Core.Engine { /// <summary> /// Converts array of bytes into native objects and native objects into array of bytes /// </summary> internal static class ByteArrayConverter { private static readonly byte[] BytesForTrue = new byte[] {1}; private static readonly byte[] BytesForFalse = new byte[] {0}; private static readonly int IntSize = OdbType.Integer.Size; private static readonly int IntSizeX2 = OdbType.Integer.Size * 2; internal static byte[] BooleanToByteArray(bool b) { return b ? BytesForTrue : BytesForFalse; } internal static bool ByteArrayToBoolean(byte[] bytes) { return ByteArrayToBoolean(bytes, 0); } internal static bool ByteArrayToBoolean(byte[] bytes, int offset) { return bytes[offset] != 0; } internal static byte[] ShortToByteArray(short s) { return BitConverter.GetBytes(s); } internal static byte[] UShortToByteArray(ushort s) { return BitConverter.GetBytes(s); } internal static short ByteArrayToShort(byte[] bytes) { return BitConverter.ToInt16(bytes, 0); } internal static ushort ByteArrayToUShort(byte[] bytes) { return BitConverter.ToUInt16(bytes, 0); } internal static byte[] CharToByteArray(char c) { return BitConverter.GetBytes(c); } internal static char ByteArrayToChar(byte[] bytes) { return BitConverter.ToChar(bytes, 0); } /// <param name="s">Input</param> /// <param name="totalSpace"> The total space of the string (can be bigger that the real string size - to support later in place update) </param> /// <returns> The byte array that represent the string </returns> internal static byte[] StringToByteArray(String s, int totalSpace) { var stringBytes = Encoding.UTF8.GetBytes(s); var size = stringBytes.Length + IntSizeX2; var totalSize = totalSpace < size ? size : totalSpace; var totalSizeBytes = IntToByteArray(totalSize); var stringRealSize = IntToByteArray(stringBytes.Length); var bytes2 = new byte[totalSize + IntSizeX2]; Buffer.BlockCopy(totalSizeBytes, 0, bytes2, 0, 4); Buffer.BlockCopy(stringRealSize, 0, bytes2, 4, 4); Buffer.BlockCopy(stringBytes, 0, bytes2, 8, stringBytes.Length); return bytes2; } /// <returns> The String represented by the byte array </returns> internal static String ByteArrayToString(byte[] bytes) { var realSize = ByteArrayToInt(bytes, IntSize); return Encoding.UTF8.GetString(bytes, IntSizeX2, realSize); } internal static byte[] DecimalToByteArray(Decimal bigDecimal) { var bits = Decimal.GetBits(bigDecimal); return GetBytes(bits[0], bits[1], bits[2], bits[3]); } private static byte[] GetBytes(int lo, int mid, int hi, int flags) { var buffer = new byte[16]; buffer[0] = (byte) lo; buffer[1] = (byte) (lo >> 8); buffer[2] = (byte) (lo >> 16); buffer[3] = (byte) (lo >> 24); buffer[4] = (byte) mid; buffer[5] = (byte) (mid >> 8); buffer[6] = (byte) (mid >> 16); buffer[7] = (byte) (mid >> 24); buffer[8] = (byte) hi; buffer[9] = (byte) (hi >> 8); buffer[10] = (byte) (hi >> 16); buffer[11] = (byte) (hi >> 24); buffer[12] = (byte) flags; buffer[13] = (byte) (flags >> 8); buffer[14] = (byte) (flags >> 16); buffer[15] = (byte) (flags >> 24); return buffer; } internal static Decimal ByteArrayToDecimal(byte[] buffer) { var lo = (buffer[0]) | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24); var mid = (buffer[4]) | (buffer[5] << 8) | (buffer[6] << 16) | (buffer[7] << 24); var hi = (buffer[8]) | (buffer[9] << 8) | (buffer[10] << 16) | (buffer[11] << 24); var flags = (buffer[12]) | (buffer[13] << 8) | (buffer[14] << 16) | (buffer[15] << 24); return new Decimal(new[] {lo, mid, hi, flags}); } internal static byte[] IntToByteArray(int l) { return BitConverter.GetBytes(l); } internal static byte[] UIntToByteArray(uint l) { return BitConverter.GetBytes(l); } internal static int ByteArrayToInt(byte[] bytes) { return ByteArrayToInt(bytes, 0); } internal static int ByteArrayToInt(byte[] bytes, int offset) { return BitConverter.ToInt32(bytes, offset); } internal static uint ByteArrayToUInt(byte[] bytes) { return ByteArrayToUInt(bytes, 0); } private static uint ByteArrayToUInt(byte[] bytes, int offset) { return BitConverter.ToUInt32(bytes, offset); } internal static byte[] LongToByteArray(long l) { return BitConverter.GetBytes(l); } internal static byte[] ULongToByteArray(ulong l) { return BitConverter.GetBytes(l); } internal static ulong ByteArrayToULong(byte[] bytes) { return ByteArrayToULong(bytes, 0); } internal static byte[] DateToByteArray(DateTime date) { return LongToByteArray(date.Ticks); } internal static DateTime ByteArrayToDate(byte[] bytes) { var ticks = ByteArrayToLong(bytes); return new DateTime(ticks); } internal static byte[] FloatToByteArray(float f) { return BitConverter.GetBytes(f); } internal static float ByteArrayToFloat(byte[] bytes) { return BitConverter.ToSingle(bytes, 0); } internal static byte[] DoubleToByteArray(double d) { return BitConverter.GetBytes(d); } internal static double ByteArrayToDouble(byte[] bytes) { return BitConverter.ToDouble(bytes, 0); } internal static long ByteArrayToLong(byte[] bytes) { return ByteArrayToLong(bytes, 0); } internal static long ByteArrayToLong(byte[] bytes, int offset) { return BitConverter.ToInt64(bytes, offset); } private static ulong ByteArrayToULong(byte[] bytes, int offset) { return BitConverter.ToUInt64(bytes, offset); } internal static OID DecodeOid(byte[] bytes, int offset) { var oid = ByteArrayToLong(bytes, offset); return oid == -1 ? null : OIDFactory.BuildObjectOID(oid); } } }
// **************************************************************** // Copyright 2009, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** // **************************************************************** // Generated by the NUnit Syntax Generator // // Command Line: GenSyntax.exe SyntaxElements.txt // // DO NOT MODIFY THIS FILE DIRECTLY // **************************************************************** using System; using System.Collections; namespace NUnit.Framework.Constraints { /// <summary> /// ConstraintExpression represents a compound constraint in the /// process of being constructed from a series of syntactic elements. /// /// Individual elements are appended to the expression as they are /// reognized. Once an actual Constraint is appended, the expression /// returns a resolvable Constraint. /// </summary> public class ConstraintExpression : ConstraintExpressionBase { /// <summary> /// Initializes a new instance of the <see cref="T:ConstraintExpression"/> class. /// </summary> public ConstraintExpression() { } /// <summary> /// Initializes a new instance of the <see cref="T:ConstraintExpression"/> /// class passing in a ConstraintBuilder, which may be pre-populated. /// </summary> /// <param name="builder">The builder.</param> public ConstraintExpression(ConstraintBuilder builder) : base( builder ) { } #region Not /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression Not { get { return this.Append(new NotOperator()); } } /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression No { get { return this.Append(new NotOperator()); } } #endregion #region All /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them succeed. /// </summary> public ConstraintExpression All { get { return this.Append(new AllOperator()); } } #endregion #region Some /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if at least one of them succeeds. /// </summary> public ConstraintExpression Some { get { return this.Append(new SomeOperator()); } } #endregion #region None /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them fail. /// </summary> public ConstraintExpression None { get { return this.Append(new NoneOperator()); } } #endregion #region Property /// <summary> /// Returns a new PropertyConstraintExpression, which will either /// test for the existence of the named property on the object /// being tested or apply any following constraint to that property. /// </summary> public ResolvableConstraintExpression Property(string name) { return this.Append(new PropOperator(name)); } #endregion #region Length /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Length property of the object being tested. /// </summary> public ResolvableConstraintExpression Length { get { return Property("Length"); } } #endregion #region Count /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Count property of the object being tested. /// </summary> public ResolvableConstraintExpression Count { get { return Property("Count"); } } #endregion #region Message /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Message property of the object being tested. /// </summary> public ResolvableConstraintExpression Message { get { return Property("Message"); } } #endregion #region InnerException /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the InnerException property of the object being tested. /// </summary> public ResolvableConstraintExpression InnerException { get { return Property("InnerException"); } } #endregion #region Attribute /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute(Type expectedType) { return this.Append(new AttributeOperator(expectedType)); } #if NET_2_0 /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute<T>() { return Attribute(typeof(T)); } #endif #endregion #region With /// <summary> /// With is currently a NOP - reserved for future use. /// </summary> public ConstraintExpression With { get { return this.Append(new WithOperator()); } } #endregion #region Matches /// <summary> /// Returns the constraint provided as an argument - used to allow custom /// custom constraints to easily participate in the syntax. /// </summary> public Constraint Matches(Constraint constraint) { return this.Append(constraint); } #if NET_2_0 /// <summary> /// Returns the constraint provided as an argument - used to allow custom /// custom constraints to easily participate in the syntax. /// </summary> public Constraint Matches<T>(Predicate<T> predicate) { return this.Append(new PredicateConstraint<T>(predicate)); } #endif #endregion #region Null /// <summary> /// Returns a constraint that tests for null /// </summary> public NullConstraint Null { get { return (NullConstraint)this.Append(new NullConstraint()); } } #endregion #region True /// <summary> /// Returns a constraint that tests for True /// </summary> public TrueConstraint True { get { return (TrueConstraint)this.Append(new TrueConstraint()); } } #endregion #region False /// <summary> /// Returns a constraint that tests for False /// </summary> public FalseConstraint False { get { return (FalseConstraint)this.Append(new FalseConstraint()); } } #endregion #region NaN /// <summary> /// Returns a constraint that tests for NaN /// </summary> public NaNConstraint NaN { get { return (NaNConstraint)this.Append(new NaNConstraint()); } } #endregion #region Empty /// <summary> /// Returns a constraint that tests for empty /// </summary> public EmptyConstraint Empty { get { return (EmptyConstraint)this.Append(new EmptyConstraint()); } } #endregion #region Unique /// <summary> /// Returns a constraint that tests whether a collection /// contains all unique items. /// </summary> public UniqueItemsConstraint Unique { get { return (UniqueItemsConstraint)this.Append(new UniqueItemsConstraint()); } } #endregion #region BinarySerializable /// <summary> /// Returns a constraint that tests whether an object graph is serializable in binary format. /// </summary> public BinarySerializableConstraint BinarySerializable { get { return (BinarySerializableConstraint)this.Append(new BinarySerializableConstraint()); } } #endregion #region XmlSerializable /// <summary> /// Returns a constraint that tests whether an object graph is serializable in xml format. /// </summary> public XmlSerializableConstraint XmlSerializable { get { return (XmlSerializableConstraint)this.Append(new XmlSerializableConstraint()); } } #endregion #region EqualTo /// <summary> /// Returns a constraint that tests two items for equality /// </summary> public EqualConstraint EqualTo(object expected) { return (EqualConstraint)this.Append(new EqualConstraint(expected)); } #endregion #region SameAs /// <summary> /// Returns a constraint that tests that two references are the same object /// </summary> public SameAsConstraint SameAs(object expected) { return (SameAsConstraint)this.Append(new SameAsConstraint(expected)); } #endregion #region GreaterThan /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than the suppled argument /// </summary> public GreaterThanConstraint GreaterThan(object expected) { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(expected)); } #endregion #region GreaterThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the suppled argument /// </summary> public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected) { return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected)); } /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the suppled argument /// </summary> public GreaterThanOrEqualConstraint AtLeast(object expected) { return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected)); } #endregion #region LessThan /// <summary> /// Returns a constraint that tests whether the /// actual value is less than the suppled argument /// </summary> public LessThanConstraint LessThan(object expected) { return (LessThanConstraint)this.Append(new LessThanConstraint(expected)); } #endregion #region LessThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the suppled argument /// </summary> public LessThanOrEqualConstraint LessThanOrEqualTo(object expected) { return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected)); } /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the suppled argument /// </summary> public LessThanOrEqualConstraint AtMost(object expected) { return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected)); } #endregion #region TypeOf /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf(Type expectedType) { return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(expectedType)); } #if NET_2_0 /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf<T>() { return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(typeof(T))); } #endif #endregion #region InstanceOf /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf(Type expectedType) { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(expectedType)); } #if NET_2_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf<T>() { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(typeof(T))); } #endif /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> [Obsolete("Use InstanceOf(expectedType)")] public InstanceOfTypeConstraint InstanceOfType(Type expectedType) { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(expectedType)); } #if NET_2_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> [Obsolete("Use InstanceOf<T>()")] public InstanceOfTypeConstraint InstanceOfType<T>() { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(typeof(T))); } #endif #endregion #region AssignableFrom /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom(Type expectedType) { return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(expectedType)); } #if NET_2_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom<T>() { return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(typeof(T))); } #endif #endregion #region AssignableTo /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo(Type expectedType) { return (AssignableToConstraint)this.Append(new AssignableToConstraint(expectedType)); } #if NET_2_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo<T>() { return (AssignableToConstraint)this.Append(new AssignableToConstraint(typeof(T))); } #endif #endregion #region EquivalentTo /// <summary> /// Returns a constraint that tests whether the actual value /// is a collection containing the same elements as the /// collection supplied as an argument. /// </summary> public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected) { return (CollectionEquivalentConstraint)this.Append(new CollectionEquivalentConstraint(expected)); } #endregion #region SubsetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a subset of the collection supplied as an argument. /// </summary> public CollectionSubsetConstraint SubsetOf(IEnumerable expected) { return (CollectionSubsetConstraint)this.Append(new CollectionSubsetConstraint(expected)); } #endregion #region Ordered /// <summary> /// Returns a constraint that tests whether a collection is ordered /// </summary> public CollectionOrderedConstraint Ordered { get { return (CollectionOrderedConstraint)this.Append(new CollectionOrderedConstraint()); } } #endregion #region Member /// <summary> /// Returns a new CollectionContainsConstraint checking for the /// presence of a particular object in the collection. /// </summary> public CollectionContainsConstraint Member(object expected) { return (CollectionContainsConstraint)this.Append(new CollectionContainsConstraint(expected)); } /// <summary> /// Returns a new CollectionContainsConstraint checking for the /// presence of a particular object in the collection. /// </summary> public CollectionContainsConstraint Contains(object expected) { return (CollectionContainsConstraint)this.Append(new CollectionContainsConstraint(expected)); } #endregion #region Contains /// <summary> /// Returns a new ContainsConstraint. This constraint /// will, in turn, make use of the appropriate second-level /// constraint, depending on the type of the actual argument. /// This overload is only used if the item sought is a string, /// since any other type implies that we are looking for a /// collection member. /// </summary> public ContainsConstraint Contains(string expected) { return (ContainsConstraint)this.Append(new ContainsConstraint(expected)); } #endregion #region StringContaining /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> public SubstringConstraint StringContaining(string expected) { return (SubstringConstraint)this.Append(new SubstringConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> public SubstringConstraint ContainsSubstring(string expected) { return (SubstringConstraint)this.Append(new SubstringConstraint(expected)); } #endregion #region StartsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StartsWith(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StringStarting(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } #endregion #region EndsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint EndsWith(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint StringEnding(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } #endregion #region Matches /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the Regex pattern supplied as an argument. /// </summary> public RegexConstraint Matches(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the Regex pattern supplied as an argument. /// </summary> public RegexConstraint StringMatching(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } #endregion #region SamePath /// <summary> /// Returns a constraint that tests whether the path provided /// is the same as an expected path after canonicalization. /// </summary> public SamePathConstraint SamePath(string expected) { return (SamePathConstraint)this.Append(new SamePathConstraint(expected)); } #endregion #region SubPath /// <summary> /// Returns a constraint that tests whether the path provided /// is the same path or under an expected path after canonicalization. /// </summary> public SubPathConstraint SubPath(string expected) { return (SubPathConstraint)this.Append(new SubPathConstraint(expected)); } #endregion #region SamePathOrUnder /// <summary> /// Returns a constraint that tests whether the path provided /// is the same path or under an expected path after canonicalization. /// </summary> public SamePathOrUnderConstraint SamePathOrUnder(string expected) { return (SamePathOrUnderConstraint)this.Append(new SamePathOrUnderConstraint(expected)); } #endregion #region InRange /// <summary> /// Returns a constraint that tests whether the actual value falls /// within a specified range. /// </summary> public RangeConstraint InRange(IComparable from, IComparable to) { return (RangeConstraint)this.Append(new RangeConstraint(from, to)); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using Newtonsoft.Json.Linq; using ReactNative.Bridge; using System; using System.Threading; using System.Threading.Tasks; namespace ReactNative.Tests.Bridge { [TestClass] public class ReactInstanceTests { [TestMethod] public async Task ReactInstance_GetModules() { var module = new TestNativeModule(); var reactContext = new ReactContext(); var registry = new NativeModuleRegistry.Builder(reactContext) .Add(module) .Build(); var executor = new MockJavaScriptExecutor { OnCallFunctionReturnFlushedQueue = (_, __, ___) => JValue.CreateNull(), OnFlushQueue = () => JValue.CreateNull(), OnInvokeCallbackAndReturnFlushedQueue = (_, __) => JValue.CreateNull() }; var builder = new ReactInstance.Builder() { QueueConfiguration = TestReactQueueConfiguration.Create(_ => { }), Registry = registry, JavaScriptExecutorFactory = () => executor, BundleLoader = JavaScriptBundleLoader.CreateFileLoader("ms-appx:///Resources/test.js"), }; var instance = await DispatcherHelpers.CallOnDispatcherAsync(() => builder.Build()); reactContext.InitializeWithInstance(instance); var actualModule = instance.GetNativeModule<TestNativeModule>(); Assert.AreSame(module, actualModule); var firstJSModule = instance.GetJavaScriptModule<TestJavaScriptModule>(); var secondJSModule = instance.GetJavaScriptModule<TestJavaScriptModule>(); Assert.AreSame(firstJSModule, secondJSModule); await DispatcherHelpers.CallOnDispatcherAsync(instance.DisposeAsync); } [TestMethod] public async Task ReactInstance_Initialize_Dispose() { var mre = new ManualResetEvent(false); var module = new TestNativeModule { OnInitialized = () => mre.Set(), }; var reactContext = new ReactContext(); var registry = new NativeModuleRegistry.Builder(reactContext) .Add(module) .Build(); var executor = new MockJavaScriptExecutor { OnCallFunctionReturnFlushedQueue = (_, __, ___) => JValue.CreateNull(), OnFlushQueue = () => JValue.CreateNull(), OnInvokeCallbackAndReturnFlushedQueue = (_, __) => JValue.CreateNull() }; var builder = new ReactInstance.Builder() { QueueConfiguration = TestReactQueueConfiguration.Create(_ => { }), Registry = registry, JavaScriptExecutorFactory = () => executor, BundleLoader = JavaScriptBundleLoader.CreateFileLoader("ms-appx:///Resources/test.js"), }; var instance = await DispatcherHelpers.CallOnDispatcherAsync(() => builder.Build()); reactContext.InitializeWithInstance(instance); await DispatcherHelpers.CallOnDispatcherAsync(async () => await instance.InitializeAsync()); var caught = false; await DispatcherHelpers.CallOnDispatcherAsync(async () => { try { await instance.InitializeAsync(); } catch (InvalidOperationException) { caught = true; } }); Assert.IsTrue(caught); mre.WaitOne(); Assert.AreEqual(1, module.InitializeCalls); await DispatcherHelpers.CallOnDispatcherAsync(instance.DisposeAsync); Assert.AreEqual(1, module.OnReactInstanceDisposeCalls); // Dispose is idempotent await DispatcherHelpers.CallOnDispatcherAsync(instance.DisposeAsync); Assert.AreEqual(1, module.OnReactInstanceDisposeCalls); Assert.IsTrue(instance.IsDisposed); } [TestMethod] public async Task ReactInstance_ExceptionHandled_DoesNotDispose() { var eventHandler = new AutoResetEvent(false); var module = new OnDisposeNativeModule(() => eventHandler.Set()); var registry = new NativeModuleRegistry.Builder(new ReactContext()) .Add(module) .Build(); var executor = new MockJavaScriptExecutor { OnCallFunctionReturnFlushedQueue = (_, __, ___) => JValue.CreateNull(), OnFlushQueue = () => JValue.CreateNull(), OnInvokeCallbackAndReturnFlushedQueue = (_, __) => JValue.CreateNull() }; var exception = new Exception(); var tcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously); var builder = new ReactInstance.Builder() { QueueConfiguration = TestReactQueueConfiguration.Create(tcs.SetResult), Registry = registry, JavaScriptExecutorFactory = () => executor, BundleLoader = JavaScriptBundleLoader.CreateFileLoader("ms-appx:///Resources/test.js"), }; var instance = await DispatcherHelpers.CallOnDispatcherAsync(() => builder.Build()); instance.QueueConfiguration.JavaScriptQueue.Dispatch(() => { throw exception; }); var actualException = await tcs.Task; Assert.AreSame(exception, actualException); Assert.IsFalse(eventHandler.WaitOne(500)); Assert.IsFalse(instance.IsDisposed); } class TestNativeModule : NativeModuleBase { public Action OnInitialized { get; set; } public int InitializeCalls { get; set; } public int OnReactInstanceDisposeCalls { get; set; } public override string Name { get { return "Test"; } } public override void Initialize() { InitializeCalls++; OnInitialized?.Invoke(); } public override Task OnReactInstanceDisposeAsync() { OnReactInstanceDisposeCalls++; return Task.CompletedTask; } } class OnDisposeNativeModule : NativeModuleBase { private readonly Action _onDispose; public OnDisposeNativeModule(Action onDispose) { _onDispose = onDispose; } public override string Name { get { return "Test"; } } public override Task OnReactInstanceDisposeAsync() { _onDispose(); return Task.CompletedTask; } } class TestJavaScriptModule : JavaScriptModuleBase { } } }
// 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 System.Globalization; using Xunit; public static class StringBuilderTests { [Fact] public static void TestToString() { StringBuilder sb = new StringBuilder("Finally"); String s = sb.ToString(2, 3); Assert.Equal(s, "nal"); } [Fact] public static void TestReplace() { StringBuilder sb; String s; sb = new StringBuilder("aaaabbbbccccdddd"); sb.Replace('a', '!', 2, 3); s = sb.ToString(); Assert.Equal(s, "aa!!bbbbccccdddd"); sb = new StringBuilder("aaaabbbbccccdddd"); sb.Replace("a", "$!", 2, 3); s = sb.ToString(); Assert.Equal(s, "aa$!$!bbbbccccdddd"); } [Fact] public static void TestRemove() { StringBuilder sb = new StringBuilder("Almost"); sb.Remove(1, 3); String s = sb.ToString(); Assert.Equal(s, "Ast"); } [Fact] public static void TestInsert() { //@todo: Not testing all the Insert() overloads that just call ToString() on the input and forward to Insert(int, String). StringBuilder sb = new StringBuilder("Hello"); sb.Insert(2, "!!"); String s = sb.ToString(); Assert.Equal(s, "He!!llo"); } [Fact] public static void TestEquals() { StringBuilder sb1 = new StringBuilder("Hello"); StringBuilder sb2 = new StringBuilder("HelloX"); bool b; b = sb1.Equals(sb1); Assert.True(b); b = sb1.Equals(sb2); Assert.False(b); } [Fact] public static void TestCopyTo() { StringBuilder sb; sb = new StringBuilder("Hello"); char[] ca = new char[10]; sb.CopyTo(1, ca, 5, 4); Assert.Equal(ca[0], 0); Assert.Equal(ca[1], 0); Assert.Equal(ca[2], 0); Assert.Equal(ca[3], 0); Assert.Equal(ca[4], 0); Assert.Equal(ca[5], 'e'); Assert.Equal(ca[6], 'l'); Assert.Equal(ca[7], 'l'); Assert.Equal(ca[8], 'o'); Assert.Equal(ca[9], 0); } [Fact] public static void TestClear() { StringBuilder sb; String s; sb = new StringBuilder("Hello"); sb.Clear(); s = sb.ToString(); Assert.Equal(s, ""); } [Fact] public static void TestLength() { StringBuilder sb; String s; int len; sb = new StringBuilder("Hello"); len = sb.Length; Assert.Equal(len, 5); sb.Length = 2; len = sb.Length; Assert.Equal(len, 2); s = sb.ToString(); Assert.Equal(s, "He"); sb.Length = 10; len = sb.Length; Assert.Equal(len, 10); s = sb.ToString(); Assert.Equal(s, "He" + new String((char)0, 8)); } [Fact] public static void TestAppendFormat() { StringBuilder sb; String s; sb = new StringBuilder(); sb.AppendFormat("Foo {0} Bar {1}", "Red", "Green"); s = sb.ToString(); Assert.Equal(s, "Foo Red Bar Green"); } [Fact] public static void TestAppend() { //@todo: Skipped all the Append overloads that just call ToString() on the argument and delegate to Append(String) StringBuilder sb; String s; sb = new StringBuilder(); s = ""; for (int i = 0; i < 500; i++) { char c = (char)(0x41 + (i % 10)); sb.Append(c); s += c; Assert.Equal(sb.ToString(), s); } sb = new StringBuilder(); s = ""; for (int i = 0; i < 500; i++) { char c = (char)(0x41 + (i % 10)); int repeat = i % 8; sb.Append(c, repeat); s += new String(c, repeat); Assert.Equal(sb.ToString(), s); } sb = new StringBuilder(); s = ""; for (int i = 0; i < 500; i++) { char c = (char)(0x41 + (i % 10)); int repeat = i % 8; char[] ca = new char[repeat]; for (int j = 0; j < ca.Length; j++) ca[j] = c; sb.Append(ca); s += new String(ca); Assert.Equal(sb.ToString(), s); } sb = new StringBuilder(); s = ""; for (int i = 0; i < 500; i++) { sb.Append("ab"); s += "ab"; Assert.Equal(sb.ToString(), s); } sb = new StringBuilder(); s = "Hello"; sb.Append(s, 2, 3); Assert.Equal(sb.ToString(), "llo"); } [Fact] public static void TestChars() { StringBuilder sb = new StringBuilder("Hello"); char c = sb[1]; Assert.Equal(c, 'e'); sb[1] = 'X'; String s = sb.ToString(); Assert.Equal(s, "HXllo"); } [Fact] public static void TestCtors() { StringBuilder sb; String s; int c; int l; int m; sb = new StringBuilder(); s = sb.ToString(); Assert.Equal(s, ""); l = sb.Length; Assert.Equal(l, 0); sb = new StringBuilder(42); c = sb.Capacity; Assert.True(c >= 42); l = sb.Length; Assert.Equal(l, 0); // The second int parameter is MaxCapacity but in CLR4.0 and later, StringBuilder isn't required to honor it. sb = new StringBuilder(42, 50); c = sb.Capacity; Assert.True(c >= 42); l = sb.Length; Assert.Equal(l, 0); m = sb.MaxCapacity; Assert.Equal(m, 50); sb = new StringBuilder("Hello"); s = sb.ToString(); Assert.Equal(s, "Hello"); l = sb.Length; Assert.Equal(l, 5); sb = new StringBuilder("Hello", 42); s = sb.ToString(); Assert.Equal(s, "Hello"); c = sb.Capacity; Assert.True(c >= 42); l = sb.Length; Assert.Equal(l, 5); sb = new StringBuilder("Hello", 2, 3, 42); s = sb.ToString(); Assert.Equal(s, "llo"); c = sb.Capacity; Assert.True(c >= 42); l = sb.Length; Assert.Equal(l, 3); } [Fact] public unsafe static void TestAppendUsingNativePointers() { StringBuilder sb = new StringBuilder(); string s = "abc "; fixed (char* pS = s) { sb.Append(pS, s.Length); sb.Append(pS, s.Length); } Assert.True("abc abc ".Equals(sb.ToString(), StringComparison.Ordinal)); } [Fact] public unsafe static void TestAppendUsingNativePointerExceptions() { StringBuilder sb = new StringBuilder(); string s = "abc "; fixed (char* pS = s) { Assert.Throws<NullReferenceException>(() => sb.Append(null, s.Length)); char* p = pS; // cannot use pS directly inside an anonymous method Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(p, -1)); } } }
// // The PickerViewController // using MonoTouch.Foundation; using MonoTouch.UIKit; using System.Drawing; using System; namespace MonoCatalog { public partial class PickerViewController : UIViewController { UIPickerView myPickerView, customPickerView; UIDatePicker datePickerView; UILabel label; public PickerViewController () : base ("PickerViewController", null) { } public override void ViewDidLoad () { base.ViewDidLoad (); Title = "Picker"; CreatePicker (); CreateDatePicker (); CreateCustomPicker (); // Colors buttonBarSegmentedControl.TintColor = UIColor.DarkGray; pickerStyleSegmentedControl.TintColor = UIColor.DarkGray; label = new UILabel (new RectangleF (20f, myPickerView.Frame.Y - 30f, View.Bounds.Width - 40f, 30f)){ Font = UIFont.SystemFontOfSize (14), TextAlignment = UITextAlignment.Center, TextColor = UIColor.White, BackgroundColor = UIColor.Clear }; View.AddSubview (label); buttonBarSegmentedControl.SelectedSegment = 0; datePickerView.Mode = UIDatePickerMode.Date; } public override void ViewWillAppear (bool animated) { NavigationController.NavigationBar.BarStyle = UIBarStyle.Black; UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.BlackOpaque; TogglePickers (buttonBarSegmentedControl); } public override void ViewWillDisappear (bool animated) { if (currentPicker != null) currentPicker.Hidden = true; NavigationController.NavigationBar.BarStyle = UIBarStyle.Default; UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.Default; } RectangleF PickerFrameWithSize (SizeF size) { var screenRect = UIScreen.MainScreen.ApplicationFrame; return new RectangleF (0f, screenRect.Height - 84f - size.Height, size.Width, size.Height); } UIView currentPicker; void ShowPicker (UIView picker) { if (currentPicker != null){ currentPicker.Hidden = true; label.Text = ""; } picker.Hidden = false; currentPicker = picker; } #region Hooks from Interface Builder [Export ("togglePickers:")] public void TogglePickers (UISegmentedControl sender) { switch (sender.SelectedSegment){ case 0: pickerStyleSegmentedControl.Hidden = true; segmentLabel.Hidden = true; ShowPicker (myPickerView); break; case 1: pickerStyleSegmentedControl.SelectedSegment = 1; datePickerView.Mode = UIDatePickerMode.Date; pickerStyleSegmentedControl.Hidden = false; segmentLabel.Hidden = false; ShowPicker (datePickerView); break; case 2: pickerStyleSegmentedControl.Hidden = true; segmentLabel.Hidden = true; ShowPicker (customPickerView); break; } } [Export ("togglePickerStyle:")] public void TogglePickerStyle (UISegmentedControl sender) { switch (sender.SelectedSegment){ case 0: // time datePickerView.Mode = UIDatePickerMode.Time; break; case 1: // date datePickerView.Mode = UIDatePickerMode.Date; break; case 2: // date & time datePickerView.Mode = UIDatePickerMode.DateAndTime; break; case 3: // counter datePickerView.Mode = UIDatePickerMode.CountDownTimer; break; } datePickerView.Date = NSDate.Now; //DateTime.Now; Console.WriteLine ("Date is: {0} {1} {2}", NSDate.Now.ToString (), ((NSDate) DateTime.Now).ToString (), DateTime.Now); } #endregion #region Custom picker public void CreateCustomPicker () { customPickerView = new UIPickerView (RectangleF.Empty) { AutoresizingMask = UIViewAutoresizing.FlexibleWidth, Model = new CustomPickerModel (), ShowSelectionIndicator = true, Hidden = true }; customPickerView.Frame = PickerFrameWithSize (customPickerView.SizeThatFits (SizeF.Empty)); View.AddSubview (customPickerView); } #endregion #region Date picker public void CreateDatePicker () { datePickerView = new UIDatePicker (RectangleF.Empty) { AutoresizingMask = UIViewAutoresizing.FlexibleWidth, Mode = UIDatePickerMode.Date, Hidden = true }; datePickerView.Frame = PickerFrameWithSize (datePickerView.SizeThatFits (SizeF.Empty)); View.AddSubview (datePickerView); } #endregion #region People picker void CreatePicker () { // // Empty is used, since UIPickerViews have auto-sizing, // all that is required is the origin // myPickerView = new UIPickerView (RectangleF.Empty){ AutoresizingMask = UIViewAutoresizing.FlexibleWidth, ShowSelectionIndicator = true, Model = new PeopleModel (this), Hidden = true }; // Now update it: myPickerView.Frame = PickerFrameWithSize (myPickerView.SizeThatFits (SizeF.Empty)); View.AddSubview (myPickerView); } public class PeopleModel : UIPickerViewModel { static string [] names = new string [] { "Brian Kernighan", "Dennis Ritchie", "Ken Thompson", "Kirk McKusick", "Rob Pike", "Dave Presotto", "Steve Johnson" }; PickerViewController pvc; public PeopleModel (PickerViewController pvc) { this.pvc = pvc; } public override int GetComponentCount (UIPickerView v) { return 2; } public override int GetRowsInComponent (UIPickerView pickerView, int component) { return names.Length; } public override string GetTitle (UIPickerView picker, int row, int component) { if (component == 0) return names [row]; else return row.ToString (); } public override void Selected (UIPickerView picker, int row, int component) { pvc.label.Text = String.Format ("{0} - {1}", names [picker.SelectedRowInComponent (0)], picker.SelectedRowInComponent (1)); } public override float GetComponentWidth (UIPickerView picker, int component) { if (component == 0) return 240f; else return 40f; } public override float GetRowHeight (UIPickerView picker, int component) { return 40f; } } #endregion } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. // Licensed under the MIT License. using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Data; using System.Collections; using System.Globalization; using System.ComponentModel; namespace InteractiveDataDisplay.WPF { /// <summary> /// A plot to draw simple line. /// </summary> [Description("Plots line graph")] public class LineGraph : Plot { private Polyline polyline; /// <summary> /// Gets or sets line graph points. /// </summary> [Category("InteractiveDataDisplay")] [Description("Line graph points")] public PointCollection Points { get { return (PointCollection)GetValue(PointsProperty); } set { SetValue(PointsProperty, value); } } private static void PointsPropertyChangedHandler(DependencyObject d, DependencyPropertyChangedEventArgs e) { LineGraph linePlot = (LineGraph)d; if (linePlot != null) { InteractiveDataDisplay.WPF.Plot.SetPoints(linePlot.polyline, (PointCollection)e.NewValue); } } /// <summary> /// Initializes a new instance of <see cref="LineGraph"/> class. /// </summary> public LineGraph() { polyline = new Polyline { Stroke = new SolidColorBrush(Colors.Black), StrokeLineJoin = PenLineJoin.Round }; BindingOperations.SetBinding(polyline, Polyline.StrokeThicknessProperty, new Binding("StrokeThickness") { Source = this }); BindingOperations.SetBinding(this, PlotBase.PaddingProperty, new Binding("StrokeThickness") { Source = this, Converter = new LineGraphThicknessConverter() }); Children.Add(polyline); } static LineGraph() { PointsProperty.OverrideMetadata(typeof(LineGraph), new PropertyMetadata(new PointCollection(), PointsPropertyChangedHandler) ); } /// <summary> /// Updates data in <see cref="Points"/> and causes a redrawing of line graph. /// </summary> /// <param name="x">A set of x coordinates of new points.</param> /// <param name="y">A set of y coordinates of new points.</param> public void Plot(IEnumerable x, IEnumerable y) { if (x == null) throw new ArgumentNullException("x"); if (y == null) throw new ArgumentNullException("y"); var points = new PointCollection(); var enx = x.GetEnumerator(); var eny = y.GetEnumerator(); while (true) { var nx = enx.MoveNext(); var ny = eny.MoveNext(); if (nx && ny) points.Add(new Point(Convert.ToDouble(enx.Current, CultureInfo.InvariantCulture), Convert.ToDouble(eny.Current, CultureInfo.InvariantCulture))); else if (!nx && !ny) break; else throw new ArgumentException("x and y have different lengthes"); } Points = points; } /// <summary> /// Updates data in <see cref="Points"/> and causes a redrawing of line graph. /// In this version a set of x coordinates is a sequence of integers starting with zero. /// </summary> /// <param name="y">A set of y coordinates of new points.</param> public void PlotY(IEnumerable y) { if (y == null) throw new ArgumentNullException("y"); int x = 0; var en = y.GetEnumerator(); var points = new PointCollection(); while (en.MoveNext()) points.Add(new Point(x++, Convert.ToDouble(en.Current, CultureInfo.InvariantCulture))); Points = points; } #region Description /// <summary> /// Identifies the <see cref="Description"/> dependency property. /// </summary> public static readonly DependencyProperty DescriptionProperty = DependencyProperty.Register("Description", typeof(string), typeof(LineGraph), new PropertyMetadata(null, (s, a) => { var lg = (LineGraph)s; ToolTipService.SetToolTip(lg, a.NewValue); })); /// <summary> /// Gets or sets description text for line graph. Description text appears in default /// legend and tooltip. /// </summary> [Category("InteractiveDataDisplay")] public string Description { get { return (string)GetValue(DescriptionProperty); } set { SetValue(DescriptionProperty, value); } } #endregion #region Thickness /// <summary> /// Identifies the <see cref="Thickness"/> dependency property. /// </summary> public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register("StrokeThickness", typeof(double), typeof(LineGraph), new PropertyMetadata(1.0)); /// <summary> /// Gets or sets the line thickness. /// </summary> /// <remarks> /// The default stroke thickness is 1.0 /// </remarks> [Category("Appearance")] public double StrokeThickness { get { return (double)GetValue(StrokeThicknessProperty); } set { SetValue(StrokeThicknessProperty, value); } } #endregion #region Stroke /// <summary> /// Identifies the <see cref="Stroke"/> dependency property. /// </summary> public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register("Stroke", typeof(Brush), typeof(LineGraph), new PropertyMetadata(new SolidColorBrush(Colors.Black), OnStrokeChanged)); private static void OnStrokeChanged(object target, DependencyPropertyChangedEventArgs e) { LineGraph lineGraph = (LineGraph)target; lineGraph.polyline.Stroke = e.NewValue as Brush; } /// <summary> /// Gets or sets the brush to draw the line. /// </summary> /// <remarks> /// The default color of stroke is black /// </remarks> [Category("Appearance")] public Brush Stroke { get { return (Brush)GetValue(StrokeProperty); } set { SetValue(StrokeProperty, value); } } #endregion #region StrokeDashArray private static DoubleCollection EmptyDoubleCollection { get { var result = new DoubleCollection(0); result.Freeze(); return result; } } /// <summary> /// Identifies the <see cref="StrokeDashArray"/> dependency property. /// </summary> public static readonly DependencyProperty StrokeDashArrayProperty = DependencyProperty.Register("StrokeDashArray", typeof(DoubleCollection), typeof(LineGraph), new PropertyMetadata(EmptyDoubleCollection, OnStrokeDashArrayChanged)); private static void OnStrokeDashArrayChanged(object target, DependencyPropertyChangedEventArgs e) { LineGraph lineGraph = (LineGraph)target; lineGraph.polyline.StrokeDashArray = e.NewValue as DoubleCollection; } /// <summary> /// Gets or sets a collection of <see cref="Double"/> values that indicate the pattern of dashes and gaps that is used to draw the line. /// </summary> [Category("Appearance")] public DoubleCollection StrokeDashArray { get { return (DoubleCollection)GetValue(StrokeDashArrayProperty); } set { SetValue(StrokeDashArrayProperty, value); } } #endregion } internal class LineGraphThicknessConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { double thickness = (double)value; return new Thickness(thickness / 2.0); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
// Copyright 2020 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using NodaTime.Extensions; namespace NodaTime.Xml { /// <summary> /// Provides XML schema types. /// </summary> public static class XmlSchemaDefinition { /// <summary> /// Gets the XML namespace for all NodaTime types. /// </summary> /// <remarks>See [Namespaces in XML 1.1 (Second Edition)](https://www.w3.org/TR/xml-names11/).</remarks> public static XmlQualifiedName NodaTimeXmlNamespace { get; } = new XmlQualifiedName("nodatime", "https://nodatime.org/api/"); /// <summary> /// Gets the compiled XML schema describing the structure for all NodaTime types that implement the <see cref="IXmlSerializable"/> interface. /// </summary> /// <remarks> /// All the pattern restrictions as regular expressions are not meant to fully validate the XML content, /// they only serve to describe the general shape of the XML content. /// </remarks> public static XmlSchema NodaTimeXmlSchema { get; } internal static XmlQualifiedName AddAnnualDateSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, AnnualDateSchemaType); internal static XmlQualifiedName AddDurationSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, DurationSchemaType); internal static XmlQualifiedName AddInstantSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, InstantSchemaType); internal static XmlQualifiedName AddIntervalSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, IntervalSchemaType); internal static XmlQualifiedName AddLocalDateSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, LocalDateSchemaType); internal static XmlQualifiedName AddLocalDateTimeSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, LocalDateTimeSchemaType); internal static XmlQualifiedName AddLocalTimeSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, LocalTimeSchemaType); internal static XmlQualifiedName AddOffsetSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, OffsetSchemaType); internal static XmlQualifiedName AddOffsetDateSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, OffsetDateSchemaType); internal static XmlQualifiedName AddOffsetDateTimeSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, OffsetDateTimeSchemaType); internal static XmlQualifiedName AddOffsetTimeSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, OffsetTimeSchemaType); internal static XmlQualifiedName AddPeriodBuilderSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, PeriodBuilderSchemaType); internal static XmlQualifiedName AddYearMonthSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, YearMonthSchemaType); internal static XmlQualifiedName AddZonedDateTimeSchemaType(XmlSchemaSet schemaSet) => AddSchemaType(schemaSet, ZonedDateTimeSchemaType); private const string YearPattern = @"-?[0-9]{4}"; private const string MonthPattern = @"[0-9]{2}"; private const string DayPattern = @"[0-9]{2}"; private const string TimePattern = @"[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{1,9})?"; private const string OffsetPattern = @"(Z|[+-][0-9]{2}(:[0-9]{2}(:[0-9]{2})?)?)"; private const string PeriodBuilderPattern = @"P(-?[0-9]+Y)?(-?[0-9]+M)?(-?[0-9]+W)?(-?[0-9]+D)?(T(-?[0-9]+H)?(-?[0-9]+M)?(-?[0-9]+S)?(-?[0-9]+s)?(-?[0-9]+t)?(-?[0-9]+n)?)?"; private const string DurationPattern = @"-?[0-9]{1,8}:[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{1,9})?"; static XmlSchemaDefinition() { var xsStringType = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String); var calendarRestriction = CreateEnumerationRestriction("calendar", xsStringType, CalendarSystem.Ids); var localDateRestriction = CreatePatternRestriction("localDate", xsStringType, $"{YearPattern}-{MonthPattern}-{DayPattern}"); var localDateTimeRestriction = CreatePatternRestriction("localDateTime", xsStringType, $"{YearPattern}-{MonthPattern}-{DayPattern}T{TimePattern}"); var zoneIds = CreateEnumerationRestriction("zoneIds", xsStringType, XmlSerializationSettings.DateTimeZoneProvider.GetAllZones().Select(e => e.Id)); // The "zoneIds" purpose is to document the known zone identifiers. The "zone" restriction is a union between known zone ids and // xs:string so that validation won't fail when a new zone identifier is added to the Time Zone Database. var zoneRestriction = QualifySchemaType(new XmlSchemaSimpleType { Name = "zone", Content = new XmlSchemaSimpleTypeUnion { MemberTypes = new[] { zoneIds.QualifiedName, xsStringType.QualifiedName } } }); var calendarAttribute = new XmlSchemaAttribute { Name = "calendar", SchemaTypeName = calendarRestriction.QualifiedName }; var zoneAttribute = new XmlSchemaAttribute { Name = "zone", SchemaTypeName = zoneRestriction.QualifiedName, Use = XmlSchemaUse.Required }; AnnualDateSchemaType = CreatePatternRestriction<AnnualDate>(xsStringType, $"{MonthPattern}-{DayPattern}"); DurationSchemaType = CreatePatternRestriction<Duration>(xsStringType, DurationPattern); InstantSchemaType = CreatePatternRestriction<Instant>(xsStringType, $"{YearPattern}-{MonthPattern}-{DayPattern}T{TimePattern}Z"); IntervalSchemaType = new XmlSchemaComplexType { Name = nameof(Interval), Attributes = { new XmlSchemaAttribute { Name = "start", SchemaTypeName = InstantSchemaType.QualifiedName }, new XmlSchemaAttribute { Name = "end", SchemaTypeName = InstantSchemaType.QualifiedName } } }; LocalDateSchemaType = CreateSchemaTypeWithAttributes<LocalDate>(localDateRestriction, calendarAttribute); LocalDateTimeSchemaType = CreateSchemaTypeWithAttributes<LocalDateTime>(localDateTimeRestriction, calendarAttribute); LocalTimeSchemaType = CreatePatternRestriction<LocalTime>(xsStringType, TimePattern); OffsetSchemaType = CreatePatternRestriction<Offset>(xsStringType, OffsetPattern); OffsetDateSchemaType = CreatePatternRestriction<OffsetDate>(xsStringType, $"{YearPattern}-{MonthPattern}-{DayPattern}{OffsetPattern}"); OffsetDateTimeSchemaType = CreatePatternRestriction<OffsetDateTime>(xsStringType, $"{YearPattern}-{MonthPattern}-{DayPattern}T{TimePattern}{OffsetPattern}"); OffsetTimeSchemaType = CreatePatternRestriction<OffsetTime>(xsStringType, $"{TimePattern}{OffsetPattern}"); PeriodBuilderSchemaType = CreatePatternRestriction<PeriodBuilder>(xsStringType, PeriodBuilderPattern); YearMonthSchemaType = CreatePatternRestriction<YearMonth>(xsStringType, $"{YearPattern}-{MonthPattern}"); ZonedDateTimeSchemaType = CreateSchemaTypeWithAttributes<ZonedDateTime>(OffsetDateTimeSchemaType, zoneAttribute, calendarAttribute); DependentSchemaTypes = new Dictionary<XmlSchemaType, IEnumerable<XmlSchemaType>> { [IntervalSchemaType] = new[] { InstantSchemaType }, [LocalDateSchemaType] = new[] { localDateRestriction, calendarRestriction }, [LocalDateTimeSchemaType] = new[] { localDateTimeRestriction, calendarRestriction }, [ZonedDateTimeSchemaType] = new[] { OffsetDateTimeSchemaType, calendarRestriction, zoneRestriction, zoneIds }, }; NodaTimeXmlSchema = CreateNodaTimeXmlSchema(); } private static readonly XmlSchemaType AnnualDateSchemaType; private static readonly XmlSchemaType DurationSchemaType; private static readonly XmlSchemaType InstantSchemaType; private static readonly XmlSchemaType IntervalSchemaType; private static readonly XmlSchemaType LocalDateSchemaType; private static readonly XmlSchemaType LocalDateTimeSchemaType; private static readonly XmlSchemaType LocalTimeSchemaType; private static readonly XmlSchemaType OffsetSchemaType; private static readonly XmlSchemaType OffsetDateSchemaType; private static readonly XmlSchemaType OffsetDateTimeSchemaType; private static readonly XmlSchemaType OffsetTimeSchemaType; private static readonly XmlSchemaType PeriodBuilderSchemaType; private static readonly XmlSchemaType YearMonthSchemaType; private static readonly XmlSchemaType ZonedDateTimeSchemaType; private static readonly Dictionary<XmlSchemaType, IEnumerable<XmlSchemaType>> DependentSchemaTypes; private static XmlQualifiedName AddSchemaType(this XmlSchemaSet schemaSet, XmlSchemaType schemaType) { var schema = new XmlSchema { TargetNamespace = NodaTimeXmlNamespace.Namespace, Items = { schemaType } }; if (DependentSchemaTypes.TryGetValue(schemaType, out var dependentSchemaTypes)) { foreach (var dependentSchemaType in dependentSchemaTypes) { schema.Items.Add(dependentSchemaType); } } schemaSet.Add(schema); return schemaType.QualifiedName; } private static XmlSchema CreateNodaTimeXmlSchema() { var schemaSetForCollecting = new XmlSchemaSet(); var addSchemaMethods = new Func<XmlSchemaSet, XmlQualifiedName>[] { AnnualDate.AddSchema, Duration.AddSchema, Instant.AddSchema, Interval.AddSchema, LocalDate.AddSchema, LocalDateTime.AddSchema, LocalTime.AddSchema, Offset.AddSchema, OffsetDate.AddSchema, OffsetDateTime.AddSchema, OffsetTime.AddSchema, PeriodBuilder.AddSchema, YearMonth.AddSchema, ZonedDateTime.AddSchema }; foreach (var addSchemaMethod in addSchemaMethods) { addSchemaMethod(schemaSetForCollecting); } var xmlSchema = new XmlSchema { TargetNamespace = NodaTimeXmlNamespace.Namespace, Namespaces = new XmlSerializerNamespaces(new[] { NodaTimeXmlNamespace }) }; var schemaTypes = schemaSetForCollecting.Schemas().Cast<XmlSchema>().SelectMany(e => e.Items.OfType<XmlSchemaType>()); foreach (var schemaType in schemaTypes.OrderBy(e => e.Name, StringComparer.Ordinal)) { var schemaContainsType = xmlSchema.Items.OfType<XmlSchemaType>().Select(e => e.QualifiedName).Contains(schemaType.QualifiedName); if (!schemaContainsType) { xmlSchema.Items.Add(schemaType); } } var schemaSetForCompiling = new XmlSchemaSet(); schemaSetForCompiling.Add(xmlSchema); schemaSetForCompiling.Compile(); return xmlSchema; } // See https://stackoverflow.com/questions/626319/add-attributes-to-a-simpletype-or-restriction-to-a-complextype-in-xml-schema/626385#626385 private static XmlSchemaComplexType CreateSchemaTypeWithAttributes<T>(XmlSchemaType baseType, params XmlSchemaAttribute[] attributes) where T : IXmlSerializable { var content = new XmlSchemaSimpleContentExtension { BaseTypeName = baseType.QualifiedName }; foreach (var attribute in attributes) { content.Attributes.Add(attribute); } return new XmlSchemaComplexType { Name = typeof(T).Name, ContentModel = new XmlSchemaSimpleContent { Content = content } }; } private static XmlSchemaSimpleType CreatePatternRestriction<T>(XmlSchemaType baseType, string pattern) where T : IXmlSerializable => CreatePatternRestriction(typeof(T).Name, baseType, pattern); private static XmlSchemaSimpleType CreatePatternRestriction(string name, XmlSchemaType baseType, string pattern) => QualifySchemaType(new XmlSchemaSimpleType { Name = name, Content = new XmlSchemaSimpleTypeRestriction { BaseTypeName = baseType.QualifiedName, Facets = { new XmlSchemaPatternFacet { Value = pattern } } } }); private static XmlSchemaType CreateEnumerationRestriction(string name, XmlSchemaType baseType, IEnumerable<string> values) { var restriction = new XmlSchemaSimpleTypeRestriction { BaseTypeName = baseType.QualifiedName }; foreach (var value in values.OrderBy(e => e, StringComparer.OrdinalIgnoreCase)) { restriction.Facets.Add(new XmlSchemaEnumerationFacet { Value = value }); } return QualifySchemaType(new XmlSchemaSimpleType { Name = name, Content = restriction }); } /// <summary> /// Sets the <see cref="XmlSchemaType.QualifiedName"/> of the given <paramref name="schemaType"/> /// to belong to <see cref="NodaTimeXmlNamespace"/>. /// </summary> /// <remarks> /// Going through an <see cref="XmlSchema"/> and an <see cref="XmlSchemaSet"/> is a bit convoluted but /// <c>XmlSchemaType.SetQualifiedName()</c> is internal. /// </remarks> /// <param name="schemaType">The schema type to qualify.</param> /// <typeparam name="T">The type of the <see cref="XmlSchemaType"/></typeparam> /// <returns>The qualified <paramref name="schemaType"/>.</returns> private static T QualifySchemaType<T>(T schemaType) where T : XmlSchemaType { var schema = new XmlSchema { TargetNamespace = NodaTimeXmlNamespace.Namespace, Items = { schemaType } }; var xmlSchemaSet = new XmlSchemaSet(); xmlSchemaSet.Add(schema); return schemaType; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Linq.Tests { public class RangeTests : EnumerableTests { [Fact] public void Range_ProduceCorrectSequence() { var rangeSequence = Enumerable.Range(1, 100); int expected = 0; foreach (var val in rangeSequence) { expected++; Assert.Equal(expected, val); } Assert.Equal(100, expected); } [Fact] public void Range_ToArray_ProduceCorrectResult() { var array = Enumerable.Range(1, 100).ToArray(); Assert.Equal(array.Length, 100); for (var i = 0; i < array.Length; i++) Assert.Equal(i + 1, array[i]); } [Fact] public void Range_ToList_ProduceCorrectResult() { var list = Enumerable.Range(1, 100).ToList(); Assert.Equal(list.Count, 100); for (var i = 0; i < list.Count; i++) Assert.Equal(i + 1, list[i]); } [Fact] public void Range_ZeroCountLeadToEmptySequence() { var array = Enumerable.Range(1, 0).ToArray(); var array2 = Enumerable.Range(int.MinValue, 0).ToArray(); var array3 = Enumerable.Range(int.MaxValue, 0).ToArray(); Assert.Equal(array.Length, 0); Assert.Equal(array2.Length, 0); Assert.Equal(array3.Length, 0); } [Fact] public void Range_ThrowExceptionOnNegativeCount() { AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Range(1, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Range(1, int.MinValue)); } [Fact] public void Range_ThrowExceptionOnOverflow() { AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Range(1000, int.MaxValue)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Range(int.MaxValue, 1000)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Range(Int32.MaxValue - 10, 20)); } [Fact] public void Range_NotEnumerateAfterEnd() { using (var rangeEnum = Enumerable.Range(1, 1).GetEnumerator()) { Assert.True(rangeEnum.MoveNext()); Assert.False(rangeEnum.MoveNext()); Assert.False(rangeEnum.MoveNext()); } } [Fact] public void Range_EnumerableAndEnumeratorAreSame() { var rangeEnumerable = Enumerable.Range(1, 1); using (var rangeEnumerator = rangeEnumerable.GetEnumerator()) { Assert.Same(rangeEnumerable, rangeEnumerator); } } [Fact] public void Range_GetEnumeratorReturnUniqueInstances() { var rangeEnumerable = Enumerable.Range(1, 1); using (var enum1 = rangeEnumerable.GetEnumerator()) using (var enum2 = rangeEnumerable.GetEnumerator()) { Assert.NotSame(enum1, enum2); } } [Fact] public void Range_ToInt32MaxValue() { int from = Int32.MaxValue - 3; int count = 4; var rangeEnumerable = Enumerable.Range(from, count); Assert.Equal(count, rangeEnumerable.Count()); int[] expected = { Int32.MaxValue - 3, Int32.MaxValue - 2, Int32.MaxValue - 1, Int32.MaxValue }; Assert.Equal(expected, rangeEnumerable); } [Fact] public void RepeatedCallsSameResults() { Assert.Equal(Enumerable.Range(-1, 2), Enumerable.Range(-1, 2)); Assert.Equal(Enumerable.Range(0, 0), Enumerable.Range(0, 0)); } [Fact] public void NegativeStart() { int start = -5; int count = 1; int[] expected = { -5 }; Assert.Equal(expected, Enumerable.Range(start, count)); } [Fact] public void ArbitraryStart() { int start = 12; int count = 6; int[] expected = { 12, 13, 14, 15, 16, 17 }; Assert.Equal(expected, Enumerable.Range(start, count)); } [Fact] public void Take() { Assert.Equal(Enumerable.Range(0, 10), Enumerable.Range(0, 20).Take(10)); } [Fact] public void TakeExcessive() { Assert.Equal(Enumerable.Range(0, 10), Enumerable.Range(0, 10).Take(int.MaxValue)); } [Fact] public void Skip() { Assert.Equal(Enumerable.Range(10, 10), Enumerable.Range(0, 20).Skip(10)); } [Fact] public void SkipExcessive() { Assert.Empty(Enumerable.Range(10, 10).Skip(20)); } [Fact] public void SkipTakeCanOnlyBeOne() { Assert.Equal(new[] { 1 }, Enumerable.Range(1, 10).Take(1)); Assert.Equal(new[] { 2 }, Enumerable.Range(1, 10).Skip(1).Take(1)); Assert.Equal(new[] { 3 }, Enumerable.Range(1, 10).Take(3).Skip(2)); Assert.Equal(new[] { 1 }, Enumerable.Range(1, 10).Take(3).Take(1)); } [Fact] public void ElementAt() { Assert.Equal(4, Enumerable.Range(0, 10).ElementAt(4)); } [Fact] public void ElementAtExcessiveThrows() { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Enumerable.Range(0, 10).ElementAt(100)); } [Fact] public void ElementAtOrDefault() { Assert.Equal(4, Enumerable.Range(0, 10).ElementAtOrDefault(4)); } [Fact] public void ElementAtOrDefaultExcessiveIsDefault() { Assert.Equal(0, Enumerable.Range(52, 10).ElementAtOrDefault(100)); } [Fact] public void First() { Assert.Equal(57, Enumerable.Range(57, 1000000000).First()); } [Fact] public void FirstOrDefault() { Assert.Equal(-100, Enumerable.Range(-100, int.MaxValue).FirstOrDefault()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Core optimizes Enumerable.Range().Last(). Without this optimization, this test takes a long time. See https://github.com/dotnet/corefx/pull/2401.")] public void Last() { Assert.Equal(1000000056, Enumerable.Range(57, 1000000000).Last()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Core optimizes Enumerable.Range().LastOrDefault(). Without this optimization, this test takes a long time. See https://github.com/dotnet/corefx/pull/2401.")] public void LastOrDefault() { Assert.Equal(int.MaxValue - 101, Enumerable.Range(-100, int.MaxValue).LastOrDefault()); } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Diagnostics; using System.Reflection; using System.Collections; using System.Collections.Specialized; using System.Runtime.Serialization; using System.Text; using System.Collections.Generic; using ESRI.ArcLogistics.Routing.Json; using System.Globalization; namespace ESRI.ArcLogistics.Routing { /// <summary> /// RestHelper class. /// </summary> internal class RestHelper { #region public methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Builds query string. /// </summary> /// <param name="escape"> /// A boolean value indicating whether parameter names and values must /// be escaped. /// </param> /// <returns>Query string</returns> public static string BuildQueryString(object request, IEnumerable<Type> knownTypes, bool escape) { StringDictionary queryData = _GetQueryParams(request, knownTypes); if (queryData.Count == 0) throw new RouteException(Properties.Messages.Error_InvalidVrpRequest); StringBuilder sb = new StringBuilder(); foreach (DictionaryEntry entry in queryData) { AddQueryParam((string)entry.Key, (string)entry.Value, sb, escape); } return sb.ToString(); } public static void AddQueryParam(string name, string value, StringBuilder sb, bool escape) { if (sb.Length > 0) sb.Append('&'); sb.Append(escape ? Uri.EscapeDataString(name) : name); sb.Append('='); // If value size is small or we don't need to // convert escape symbols - append value to stringbuilder. if (value.Length < URI_ESCAPE_METHOD_INPUT_STRING_MAX_LENGTH || !escape) sb.Append(escape ? Uri.EscapeDataString(value) : value); // If we have big value - covnert each text element separately. else { var textElementEnumerator = StringInfo.GetTextElementEnumerator(value); while(textElementEnumerator.MoveNext()) sb.Append(Uri.EscapeDataString(textElementEnumerator.GetTextElement())); } } #endregion public methods /// <summary> /// Creates RestException object. /// </summary> public static RestException CreateRestException(IFaultInfo faultInfo) { Debug.Assert(faultInfo != null); Debug.Assert(faultInfo.IsFault); RestException ex = null; GPError error = faultInfo.FaultInfo; if (error != null) { ex = new RestException(error.Message, error.Code, error.Details); } else ex = new RestException( Properties.Messages.Error_InvalidArcgisRestResponse); return ex; } /// <summary> /// Validates ArcGIS REST service response. /// </summary> public static void ValidateResponse(object resp) { Debug.Assert(resp != null); IFaultInfo faultInfo = resp as IFaultInfo; Debug.Assert(faultInfo != null); if (faultInfo.IsFault) throw CreateRestException(faultInfo); } #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private static StringDictionary _GetQueryParams(object request, IEnumerable<Type> knownTypes) { StringDictionary dict = new StringDictionary(); _AddPropertyParams(request, dict, knownTypes); _AddFieldParams(request, dict, knownTypes); return dict; } private static void _AddPropertyParams(object obj, StringDictionary dict, IEnumerable<Type> knownTypes) { PropertyInfo[] propInfo = obj.GetType().GetProperties(); foreach (PropertyInfo pi in propInfo) { QueryParameterAttribute queryAttr = null; if (_FindCustomAttr(pi.GetCustomAttributes(false), out queryAttr)) { dict.Add(queryAttr.Name, _ParamValueToString(pi.GetValue(obj, null), knownTypes)); } } } private static void _AddFieldParams(object obj, StringDictionary dict, IEnumerable<Type> knownTypes) { FieldInfo[] info = obj.GetType().GetFields(); foreach (FieldInfo fi in info) { QueryParameterAttribute queryAttr = null; if (_FindCustomAttr(fi.GetCustomAttributes(false), out queryAttr)) { dict.Add(queryAttr.Name, _ParamValueToString(fi.GetValue(obj), knownTypes)); } } } private static string _ParamValueToString(object value, IEnumerable<Type> knownTypes) { string valueStr = ""; // reserve empty string for null values if (value != null) { if (_IsJsonObject(value)) { // serialize JSON object valueStr = JsonSerializeHelper.Serialize(value, knownTypes, true); } else { // serialize non-JSON object valueStr = value.ToString(); } } return valueStr; } private static bool _IsJsonObject(object obj) { return _HasCustomAttr<DataContractAttribute>( obj.GetType().GetCustomAttributes(false)); } private static bool _HasCustomAttr<T>(object[] attrs) { T attr; return _FindCustomAttr(attrs, out attr); } private static bool _FindCustomAttr<T>(object[] attrs, out T resAttr) { resAttr = default(T); bool found = false; foreach (object attr in attrs) { if (attr.GetType() == typeof(T)) { resAttr = (T)attr; found = true; break; } } return found; } #endregion private methods #region private const /// <summary> /// Maximum size of input string for Uri.EscapeUriString method. /// </summary> private const int URI_ESCAPE_METHOD_INPUT_STRING_MAX_LENGTH = 32768; #endregion } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; namespace Aurora.Modules.Sun { public class SunModule : ISunModule { // // Global Constants used to determine where in the sky the sun is // private const double m_SeasonalTilt = 0.03*Math.PI; // A daily shift of approximately 1.7188 degrees private const double m_AverageTilt = -0.25*Math.PI; // A 45 degree tilt private const double m_SunCycle = 2.0D*Math.PI; // A perfect circle measured in radians private const double m_SeasonalCycle = 2.0D*Math.PI; // Ditto private const int TICKS_PER_SECOND = 10000000; private double HorizonShift; // Axis offset to skew day and night private float Magnitude; // Normal tilt private float OrbitalPosition; // Orbital placement at a point in time private ulong PosTime; private Vector3 Position = Vector3.Zero; private double SeasonSpeed; // Rate of change for seasonal effects private double SeasonalOffset; // Seaonal variation of tilt // // Per Region Values // private uint SecondsPerSunCycle; // Length of a virtual day in RW seconds private uint SecondsPerYear; // Length of a virtual year in RW seconds private double SunSpeed; // Rate of passage in radians/second private long TicksToEpoch; // Elapsed time for 1/1/1970 // private double HoursToRadians; // Rate of change for seasonal effects private long TicksUTCOffset; // seconds offset from UTC private Quaternion Tilt = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f); // Calculated every update private double TotalDistanceTravelled; // Distance since beginning of time (in radians) private Vector3 Velocity = Vector3.Zero; private double d_DayTimeSunHourScale = 0.5; // Day/Night hours are equal private double d_day_length = 4; // A VW day is 4 RW hours long private double d_day_night = 0.5; // axis offset: Default Hoizon shift to try and closely match the sun model in LL Viewer private int d_frame_mod = 25; // Every 2 seconds (actually less) private string d_mode = "SL"; private int d_year_length = 60; // There are 60 VW days in a VW year private double m_DayLengthHours; private double m_DayTimeSunHourScale; private double m_HorizonShift; private string m_RegionMode = "SL"; // Used to fix the sun in the sky so it doesn't move based on current time private bool m_SunFixed; private float m_SunFixedHour; private int m_UpdateInterval; private int m_YearLengthDays; // This solves a chick before the egg problem // the local SunFixedHour and SunFixed variables MUST be updated // at least once with the proper Region Settings before we start // updating those region settings in GenSunPos() private IConfigSource m_config; private uint m_frame; // Cached Scene reference private IScene m_scene; private bool m_sunIsReadyToRun; private bool ready; // Current time in elapsed seconds since Jan 1st 1970 private ulong CurrentTime { get { return (ulong) (((DateTime.Now.Ticks) - TicksToEpoch + TicksUTCOffset)/TICKS_PER_SECOND); } } // Time in seconds since UTC to use to calculate sun position. #region ISunModule Members public float GetCurrentTimeAsLindenSunHour() { if (m_SunFixed) { return m_SunFixedHour + 6; } return GetCurrentSunHour() + 6.0f; } public double GetSunParameter(string param) { switch (param.ToLower()) { case "year_length": return m_YearLengthDays; case "day_length": return m_DayLengthHours; case "day_night_offset": return m_HorizonShift; case "day_time_sun_hour_scale": return m_DayTimeSunHourScale; case "update_interval": return m_UpdateInterval; default: throw new Exception("Unknown sun parameter."); } } public void SetSunParameter(string param, double value) { HandleSunConsoleCommand(new[] {param, value.ToString()}); } public float GetCurrentSunHour() { float ticksleftover = CurrentTime%SecondsPerSunCycle; return (24.0f*(ticksleftover/SecondsPerSunCycle)); } #endregion #region IRegion Methods // Called immediately after the module is loaded for a given region // i.e. Immediately after instance creation. public bool IsSharedModule { get { return false; } } public void Initialise(IConfigSource config) { m_frame = 0; m_config = config; } public void AddRegion(IScene scene) { m_scene = scene; // This one enables the ability to type just "sun" without any parameters if (MainConsole.Instance != null) { foreach (KeyValuePair<string, string> kvp in GetParamList()) { MainConsole.Instance.Commands.AddCommand( String.Format("sun {0}", kvp.Key), String.Format("{0} - {1}", kvp.Key, kvp.Value), "", HandleSunConsoleCommand); } } TimeZone local = TimeZone.CurrentTimeZone; TicksUTCOffset = local.GetUtcOffset(local.ToLocalTime(DateTime.Now)).Ticks; //MainConsole.Instance.Debug("[SUN]: localtime offset is " + TicksUTCOffset); // Align ticks with Second Life TicksToEpoch = new DateTime(1970, 1, 1).Ticks; // Just in case they don't have the stanzas try { if (m_config.Configs["Sun"] != null) { // Mode: determines how the sun is handled m_RegionMode = m_config.Configs["Sun"].GetString("mode", d_mode); // Mode: determines how the sun is handled // m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude); // Mode: determines how the sun is handled // m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude); // Year length in days m_YearLengthDays = m_config.Configs["Sun"].GetInt("year_length", d_year_length); // Day length in decimal hours m_DayLengthHours = m_config.Configs["Sun"].GetDouble("day_length", d_day_length); // Horizon shift, this is used to shift the sun's orbit, this affects the day / night ratio // must hard code to ~.5 to match sun position in LL based viewers m_HorizonShift = m_config.Configs["Sun"].GetDouble("day_night_offset", d_day_night); // Scales the sun hours 0...12 vs 12...24, essentially makes daylight hours longer/shorter vs nighttime hours m_DayTimeSunHourScale = m_config.Configs["Sun"].GetDouble("day_time_sun_hour_scale", d_DayTimeSunHourScale); // Update frequency in frames m_UpdateInterval = m_config.Configs["Sun"].GetInt("update_interval", d_frame_mod); } else { m_RegionMode = d_mode; m_YearLengthDays = d_year_length; m_DayLengthHours = d_day_length; m_HorizonShift = d_day_night; m_UpdateInterval = d_frame_mod; m_DayTimeSunHourScale = d_DayTimeSunHourScale; // m_latitude = d_latitude; // m_longitude = d_longitude; } } catch (Exception e) { MainConsole.Instance.Debug("[SUN]: Configuration access failed, using defaults. Reason: " + e.Message); m_RegionMode = d_mode; m_YearLengthDays = d_year_length; m_DayLengthHours = d_day_length; m_HorizonShift = d_day_night; m_UpdateInterval = d_frame_mod; m_DayTimeSunHourScale = d_DayTimeSunHourScale; // m_latitude = d_latitude; // m_longitude = d_longitude; } switch (m_RegionMode) { case "T1": default: case "SL": // Time taken to complete a cycle (day and season) SecondsPerSunCycle = (uint) (m_DayLengthHours*60*60); SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays); // Ration of real-to-virtual time // VWTimeRatio = 24/m_day_length; // Speed of rotation needed to complete a cycle in the // designated period (day and season) SunSpeed = m_SunCycle/SecondsPerSunCycle; SeasonSpeed = m_SeasonalCycle/SecondsPerYear; // Horizon translation HorizonShift = m_HorizonShift; // Z axis translation // HoursToRadians = (SunCycle/24)*VWTimeRatio; // Insert our event handling hooks scene.EventManager.OnFrame += SunUpdate; m_scene.EventManager.OnStartupComplete += EventManager_OnStartupComplete; scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; scene.EventManager.OnEstateToolsSunUpdate += EstateToolsSunUpdate; ready = true; //MainConsole.Instance.Debug("[SUN]: Mode is " + m_RegionMode); //MainConsole.Instance.Debug("[SUN]: Initialization completed. Day is " + SecondsPerSunCycle + " seconds, and year is " + m_YearLengthDays + " days"); //MainConsole.Instance.Debug("[SUN]: Axis offset is " + m_HorizonShift); //MainConsole.Instance.Debug("[SUN]: Percentage of time for daylight " + m_DayTimeSunHourScale); //MainConsole.Instance.Debug("[SUN]: Positional data updated every " + m_UpdateInterval + " frames"); break; } scene.RegisterModuleInterface<ISunModule>(this); } public void RemoveRegion(IScene scene) { } public void RegionLoaded(IScene scene) { } public Type ReplaceableInterface { get { return null; } } public void Close() { ready = false; // Remove our hooks m_scene.EventManager.OnStartupComplete -= EventManager_OnStartupComplete; m_scene.EventManager.OnFrame -= SunUpdate; m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel; m_scene.EventManager.OnEstateToolsSunUpdate -= EstateToolsSunUpdate; } public string Name { get { return "SunModule"; } } public void PostInitialise() { } private void EventManager_OnStartupComplete(IScene scene, List<string> data) { //Get the old sun data if (m_scene.RegionInfo.RegionSettings.UseEstateSun) { m_SunFixedHour = (float) m_scene.RegionInfo.EstateSettings.SunPosition; m_SunFixed = m_scene.RegionInfo.EstateSettings.FixedSun; } else { m_SunFixedHour = (float) m_scene.RegionInfo.RegionSettings.SunPosition; m_SunFixed = m_scene.RegionInfo.RegionSettings.FixedSun; } m_sunIsReadyToRun = true; } #endregion #region EventManager Events public void SunToClient(IClientAPI client) { if (m_RegionMode != "T1") { if (ready) { client.SendSunPos(Position, Velocity, m_SunFixed ? PosTime : CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition); } } } public void SunUpdate() { if (((m_frame++%m_UpdateInterval) != 0) || !ready || m_SunFixed /* || !receivedEstateToolsSunUpdate*/) { return; } GenSunPos(); // Generate shared values once SunUpdateToAllClients(); } /// <summary> /// When an avatar enters the region, it's probably a good idea to send them the current sun info /// </summary> /// <param name = "avatar"></param> /// <param name = "localLandID"></param> /// <param name = "regionID"></param> private void AvatarEnteringParcel(IScenePresence avatar, ILandObject oldParcel) { SunToClient(avatar.ControllingClient); } /// <summary> /// </summary> /// <param name = "regionHandle"></param> /// <param name = "FixedTime">Is the sun's position fixed?</param> /// <param name = "useEstateTime">Use the Region or Estate Sun hour?</param> /// <param name = "FixedSunHour">What hour of the day is the Sun Fixed at?</param> public void EstateToolsSunUpdate(ulong regionHandle, bool FixedSun, bool useEstateTime, float FixedSunHour) { if (m_scene.RegionInfo.RegionHandle == regionHandle) { // Must limit the Sun Hour to 0 ... 24 while (FixedSunHour > 24.0f) FixedSunHour -= 24; while (FixedSunHour < 0) FixedSunHour += 24; m_SunFixedHour = FixedSunHour; m_SunFixed = FixedSun; //MainConsole.Instance.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString()); //MainConsole.Instance.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString()); // Generate shared values GenSunPos(); // When sun settings are updated, we should update all clients with new settings. SunUpdateToAllClients(); //MainConsole.Instance.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString()); } } #endregion /// <summary> /// Calculate the sun's orbital position and its velocity. /// </summary> private void GenSunPos() { if (!m_sunIsReadyToRun) return; //We havn't set up the time for this region yet! // Time in seconds since UTC to use to calculate sun position. PosTime = CurrentTime; if (m_SunFixed) { // SunFixedHour represents the "hour of day" we would like // It's represented in 24hr time, with 0 hour being sun-rise // Because our day length is probably not 24hrs {LL is 6} we need to do a bit of math // Determine the current "day" from current time, so we can use "today" // to determine Seasonal Tilt and what'not // Integer math rounded is on purpose to drop fractional day, determines number // of virtual days since Epoch PosTime = CurrentTime/SecondsPerSunCycle; // Since we want number of seconds since Epoch, multiply back up PosTime *= SecondsPerSunCycle; // Then offset by the current Fixed Sun Hour // Fixed Sun Hour needs to be scaled to reflect the user configured Seconds Per Sun Cycle PosTime += (ulong) ((m_SunFixedHour/24.0)*SecondsPerSunCycle); } else { if (m_DayTimeSunHourScale != 0.5f) { ulong CurDaySeconds = CurrentTime%SecondsPerSunCycle; double CurDayPercentage = (double) CurDaySeconds/SecondsPerSunCycle; ulong DayLightSeconds = (ulong) (m_DayTimeSunHourScale*SecondsPerSunCycle); ulong NightSeconds = SecondsPerSunCycle - DayLightSeconds; PosTime = CurrentTime/SecondsPerSunCycle; PosTime *= SecondsPerSunCycle; if (CurDayPercentage < 0.5) { PosTime += (ulong) ((CurDayPercentage/.5)*DayLightSeconds); } else { PosTime += DayLightSeconds; PosTime += (ulong) (((CurDayPercentage - 0.5)/.5)*NightSeconds); } } } TotalDistanceTravelled = SunSpeed*PosTime; // distance measured in radians OrbitalPosition = (float) (TotalDistanceTravelled%m_SunCycle); // position measured in radians // TotalDistanceTravelled += HoursToRadians-(0.25*Math.PI)*Math.Cos(HoursToRadians)-OrbitalPosition; // OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle); SeasonalOffset = SeasonSpeed*PosTime; // Present season determined as total radians travelled around season cycle Tilt.W = (float) (m_AverageTilt + (m_SeasonalTilt*Math.Sin(SeasonalOffset))); // Calculate seasonal orbital N/S tilt // MainConsole.Instance.Debug("[SUN] Total distance travelled = "+TotalDistanceTravelled+", present position = "+OrbitalPosition+"."); // MainConsole.Instance.Debug("[SUN] Total seasonal progress = "+SeasonalOffset+", present tilt = "+Tilt.W+"."); // The sun rotates about the Z axis Position.X = (float) Math.Cos(-TotalDistanceTravelled); Position.Y = (float) Math.Sin(-TotalDistanceTravelled); Position.Z = 0; // For interest we rotate it slightly about the X access. // Celestial tilt is a value that ranges .025 Position *= Tilt; // Finally we shift the axis so that more of the // circle is above the horizon than below. This // makes the nights shorter than the days. Position = Vector3.Normalize(Position); Position.Z = Position.Z + (float) HorizonShift; Position = Vector3.Normalize(Position); // MainConsole.Instance.Debug("[SUN] Position("+Position.X+","+Position.Y+","+Position.Z+")"); Velocity.X = 0; Velocity.Y = 0; Velocity.Z = (float) SunSpeed; // Correct angular velocity to reflect the seasonal rotation Magnitude = Position.Length(); if (m_SunFixed) { Velocity.X = 0; Velocity.Y = 0; Velocity.Z = 0; } else { Velocity = (Velocity*Tilt)*(1.0f/Magnitude); } m_scene.RegionInfo.RegionSettings.SunVector = Position; m_scene.RegionInfo.RegionSettings.SunPosition = GetCurrentTimeAsLindenSunHour(); } private void SunUpdateToAllClients() { m_scene.ForEachScenePresence(delegate(IScenePresence sp) { if (!sp.IsChildAgent) { SunToClient(sp.ControllingClient); } }); } public void HandleSunConsoleCommand(string[] cmdparams) { if (MainConsole.Instance.ConsoleScene != m_scene) { MainConsole.Instance.InfoFormat("[Sun]: Console Scene is not my scene."); return; } MainConsole.Instance.InfoFormat("[Sun]: Processing command."); foreach (string output in ParseCmdParams(cmdparams)) { MainConsole.Instance.Info("[SUN] " + output); } } private Dictionary<string, string> GetParamList() { Dictionary<string, string> Params = new Dictionary<string, string> { {"year_length", "number of days to a year"}, {"day_length", "number of seconds to a day"}, {"day_night_offset", "induces a horizon shift"}, { "update_interval", "how often to update the sun's position in frames" }, { "day_time_sun_hour_scale", "scales day light vs nite hours to change day/night ratio" } }; return Params; } private List<string> ParseCmdParams(string[] args) { List<string> Output = new List<string>(); if ((args.Length == 1) || (args[1].ToLower() == "help") || (args[1].ToLower() == "list")) { Output.Add("The following parameters can be changed or viewed:"); #if (!ISWIN) foreach (KeyValuePair<string, string> kvp in GetParamList()) { Output.Add(String.Format("{0} - {1}", kvp.Key, kvp.Value)); } #else Output.AddRange(GetParamList().Select(kvp => String.Format("{0} - {1}", kvp.Key, kvp.Value))); #endif return Output; } if (args.Length == 2) { try { double value = GetSunParameter(args[1]); Output.Add(String.Format("Parameter {0} is {1}.", args[1], value.ToString())); } catch (Exception) { Output.Add(String.Format("Unknown parameter {0}.", args[1])); } } else if (args.Length == 3) { float value = 0.0f; if (!float.TryParse(args[2], out value)) { Output.Add(String.Format("The parameter value {0} is not a valid number.", args[2])); } switch (args[1].ToLower()) { case "year_length": m_YearLengthDays = (int) value; break; case "day_length": m_DayLengthHours = value; break; case "day_night_offset": m_HorizonShift = value; break; case "day_time_sun_hour_scale": m_DayTimeSunHourScale = value; break; case "update_interval": m_UpdateInterval = (int) value; break; default: Output.Add(String.Format("Unknown parameter {0}.", args[1])); return Output; } Output.Add(String.Format("Parameter {0} set to {1}.", args[1], value.ToString())); // Generate shared values GenSunPos(); // When sun settings are updated, we should update all clients with new settings. SunUpdateToAllClients(); } return Output; } } }
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; namespace DMPServerReportingReceiver { public delegate void ConnectionCallback(ClientObject client,byte[] messageData); public enum MessageTypes { HEARTBEAT, REPORTING_VERSION_1, REPORTING_VERSION_2, } public class MainClass { //Server socket private static TcpListener serverListener; //State tracking private static int connectedClients = 0; public static List<ClientObject> clients = new List<ClientObject>(); public static Stopwatch programClock = new Stopwatch(); //Server disappears after 60 seconds private const int CONNECTION_TIMEOUT = 30000; //5MB max message size private const int MAX_PAYLOAD_SIZE = 5000 * 1024; //Message handlers private static Dictionary<int, ConnectionCallback> registeredHandlers = new Dictionary<int, ConnectionCallback>(); public static DatabaseConnection databaseConnection = new DatabaseConnection(); public static void Main() { SetErrorCounter(); programClock.Start(); //Register handlers registeredHandlers.Add((int)MessageTypes.HEARTBEAT, MessageHandlers.HandleHeartbeat); registeredHandlers.Add((int)MessageTypes.REPORTING_VERSION_1, MessageHandlers.HandleReportingVersion1); registeredHandlers.Add((int)MessageTypes.REPORTING_VERSION_2, MessageHandlers.HandleReportingVersion2); ReportTee.StartReportTee(); StartServer(); ExpireAllOnlineServers(); while (true) { CheckTimeouts(); Thread.Sleep(500); } } private static void SetErrorCounter() { string errorDirectory = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "errors"); if (!Directory.Exists(errorDirectory)) { Directory.CreateDirectory(errorDirectory); } while (File.Exists(Path.Combine(errorDirectory, MessageHandlers.reportID + ".txt"))) { MessageHandlers.reportID++; } Console.WriteLine("Error pointer set to " + MessageHandlers.reportID); } private static void ConnectClient(ClientObject newClient) { lock (clients) { ReportTee.QueueConnect(newClient); clients.Add(newClient); connectedClients = clients.Count; Console.WriteLine("New connection from " + newClient.address.ToString() + ", connected: " + connectedClients); } } public static void DisconnectClient(ClientObject disconnectClient) { lock (clients) { if (clients.Contains(disconnectClient)) { ReportTee.QueueDisconnect(disconnectClient); clients.Remove(disconnectClient); if (disconnectClient.initialized) { CallServerOffline(disconnectClient.serverHash); } connectedClients = clients.Count; Console.WriteLine("Dropped connection from " + disconnectClient.address.ToString() + ", connected: " + connectedClients); try { if (disconnectClient.clientConnection.Connected) { disconnectClient.clientConnection.GetStream().Close(); disconnectClient.clientConnection.GetStream().Dispose(); disconnectClient.clientConnection.Close(); } } catch { //Don't care. } } } } private static void ExpireAllOnlineServers() { databaseConnection.ExecuteNonReader("CALL gameserverscleanup()"); } private static void CallServerOffline(string hash) { Dictionary<string, object> offlineParams = new Dictionary<string, object>(); offlineParams["@hash"] = hash; string mySql = "CALL gameserveroffline(@hash)"; databaseConnection.ExecuteNonReader(mySql, offlineParams); } public static void DisconnectOtherClientsWithHash(ClientObject ourClient, string hash) { foreach (ClientObject client in clients.ToArray()) { if (client.serverHash == hash && client != ourClient) { Console.WriteLine("Disconnecting duplicate client: " + client.serverHash); DisconnectClient(client); } } } private static void CheckTimeouts() { lock (clients) { foreach (ClientObject client in clients.ToArray()) { if (programClock.ElapsedMilliseconds > (client.lastReceiveTime + CONNECTION_TIMEOUT)) { DisconnectClient(client); } } } } private static void StartServer() { serverListener = new TcpListener(IPAddress.Any, 9001); serverListener.Start(); serverListener.BeginAcceptTcpClient(AcceptCallback, null); Console.WriteLine("Listening for connections!"); } private static void AcceptCallback(IAsyncResult ar) { TcpClient clientConnection = serverListener.EndAcceptTcpClient(ar); try { if (clientConnection.Connected) { SetupNewClient(clientConnection); } } catch (Exception e) { Console.WriteLine("Client failed to connect, error: " + e); } serverListener.BeginAcceptSocket(AcceptCallback, null); } private static void SetupNewClient(TcpClient clientConnection) { //Create a new ClientObject for the reporting client ClientObject newClient = new ClientObject(); newClient.clientConnection = clientConnection; newClient.incomingMessage = new NetworkMessage(); newClient.incomingMessage.data = new byte[8]; newClient.bytesToReceive = 8; newClient.lastReceiveTime = programClock.ElapsedMilliseconds; newClient.address = (IPEndPoint)newClient.clientConnection.Client.RemoteEndPoint; ConnectClient(newClient); try { newClient.clientConnection.GetStream().BeginRead(newClient.incomingMessage.data, newClient.incomingMessage.data.Length - newClient.bytesToReceive, newClient.bytesToReceive, ReceiveCallback, newClient); } catch (Exception e) { Console.WriteLine("Error setting up new client, Exception: " + e); DisconnectClient(newClient); } } private static void ReceiveCallback(IAsyncResult ar) { ClientObject client = (ClientObject)ar.AsyncState; try { int bytesReceived = client.clientConnection.GetStream().EndRead(ar); client.bytesToReceive -= bytesReceived; if (bytesReceived > 0) { client.lastReceiveTime = programClock.ElapsedMilliseconds; } if (client.bytesToReceive == 0) { //We have a header or a payload if (!client.isRecevingPayload) { //We have a header client.incomingMessage.type = BitConverter.ToInt32(client.incomingMessage.data, 0); int messagePayload = BitConverter.ToInt32(client.incomingMessage.data, 4); if (messagePayload > MAX_PAYLOAD_SIZE || MAX_PAYLOAD_SIZE < 0) { Console.WriteLine("Invalid TCP message. Disconnecting client."); DisconnectClient(client); return; } if (messagePayload == 0) { client.incomingMessage.data = null; HandleMessage(client, client.incomingMessage); client.incomingMessage = new NetworkMessage(); client.incomingMessage.data = new byte[8]; client.bytesToReceive = 8; } else { client.isRecevingPayload = true; client.incomingMessage.data = new byte[messagePayload]; client.bytesToReceive = messagePayload; } } else { //We have a payload HandleMessage(client, client.incomingMessage); client.isRecevingPayload = false; client.incomingMessage = new NetworkMessage(); client.incomingMessage.data = new byte[8]; client.bytesToReceive = 8; } } client.clientConnection.GetStream().BeginRead(client.incomingMessage.data, client.incomingMessage.data.Length - client.bytesToReceive, client.bytesToReceive, ReceiveCallback, client); } catch (Exception e) { Console.WriteLine("Error reading data, Exception: " + e); DisconnectClient(client); } } private static void HandleMessage(ClientObject client, NetworkMessage receivedMessage) { if (registeredHandlers.ContainsKey(receivedMessage.type)) { try { registeredHandlers[receivedMessage.type](client, receivedMessage.data); } catch (Exception e) { Console.WriteLine("Error processing type " + receivedMessage.type + ", Exception :" + e); } } } } }
/* * AwaitingQueue.cs * * This class is copied directly into the react-native-sqlite-storage repo * for now. When this gets checked into react-native-windows, we can remove * this file and start depending on that RNW's copy. * * Serializes the work of all Tasks that are added to its queue. Awaits the * Task returned by the current work item before moving on to the next work * item. * * This class is not thread-safe. All methods should be called from the same thread * or LimitedConcurrencyActionQueue. `await` must cause the continuation to run on * the same thread or LimitedConcurrencyActionQueue. * * Motivation: * When you `await` a Task, you have to consider all of the things that could have * changed by the time your continuation runs. For example: * * class Recorder * { * private MediaCapture _captureMedia; * * public async Task StartRecording() * { * _captureMedia = new MediaCapture(); * await _captureMedia.InitializeAsync(); * // Lots of things could have changed by the time we get here. * // For example, maybe `_captureMedia` is null! * await _captureMedia.StartRecordToStreamAsync(...); * } * * public async Task StopRecording() * { * // This code can run while `StartRecording` is in the middle * // of running. * * if (_captureMedia != null) * { * // Code to clean up _captureMedia... * _captureMedia = null; * } * } * } * * Alternatively, you can use `AwaitingQueue` to serialize async work that * interacts with each other to prevent any interleavings. Example: * * class Recorder * { * private AwaitingQueue _awaitingQueue = new AwaitingQueue(); * private MediaCapture _captureMedia; * * public async Task StartRecording() * { * _awaitingQueue.RunOrDispatch(async () => * { * // This code won't run until all of the other Tasks * // that were added to the `_awaitingQueue` before us * // have already completed. * * _captureMedia = new MediaCapture(); * await _captureMedia.InitializeAsync(captureInitSettings); * // We can think of `StartRecording` as being atomic which * // means we don't have to worry about anything we care about * // changing by the time we get here. For example, `_captureMedia` * // is guaranteed to be non-null by design. * await _captureMedia.StartRecordToStreamAsync(...); * }); * } * * public async Task StopRecording() * { * _awaitingQueue.RunOrDispatch(() => * { * // This code won't run until all of the other Tasks * // that were added to the `_awaitingQueue` before us * // have already completed. This means this code can't * // run while `StartRecording` is in the middle of running. * * if (_captureMedia != null) * { * // Code to clean up _captureMedia... * _captureMedia = null; * } * }); * } * } */ using System; using System.Collections.Generic; using System.Reactive; using System.Threading; using System.Threading.Tasks; namespace Org.PGSQLite.SQLitePlugin { /// <summary> /// Serializes the work of all Tasks that are added to its queue. Awaits the /// Task returned by the current work item before moving on to the next work /// item. /// </summary> /// <remarks> /// This class is not thread-safe. All methods should be called from the same thread /// or LimitedConcurrencyActionQueue. `await` must cause the continuation to run on /// the same thread or LimitedConcurrencyActionQueue. /// </remarks> /// <typeparam name="T">The type of value yielded by each Task in the queue.</typeparam> public class AwaitingQueue<T> { private const string _tag = nameof(AwaitingQueue); private class WorkItemInfo { public readonly Func<Task<T>> WorkItem; public readonly TaskCompletionSource<T> CompletionSource; public readonly CancellationToken CancellationToken; public WorkItemInfo(Func<Task<T>> workItem, TaskCompletionSource<T> completionSource, CancellationToken cancellationToken) { WorkItem = workItem; CompletionSource = completionSource; CancellationToken = cancellationToken; } } private bool _running = false; private readonly Queue<WorkItemInfo> _workQueue = new Queue<WorkItemInfo>(); private async void StartWorkLoopIfNeeded() { if (_running) { return; } try { _running = true; while (_workQueue.Count > 0) { var workItemInfo = _workQueue.Dequeue(); if (workItemInfo.CancellationToken.IsCancellationRequested) { workItemInfo.CompletionSource.SetCanceled(); } else { //RnLog.Info($"UI AwaitingQueue: Start {currentName}"); try { var result = await workItemInfo.WorkItem(); workItemInfo.CompletionSource.SetResult(result); } catch (Exception ex) { workItemInfo.CompletionSource.SetException(ex); } //RnLog.Info($"UI AwaitingQueue: End {currentName}"); } } _running = false; // Ensure _running is updated before firing the event QueueEmptied?.Invoke(this, null); } finally { // Before exiting this method, ensure _running is updated _running = false; } } /// <summary> /// Adds `workItem` to the queue. If the queue is currently empty and not /// executing any work items, executes `workItem` immediately and synchronously. /// </summary> /// <param name="workItem">The work item to add to the queue.</param> /// <returns> /// A Task which completes when `workItem` finishes executing. The returned /// Task resolves to the result or exception from `workItem`. /// </returns> public Task<T> RunOrQueue(Func<Task<T>> workItem) { return RunOrQueue(workItem, CancellationToken.None); } /// <summary> /// Adds `workItem` to the queue. If the queue is currently empty and not /// executing any work items, executes `workItem` immediately and synchronously. /// </summary> /// <param name="workItem">The work item to add to the queue.</param> /// <param name="cancellationToken"> /// The cancellation token associated with the work item. The work item will /// be skipped if the cancellation token is canceled before the work item begins. /// </param> /// <returns> /// A Task which completes when `workItem` finishes executing. The returned /// Task resolves to the result or exception from `workItem`. If the /// cancellation token is canceled before `workItem` begins, Task is canceled. /// </returns> public Task<T> RunOrQueue(Func<Task<T>> workItem, CancellationToken cancellationToken) { //RnLog.Info($"UI AwaitingQueue: Add {name}"); TaskCompletionSource<T> completionSource = new TaskCompletionSource<T>(); _workQueue.Enqueue(new WorkItemInfo(workItem, completionSource, cancellationToken)); StartWorkLoopIfNeeded(); return completionSource.Task; } /// <summary> /// Indicates that the AwaitingQueue has finished executing all of its /// currently scheduled work items. /// </summary> /// <remarks> /// Fires on the thread or LimitedConcurrencyActionQueue of the code that /// has been conusming the AwaitingQueue. /// </remarks> public event EventHandler QueueEmptied; } /// <summary> /// Serializes the work of all Tasks that are added to its queue. Awaits the /// Task returned by the current work item before moving on to the next work /// item. /// </summary> /// <remarks> /// This class is not thread-safe. All methods should be called from the same thread /// or LimitedConcurrencyActionQueue. `await` must cause the continuation to run on /// the same thread or LimitedConcurrencyActionQueue. /// </remarks> public class AwaitingQueue { private AwaitingQueue<Unit> _awaitingQueue = new AwaitingQueue<Unit>(); /// <summary> /// Adds `workItem` to the queue. If the queue is currently empty and not /// executing any work items, executes `workItem` immediately and synchronously. /// </summary> /// <param name="workItem">The work item to add to the queue.</param> /// <returns> /// A Task which completes when `workItem` finishes executing. The returned /// Task throws any exceptions that `workItem` may have thrown. /// </returns> public Task RunOrQueue(Func<Task> workItem) { return RunOrQueue(workItem, CancellationToken.None); } /// <summary> /// Adds `workItem` to the queue. If the queue is currently empty and not /// executing any work items, executes `workItem` immediately and synchronously. /// </summary> /// <param name="workItem">The work item to add to the queue.</param> /// <param name="cancellationToken"> /// The cancellation token associated with the work item. The work item will /// be skipped if the cancellation token is canceled before the work item begins. /// </param> /// <returns> /// A Task which completes when `workItem` finishes executing. The returned /// Task throws any exceptions that `workItem` may have thrown. If the /// cancellation token is canceled before `workItem` begins, Task is canceled. /// </returns> public Task RunOrQueue(Func<Task> workItem, CancellationToken cancellationToken) { return _awaitingQueue.RunOrQueue(async () => { await workItem(); return Unit.Default; }, cancellationToken); } /// <summary> /// Indicates that the AwaitingQueue has finished executing all of its /// currently scheduled work items. /// </summary> /// <remarks> /// Fires on the thread or LimitedConcurrencyActionQueue of the code that /// has been conusming the AwaitingQueue. /// </remarks> public event EventHandler QueueEmptied { add { _awaitingQueue.QueueEmptied += value; } remove { _awaitingQueue.QueueEmptied -= value; } } } }
using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using System.Security.AccessControl; using System.Text; using Microsoft.Win32; namespace Cyotek.RegistryComparer { public class RegistrySnapshotBuilder { #region Constants private readonly byte[] _defaultBinaryValue = new byte[0]; private const string _defaultStringValue = null; private const int _defaultWordValue = 0; private const RegistryKeyPermissionCheck _permissions = RegistryKeyPermissionCheck.Default; private const RegistryRights _rights = RegistryRights.EnumerateSubKeys | RegistryRights.QueryValues; private readonly string[] _emptyArray = new string[0]; #endregion #region Methods public RegistrySnapshot TakeSnapshot(string[] keys) { RegistrySnapshot snapshot; snapshot = new RegistrySnapshot(); foreach (string key in keys) { snapshot.Keys.Add(this.TakeSnapshot(key)); } return snapshot; } public RegistryKeySnapshot TakeSnapshot(string key) { int endOfHivePosition; RegistryKey registryKey; endOfHivePosition = key.IndexOf('\\'); if (endOfHivePosition == -1) { registryKey = this.GetHive(key); } else { string hive; hive = key.Substring(0, endOfHivePosition); registryKey = this.GetSubKey(this.GetHive(hive), key.Substring(endOfHivePosition + 1)); } return this.TakeSnapshot(registryKey); } private string EncodeByteArray(byte[] value) { StringBuilder sb; sb = new StringBuilder(); foreach (byte bte in value) { if (sb.Length != 0) { sb.Append(' '); } sb.Append(bte.ToString("x2")); } return sb.ToString(); } private void FillKeys(RegistryKeySnapshot snapshot, RegistryKey key) { if (key.SubKeyCount != 0) { RegistryKeySnapshotCollection children; children = new RegistryKeySnapshotCollection(snapshot); // ReSharper disable once LoopCanBePartlyConvertedToQuery foreach (string name in key.GetSubKeyNames()) { // HACK: Although I thought key names were unique, clearly I was wrong as the scan used to crash on // HKEY_LOCAL_MACHINE\SOFTWARE\Yamaha APO which appears at least twice on my system, although RegEdit // only shows a single copy if (!children.Contains(this.GetShortName(name))) { RegistryKey subKey; subKey = this.GetSubKey(key, name); if (subKey != null) { RegistryKeySnapshot childSnapshot; childSnapshot = this.TakeSnapshot(subKey); children.Add(childSnapshot); } } } snapshot.SubKeys = children; } } private void FillSnapshot(RegistryKeySnapshot snapshot, RegistryKey key) { this.FillKeys(snapshot, key); this.FillValues(snapshot, key); } private void FillValues(RegistryKeySnapshot snapshot, RegistryKey key) { if (key.ValueCount != 0) { RegistryValueSnapshotCollection children; string[] names; children = new RegistryValueSnapshotCollection(snapshot); try { names = key.GetValueNames(); } catch (IOException) { // system error, saw this in latest Windows 10 // when trying to scan HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager\CreativeEventCache\SubscribedContent-314559 names = _emptyArray; } for (int i = 0; i < names.Length; i++) { string name; string value; RegistryValueKind type; object rawValue; name = names[i]; type = key.GetValueKind(name); rawValue = this.GetValue(key, type, name); value = this.TransformRawValue(type, rawValue); children.Add(new RegistryValueSnapshot(name, value, type)); } snapshot.Values = children; } } private object GetDefaultValue(RegistryValueKind type) { object defaultValue; switch (type) { case RegistryValueKind.String: case RegistryValueKind.ExpandString: case RegistryValueKind.MultiString: defaultValue = _defaultStringValue; break; case RegistryValueKind.DWord: case RegistryValueKind.QWord: // ReSharper disable once HeapView.BoxingAllocation defaultValue = _defaultWordValue; break; case RegistryValueKind.Binary: case RegistryValueKind.Unknown: defaultValue = _defaultBinaryValue; break; case RegistryValueKind.None: // GitHub Issue: #1 // Not entirely sure what value I should use in the case of a None, went with a null defaultValue = null; break; default: throw new ArgumentOutOfRangeException(); } return defaultValue; } private RegistryKey GetHive(string hive) { RegistryKey rootHive; switch (hive) { case "HKEY_CLASSES_ROOT": rootHive = Registry.ClassesRoot; break; case "HKEY_CURRENT_USER": rootHive = Registry.CurrentUser; break; case "HKEY_LOCAL_MACHINE": rootHive = Registry.LocalMachine; break; case "HKEY_USERS": rootHive = Registry.Users; break; case "HKEY_CURRENT_CONFIG": rootHive = Registry.CurrentConfig; break; case "HKEY_PERFORMANCE_DATA": rootHive = Registry.PerformanceData; break; case "HKEY_DYN_DATA": #pragma warning disable CS0618 // Type or member is obsolete rootHive = Registry.DynData; #pragma warning restore CS0618 // Type or member is obsolete break; default: throw new ArgumentException("Invalid hive.", nameof(hive)); } return rootHive; } private string GetShortName(string name) { int pathPosition; pathPosition = name.LastIndexOf('\\'); if (pathPosition != -1) { name = name.Substring(pathPosition + 1); } return name; } private RegistryKey GetSubKey(RegistryKey key, string name) { RegistryKey subKey; try { subKey = key.OpenSubKey(name, _permissions, _rights); } catch (SecurityException ex) { Trace.WriteLine($"EXCEPTION: {ex.GetBaseException().Message}"); subKey = null; } return subKey; } private object GetValue(RegistryKey key, RegistryValueKind type, string name) { object value; object defaultValue; defaultValue = this.GetDefaultValue(type); try { value = key.GetValue(name, defaultValue, RegistryValueOptions.DoNotExpandEnvironmentNames); } catch (SecurityException) { value = defaultValue; } catch (UnauthorizedAccessException) { value = defaultValue; } return value; } private RegistryKeySnapshot TakeSnapshot(RegistryKey key) { RegistryKeySnapshot snapshot; string name; Trace.WriteLine($"Scanning: {key.Name}"); name = this.GetShortName(key.Name); snapshot = new RegistryKeySnapshot(name); this.FillSnapshot(snapshot, key); return snapshot; } private string TransformRawValue(RegistryValueKind type, object rawValue) { string value; switch (type) { case RegistryValueKind.String: case RegistryValueKind.ExpandString: value = (string)rawValue; break; case RegistryValueKind.MultiString: value = string.Join("\n", (string[])rawValue); break; case RegistryValueKind.DWord: case RegistryValueKind.QWord: value = Convert.ToInt64(rawValue). ToString(CultureInfo.InvariantCulture); break; default: value = this.EncodeByteArray((byte[])rawValue); break; } return value; } #endregion } }
#region license // Copyright (c) 2007 Ivan Krivyakov (ivan@ikriv.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Neither the name of Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using Xunit; using Rhino.Mocks.Exceptions; namespace Rhino.Mocks.Tests { public class StrictMockTests { public class TestClass : MarshalByRefObject { public TestClass(string unused) { throw new InvalidCastException("Real method should never be called"); } public void Method() { throw new InvalidCastException("Real method should never be called"); } public int MethodReturningInt() { throw new InvalidCastException("Real method should never be called"); } public string MethodReturningString() { throw new InvalidCastException("Real method should never be called"); } public string MethodGettingParameters(int intParam, string stringParam) { throw new InvalidCastException("Real method should never be called"); } public void MethodAcceptingTestClass(TestClass other) { throw new InvalidCastException("Real method should never be called"); } public int GenericMethod<T>(string parameter) { throw new InvalidCastException("Real method should never be called"); } public T GenericMethodReturningGenericType<T>(string parameter) { throw new InvalidCastException("Real method should never be called"); } public T GenericMethodWithGenericParam<T>( T parameter ) { throw new InvalidCastException("Real method should never be called"); } public string StringProperty { get { throw new InvalidCastException("Real method should never be called"); } set { throw new InvalidCastException("Real method should never be called"); } } } public class GenericTestClass<T> : MarshalByRefObject { public int Method(T parameter) { throw new InvalidCastException("Real method should never be called"); } public U GenericMethod<U>(T parameter) { throw new InvalidCastException("Real method should never be called"); } } [Fact] public void CanMockVoidMethod() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); t.Method(); mocks.ReplayAll(); t.Method(); mocks.VerifyAll(); } [Fact] public void ThrowOnUnexpectedVoidMethod() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); mocks.ReplayAll(); Assert.Throws<ExpectationViolationException>( "TestClass.Method(); Expected #0, Actual #1.", () => t.Method()); } [Fact] public void CanMockMethodReturningInt() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); Expect.Call(t.MethodReturningInt()).Return(42); mocks.ReplayAll(); Assert.Equal(42, t.MethodReturningInt()); mocks.VerifyAll(); } [Fact] public void CanMockMethodReturningString() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); Expect.Call(t.MethodReturningString()).Return("foo"); mocks.ReplayAll(); Assert.Equal("foo", t.MethodReturningString()); mocks.VerifyAll(); } [Fact] public void CanMockMethodGettingParameters() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); Expect.Call(t.MethodGettingParameters(42, "foo")).Return("bar"); mocks.ReplayAll(); Assert.Equal("bar", t.MethodGettingParameters(42, "foo")); mocks.VerifyAll(); } [Fact] public void CanRejectIncorrectParameters() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); Expect.Call(t.MethodGettingParameters(42, "foo")).Return("bar"); mocks.ReplayAll(); Assert.Throws<ExpectationViolationException>( "TestClass.MethodGettingParameters(19, \"foo\"); Expected #0, Actual #1.\r\nTestClass.MethodGettingParameters(42, \"foo\"); Expected #1, Actual #0.", () => t.MethodGettingParameters(19, "foo")); } [Fact] public void CanMockPropertyGet() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); Expect.Call(t.StringProperty).Return("foo"); mocks.ReplayAll(); Assert.Equal("foo", t.StringProperty); mocks.VerifyAll(); } [Fact] public void CanMockPropertySet() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); t.StringProperty = "foo"; mocks.ReplayAll(); t.StringProperty = "foo"; mocks.VerifyAll(); } [Fact] public void CanRejectIncorrectPropertySet() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); t.StringProperty = "foo"; mocks.ReplayAll(); Assert.Throws<ExpectationViolationException>( "TestClass.set_StringProperty(\"bar\"); Expected #0, Actual #1.\r\nTestClass.set_StringProperty(\"foo\"); Expected #1, Actual #0.", () => t.StringProperty = "bar"); } [Fact] public void CanMockGenericClass() { MockRepository mocks = new MockRepository(); GenericTestClass<string> t = (GenericTestClass<string>)mocks.StrictMock(typeof(GenericTestClass<string>)); Expect.Call(t.Method("foo")).Return(42); mocks.ReplayAll(); Assert.Equal(42, t.Method("foo")); mocks.VerifyAll(); } [Fact] public void CanMockGenericMethod() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); Expect.Call(t.GenericMethod<string>("foo")).Return(42); mocks.ReplayAll(); Assert.Equal(42, t.GenericMethod<string>("foo")); mocks.VerifyAll(); } [Fact] public void CanMockGenericMethod_WillErrorOnWrongType() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); Expect.Call(t.GenericMethod<string>("foo")).Return(42); mocks.ReplayAll(); Assert.Throws<ExpectationViolationException>( @"TestClass.GenericMethod<System.Int32>(""foo""); Expected #1, Actual #1. TestClass.GenericMethod<System.String>(""foo""); Expected #1, Actual #0.", () => Assert.Equal(42, t.GenericMethod<int>("foo"))); } [Fact] public void CanMockGenericMethodReturningGenericType() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); Expect.Call(t.GenericMethodReturningGenericType<string>("foo")).Return("bar"); mocks.ReplayAll(); Assert.Equal("bar", t.GenericMethodReturningGenericType<string>("foo")); mocks.VerifyAll(); } [Fact] public void CanMockGenericMethodWithGenericParam() { MockRepository mocks = new MockRepository(); TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); Expect.Call(t.GenericMethodWithGenericParam<string>("foo")).Return("bar"); mocks.ReplayAll(); Assert.Equal("bar", t.GenericMethodWithGenericParam("foo")); mocks.VerifyAll(); } [Fact] public void CanMockGenericMethodInGenericClass() { MockRepository mocks = new MockRepository(); GenericTestClass<string> t = mocks.StrictMock<GenericTestClass<string>>(); Expect.Call(t.GenericMethod<int>("foo")).Return(42); mocks.ReplayAll(); Assert.Equal(42, t.GenericMethod<int>("foo")); mocks.VerifyAll(); } [Fact] public void CanMockAppDomain() { MockRepository mocks = new MockRepository(); AppDomain appDomain = mocks.StrictMock<AppDomain>(); Expect.Call(appDomain.BaseDirectory).Return("/home/user/ayende"); mocks.ReplayAll(); Assert.Equal(appDomain.BaseDirectory, "/home/user/ayende" ); mocks.VerifyAll(); } [Fact] public void NotCallingExpectedMethodWillCauseVerificationError() { MockRepository mocks = new MockRepository(); AppDomain appDomain = mocks.StrictMock<AppDomain>(); Expect.Call(appDomain.BaseDirectory).Return("/home/user/ayende"); mocks.ReplayAll(); Assert.Throws<ExpectationViolationException>(@"AppDomain.get_BaseDirectory(); Expected #1, Actual #0.", () => mocks.VerifyAll()); } [Fact] public void CanMockMethodAcceptingTestClass() { MockRepository mocks = new MockRepository(); TestClass t1 = mocks.StrictMock<TestClass>(); TestClass t2 = mocks.StrictMock<TestClass>(); t1.MethodAcceptingTestClass(t2); mocks.ReplayAll(); t1.MethodAcceptingTestClass(t2); mocks.VerifyAll(); } [Fact] // can't use ExpectedException since expected message is dynamic public void CanMockMethodAcceptingTestClass_WillErrorOnWrongParameter() { string t2Text = "@"; string t3Text = "@"; try { MockRepository mocks = new MockRepository(); TestClass t1 = mocks.StrictMock<TestClass>(); TestClass t2 = mocks.StrictMock<TestClass>(); TestClass t3 = mocks.StrictMock<TestClass>(); t2Text = t2.ToString(); t3Text = t3.ToString(); t1.MethodAcceptingTestClass(t2); mocks.ReplayAll(); t1.MethodAcceptingTestClass(t3); mocks.VerifyAll(); Assert.False(true, "Expected ExpectationViolationException"); } catch (ExpectationViolationException ex) { string msg = String.Format("TestClass.MethodAcceptingTestClass({0}); Expected #0, Actual #1.\r\n" + "TestClass.MethodAcceptingTestClass({1}); Expected #1, Actual #0.", t3Text, t2Text); Assert.Equal(msg, ex.Message); } } [Fact] public void StrictMockGetTypeReturnsMockedType() { MockRepository mocks = new MockRepository(); TestClass t = mocks.StrictMock<TestClass>(); Assert.Same(typeof(TestClass), t.GetType()); } [Fact] public void StrictMockGetHashCodeWorks() { MockRepository mocks = new MockRepository(); TestClass t = mocks.StrictMock<TestClass>(); t.GetHashCode(); } [Fact] public void StrictMockToStringReturnsDescription() { MockRepository mocks = new MockRepository(); TestClass t = mocks.StrictMock<TestClass>(); int hashCode = t.GetHashCode(); string toString = t.ToString(); Assert.Equal(String.Format("RemotingMock_{0}<TestClass>", hashCode), toString); } [Fact] public void StrictMockEquality() { MockRepository mocks = new MockRepository(); TestClass t = mocks.StrictMock<TestClass>(); Assert.False(t.Equals(null)); Assert.False(t.Equals(42)); Assert.False(t.Equals("foo")); Assert.True(t.Equals(t)); } } }
// // 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.ObjectModel; using System.IO; using System.Management.Automation; using System.Management.Automation.Provider; using DiscUtils.Registry; namespace DiscUtils.PowerShell.VirtualRegistryProvider { [CmdletProvider("VirtualRegistry", ProviderCapabilities.None)] public sealed class Provider : NavigationCmdletProvider, IDynamicPropertyCmdletProvider { private static readonly string DefaultValueName = "(default)"; #region Drive manipulation protected override PSDriveInfo NewDrive(PSDriveInfo drive) { NewDriveParameters dynParams = DynamicParameters as NewDriveParameters; if (drive == null) { WriteError(new ErrorRecord( new ArgumentNullException(nameof(drive)), "NullDrive", ErrorCategory.InvalidArgument, null)); return null; } if (string.IsNullOrEmpty(drive.Root)) { WriteError(new ErrorRecord( new ArgumentException("drive"), "NoRoot", ErrorCategory.InvalidArgument, drive)); return null; } string[] mountPaths = drive.Root.Split('!'); if (mountPaths.Length < 1 || mountPaths.Length > 2) { WriteError(new ErrorRecord( new ArgumentException("drive"), "InvalidRoot", ErrorCategory.InvalidArgument, drive)); return null; } string filePath = mountPaths[0]; string relPath = mountPaths.Length > 1 ? mountPaths[1] : ""; Stream hiveStream = null; FileAccess access = dynParams.ReadWrite.IsPresent ? FileAccess.ReadWrite : FileAccess.Read; FileShare share = access == FileAccess.Read ? FileShare.Read : FileShare.None; filePath = Utilities.ResolvePsPath(SessionState, filePath); hiveStream = Utilities.OpenPsPath(SessionState, filePath, access, share); if (hiveStream == null) { WriteError(new ErrorRecord( new ArgumentException("drive"), "InvalidRoot", ErrorCategory.InvalidArgument, drive)); return null; } else { return new VirtualRegistryPSDriveInfo(drive, MakePath(Utilities.NormalizePath(filePath + "!"), Utilities.NormalizePath(relPath)), hiveStream); } } protected override object NewDriveDynamicParameters() { return new NewDriveParameters(); } protected override PSDriveInfo RemoveDrive(PSDriveInfo drive) { if (drive == null) { WriteError(new ErrorRecord( new ArgumentNullException(nameof(drive)), "NullDrive", ErrorCategory.InvalidArgument, null)); return null; } VirtualRegistryPSDriveInfo vrDrive = drive as VirtualRegistryPSDriveInfo; if (vrDrive == null) { WriteError(new ErrorRecord( new ArgumentException("invalid type of drive"), "BadDrive", ErrorCategory.InvalidArgument, null)); return null; } vrDrive.Close(); return vrDrive; } #endregion #region Item methods protected override void GetItem(string path) { RegistryKey key = FindItemByPath(path); WriteKey(path, key); } protected override object GetItemDynamicParameters(string path) { return null; } protected override void SetItem(string path, object value) { throw new NotImplementedException(); } protected override bool ItemExists(string path) { return FindItemByPath(path) != null; } protected override bool IsValidPath(string path) { throw new NotImplementedException(); } #endregion #region Container methods protected override void GetChildItems(string path, bool recurse) { RegistryKey key = FindItemByPath(path); foreach (var subKeyName in key.GetSubKeyNames()) { WriteKey(MakePath(path, subKeyName), key.OpenSubKey(subKeyName)); } } protected override void GetChildNames(string path, ReturnContainers returnContainers) { RegistryKey key = FindItemByPath(path); foreach (var subKeyName in key.GetSubKeyNames()) { WriteItemObject(subKeyName, MakePath(path, subKeyName), true); } } protected override bool HasChildItems(string path) { RegistryKey key = FindItemByPath(path); return key.SubKeyCount != 0; } protected override void RemoveItem(string path, bool recurse) { string parentPath = GetParentPath(path, null); RegistryKey parentKey = FindItemByPath(parentPath); if (recurse) { parentKey.DeleteSubKeyTree(GetChildName(path)); } else { parentKey.DeleteSubKey(GetChildName(path)); } } protected override void NewItem(string path, string itemTypeName, object newItemValue) { string parentPath = GetParentPath(path, null); RegistryKey parentKey = FindItemByPath(parentPath); WriteItemObject(parentKey.CreateSubKey(GetChildName(path)), path, true); } protected override void RenameItem(string path, string newName) { throw new NotImplementedException(); } protected override void CopyItem(string path, string copyPath, bool recurse) { throw new NotImplementedException(); } #endregion #region Navigation methods protected override bool IsItemContainer(string path) { return true; } protected override string MakePath(string parent, string child) { return Utilities.NormalizePath(base.MakePath(Utilities.DenormalizePath(parent), Utilities.DenormalizePath(child))); } #endregion #region IPropertyCmdletProvider Members public void ClearProperty(string path, Collection<string> propertyToClear) { PSObject propVal = new PSObject(); bool foundProp = false; RegistryKey key = FindItemByPath(path); foreach (var valueName in key.GetValueNames()) { string propName = valueName; if (string.IsNullOrEmpty(valueName)) { propName = DefaultValueName; } if (IsMatch(propName, propertyToClear)) { RegistryValueType type = key.GetValueType(valueName); object newVal = DefaultRegistryTypeValue(type); key.SetValue(valueName, newVal); propVal.Properties.Add(new PSNoteProperty(propName, newVal)); foundProp = true; } } if (foundProp) { WritePropertyObject(propVal, path); } } public object ClearPropertyDynamicParameters(string path, Collection<string> propertyToClear) { return null; } public void GetProperty(string path, Collection<string> providerSpecificPickList) { PSObject propVal = new PSObject(); bool foundProp = false; RegistryKey key = FindItemByPath(path); foreach(var valueName in key.GetValueNames()) { string propName = valueName; if (string.IsNullOrEmpty(valueName)) { propName = DefaultValueName; } if (IsMatch(propName, providerSpecificPickList)) { propVal.Properties.Add(new PSNoteProperty(propName, key.GetValue(valueName))); foundProp = true; } } if (foundProp) { WritePropertyObject(propVal, path); } } public object GetPropertyDynamicParameters(string path, Collection<string> providerSpecificPickList) { return null; } public void SetProperty(string path, PSObject propertyValue) { PSObject propVal = new PSObject(); RegistryKey key = FindItemByPath(path); if (key == null) { WriteError(new ErrorRecord( new ArgumentException("path"), "NoSuchRegistryKey", ErrorCategory.ObjectNotFound, path)); } foreach (var prop in propertyValue.Properties) { key.SetValue(prop.Name, prop.Value); } } public object SetPropertyDynamicParameters(string path, PSObject propertyValue) { return null; } #endregion #region IDynamicPropertyCmdletProvider Members public void CopyProperty(string sourcePath, string sourceProperty, string destinationPath, string destinationProperty) { throw new NotImplementedException(); } public object CopyPropertyDynamicParameters(string sourcePath, string sourceProperty, string destinationPath, string destinationProperty) { return null; } public void MoveProperty(string sourcePath, string sourceProperty, string destinationPath, string destinationProperty) { throw new NotImplementedException(); } public object MovePropertyDynamicParameters(string sourcePath, string sourceProperty, string destinationPath, string destinationProperty) { return null; } public void NewProperty(string path, string propertyName, string propertyTypeName, object value) { RegistryKey key = FindItemByPath(path); if (key == null) { WriteError(new ErrorRecord( new ArgumentException("path"), "NoSuchRegistryKey", ErrorCategory.ObjectNotFound, path)); } RegistryValueType type; type = RegistryValueType.None; if (!string.IsNullOrEmpty(propertyTypeName)) { try { type = (RegistryValueType)Enum.Parse(typeof(RegistryValueType), propertyTypeName, true); } catch(ArgumentException) { } } if(string.Compare(propertyName, DefaultValueName, StringComparison.OrdinalIgnoreCase) == 0) { propertyName = ""; } key.SetValue(propertyName, value ?? DefaultRegistryTypeValue(type), type); } public object NewPropertyDynamicParameters(string path, string propertyName, string propertyTypeName, object value) { return null; } public void RemoveProperty(string path, string propertyName) { RegistryKey key = FindItemByPath(path); if (key == null) { WriteError(new ErrorRecord( new ArgumentException("path"), "NoSuchRegistryKey", ErrorCategory.ObjectNotFound, path)); } if (string.Compare(propertyName, DefaultValueName, StringComparison.OrdinalIgnoreCase) == 0) { propertyName = ""; } key.DeleteValue(propertyName); } public object RemovePropertyDynamicParameters(string path, string propertyName) { return null; } public void RenameProperty(string path, string sourceProperty, string destinationProperty) { throw new NotImplementedException(); } public object RenamePropertyDynamicParameters(string path, string sourceProperty, string destinationProperty) { return null; } #endregion private VirtualRegistryPSDriveInfo DriveInfo { get { return PSDriveInfo as VirtualRegistryPSDriveInfo; } } private RegistryHive Hive { get { VirtualRegistryPSDriveInfo driveInfo = DriveInfo; return (driveInfo != null) ? driveInfo.Hive : null; } } private RegistryKey FindItemByPath(string path) { string filePath; string relPath; int mountSepIdx = path.IndexOf('!'); if (mountSepIdx < 0) { filePath = path; relPath = ""; } else { filePath = path.Substring(0, mountSepIdx); relPath = path.Substring(mountSepIdx + 1); if (relPath.Length > 0 && relPath[0] == '\\') { relPath = relPath.Substring(1); } } RegistryHive hive = Hive; if (hive == null) { throw new NotImplementedException("Accessing registry hives outside of a mounted drive"); } return hive.Root.OpenSubKey(relPath); } private void WriteKey(string path, RegistryKey key) { if (key == null) { return; } PSObject psObj = PSObject.AsPSObject(key); string[] valueNames = key.GetValueNames(); for (int i = 0; i < valueNames.Length; ++i) { if (string.IsNullOrEmpty(valueNames[i])) { valueNames[i] = DefaultValueName; } } psObj.Properties.Add(new PSNoteProperty("Property", valueNames)); WriteItemObject(psObj, path.Trim('\\'), true); } private bool IsMatch(string valueName, Collection<string> filters) { if (filters == null || filters.Count == 0) { return true; } foreach (var filter in filters) { if (WildcardPattern.ContainsWildcardCharacters(filter)) { if (new WildcardPattern(filter, WildcardOptions.IgnoreCase).IsMatch(valueName)) { return true; } } else if (string.Compare(filter, valueName, StringComparison.OrdinalIgnoreCase) == 0) { return true; } } return false; } private static object DefaultRegistryTypeValue(RegistryValueType type) { switch (type) { case RegistryValueType.Binary: case RegistryValueType.None: return new byte[] { }; case RegistryValueType.Dword: case RegistryValueType.DwordBigEndian: return 0; case RegistryValueType.QWord: return 0L; case RegistryValueType.String: case RegistryValueType.ExpandString: return ""; case RegistryValueType.MultiString: return new string[] { }; } 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. /****************************************************************************** * 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 AndNotInt64() { var test = new SimpleBinaryOpTest__AndNotInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndNotInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int64> _fld1; public Vector128<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndNotInt64 testClass) { var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotInt64 testClass) { fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int64*)(pFld1)), Sse2.LoadVector128((Int64*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndNotInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public SimpleBinaryOpTest__AndNotInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.AndNot( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.AndNot( Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.AndNot( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int64>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar2 = &_clsVar2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int64*)(pClsVar1)), Sse2.LoadVector128((Int64*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndNotInt64(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndNotInt64(); fixed (Vector128<Int64>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int64*)(pFld1)), Sse2.LoadVector128((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int64*)(pFld1)), Sse2.LoadVector128((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.AndNot( Sse2.LoadVector128((Int64*)(&test._fld1)), Sse2.LoadVector128((Int64*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int64> op1, Vector128<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((long)(~left[0] & right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((long)(~left[i] & right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<Int64>(Vector128<Int64>, Vector128<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Globalization; using System.Linq; using Xunit; namespace System.Text.Tests { public class EncodingTest : IClassFixture<CultureSetup> { public EncodingTest(CultureSetup setup) { // Setting up the culture happens externally, and only once, which is what we want. // xUnit will keep track of it, do nothing. } public static IEnumerable<object[]> CodePageInfo() { // The layout is code page, IANA(web) name, and query string. // Query strings may be undocumented, and IANA names will be returned from Encoding objects. // Entries are sorted by code page. yield return new object[] { 37, "ibm037", "ibm037" }; yield return new object[] { 37, "ibm037", "cp037" }; yield return new object[] { 37, "ibm037", "csibm037" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-ca" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-nl" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-us" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-wt" }; yield return new object[] { 437, "ibm437", "ibm437" }; yield return new object[] { 437, "ibm437", "437" }; yield return new object[] { 437, "ibm437", "cp437" }; yield return new object[] { 437, "ibm437", "cspc8codepage437" }; yield return new object[] { 500, "ibm500", "ibm500" }; yield return new object[] { 500, "ibm500", "cp500" }; yield return new object[] { 500, "ibm500", "csibm500" }; yield return new object[] { 500, "ibm500", "ebcdic-cp-be" }; yield return new object[] { 500, "ibm500", "ebcdic-cp-ch" }; yield return new object[] { 708, "asmo-708", "asmo-708" }; yield return new object[] { 720, "dos-720", "dos-720" }; yield return new object[] { 737, "ibm737", "ibm737" }; yield return new object[] { 775, "ibm775", "ibm775" }; yield return new object[] { 850, "ibm850", "ibm850" }; yield return new object[] { 850, "ibm850", "cp850" }; yield return new object[] { 852, "ibm852", "ibm852" }; yield return new object[] { 852, "ibm852", "cp852" }; yield return new object[] { 855, "ibm855", "ibm855" }; yield return new object[] { 855, "ibm855", "cp855" }; yield return new object[] { 857, "ibm857", "ibm857" }; yield return new object[] { 857, "ibm857", "cp857" }; yield return new object[] { 858, "ibm00858", "ibm00858" }; yield return new object[] { 858, "ibm00858", "ccsid00858" }; yield return new object[] { 858, "ibm00858", "cp00858" }; yield return new object[] { 858, "ibm00858", "cp858" }; yield return new object[] { 858, "ibm00858", "pc-multilingual-850+euro" }; yield return new object[] { 860, "ibm860", "ibm860" }; yield return new object[] { 860, "ibm860", "cp860" }; yield return new object[] { 861, "ibm861", "ibm861" }; yield return new object[] { 861, "ibm861", "cp861" }; yield return new object[] { 862, "dos-862", "dos-862" }; yield return new object[] { 862, "dos-862", "cp862" }; yield return new object[] { 862, "dos-862", "ibm862" }; yield return new object[] { 863, "ibm863", "ibm863" }; yield return new object[] { 863, "ibm863", "cp863" }; yield return new object[] { 864, "ibm864", "ibm864" }; yield return new object[] { 864, "ibm864", "cp864" }; yield return new object[] { 865, "ibm865", "ibm865" }; yield return new object[] { 865, "ibm865", "cp865" }; yield return new object[] { 866, "cp866", "cp866" }; yield return new object[] { 866, "cp866", "ibm866" }; yield return new object[] { 869, "ibm869", "ibm869" }; yield return new object[] { 869, "ibm869", "cp869" }; yield return new object[] { 870, "ibm870", "ibm870" }; yield return new object[] { 870, "ibm870", "cp870" }; yield return new object[] { 870, "ibm870", "csibm870" }; yield return new object[] { 870, "ibm870", "ebcdic-cp-roece" }; yield return new object[] { 870, "ibm870", "ebcdic-cp-yu" }; yield return new object[] { 874, "windows-874", "windows-874" }; yield return new object[] { 874, "windows-874", "dos-874" }; yield return new object[] { 874, "windows-874", "iso-8859-11" }; yield return new object[] { 874, "windows-874", "tis-620" }; yield return new object[] { 875, "cp875", "cp875" }; yield return new object[] { 932, "shift_jis", "shift_jis" }; yield return new object[] { 932, "shift_jis", "csshiftjis" }; yield return new object[] { 932, "shift_jis", "cswindows31j" }; yield return new object[] { 932, "shift_jis", "ms_kanji" }; yield return new object[] { 932, "shift_jis", "shift-jis" }; yield return new object[] { 932, "shift_jis", "sjis" }; yield return new object[] { 932, "shift_jis", "x-ms-cp932" }; yield return new object[] { 932, "shift_jis", "x-sjis" }; yield return new object[] { 936, "gb2312", "gb2312" }; yield return new object[] { 936, "gb2312", "chinese" }; yield return new object[] { 936, "gb2312", "cn-gb" }; yield return new object[] { 936, "gb2312", "csgb2312" }; yield return new object[] { 936, "gb2312", "csgb231280" }; yield return new object[] { 936, "gb2312", "csiso58gb231280" }; yield return new object[] { 936, "gb2312", "gb_2312-80" }; yield return new object[] { 936, "gb2312", "gb231280" }; yield return new object[] { 936, "gb2312", "gb2312-80" }; yield return new object[] { 936, "gb2312", "gbk" }; yield return new object[] { 936, "gb2312", "iso-ir-58" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1987" }; yield return new object[] { 949, "ks_c_5601-1987", "csksc56011987" }; yield return new object[] { 949, "ks_c_5601-1987", "iso-ir-149" }; yield return new object[] { 949, "ks_c_5601-1987", "korean" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601_1987" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1989" }; yield return new object[] { 949, "ks_c_5601-1987", "ksc_5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ksc5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks-c5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks-c-5601" }; yield return new object[] { 950, "big5", "big5" }; yield return new object[] { 950, "big5", "big5-hkscs" }; yield return new object[] { 950, "big5", "cn-big5" }; yield return new object[] { 950, "big5", "csbig5" }; yield return new object[] { 950, "big5", "x-x-big5" }; yield return new object[] { 1026, "ibm1026", "ibm1026" }; yield return new object[] { 1026, "ibm1026", "cp1026" }; yield return new object[] { 1026, "ibm1026", "csibm1026" }; yield return new object[] { 1047, "ibm01047", "ibm01047" }; yield return new object[] { 1140, "ibm01140", "ibm01140" }; yield return new object[] { 1140, "ibm01140", "ccsid01140" }; yield return new object[] { 1140, "ibm01140", "cp01140" }; yield return new object[] { 1140, "ibm01140", "ebcdic-us-37+euro" }; yield return new object[] { 1141, "ibm01141", "ibm01141" }; yield return new object[] { 1141, "ibm01141", "ccsid01141" }; yield return new object[] { 1141, "ibm01141", "cp01141" }; yield return new object[] { 1141, "ibm01141", "ebcdic-de-273+euro" }; yield return new object[] { 1142, "ibm01142", "ibm01142" }; yield return new object[] { 1142, "ibm01142", "ccsid01142" }; yield return new object[] { 1142, "ibm01142", "cp01142" }; yield return new object[] { 1142, "ibm01142", "ebcdic-dk-277+euro" }; yield return new object[] { 1142, "ibm01142", "ebcdic-no-277+euro" }; yield return new object[] { 1143, "ibm01143", "ibm01143" }; yield return new object[] { 1143, "ibm01143", "ccsid01143" }; yield return new object[] { 1143, "ibm01143", "cp01143" }; yield return new object[] { 1143, "ibm01143", "ebcdic-fi-278+euro" }; yield return new object[] { 1143, "ibm01143", "ebcdic-se-278+euro" }; yield return new object[] { 1144, "ibm01144", "ibm01144" }; yield return new object[] { 1144, "ibm01144", "ccsid01144" }; yield return new object[] { 1144, "ibm01144", "cp01144" }; yield return new object[] { 1144, "ibm01144", "ebcdic-it-280+euro" }; yield return new object[] { 1145, "ibm01145", "ibm01145" }; yield return new object[] { 1145, "ibm01145", "ccsid01145" }; yield return new object[] { 1145, "ibm01145", "cp01145" }; yield return new object[] { 1145, "ibm01145", "ebcdic-es-284+euro" }; yield return new object[] { 1146, "ibm01146", "ibm01146" }; yield return new object[] { 1146, "ibm01146", "ccsid01146" }; yield return new object[] { 1146, "ibm01146", "cp01146" }; yield return new object[] { 1146, "ibm01146", "ebcdic-gb-285+euro" }; yield return new object[] { 1147, "ibm01147", "ibm01147" }; yield return new object[] { 1147, "ibm01147", "ccsid01147" }; yield return new object[] { 1147, "ibm01147", "cp01147" }; yield return new object[] { 1147, "ibm01147", "ebcdic-fr-297+euro" }; yield return new object[] { 1148, "ibm01148", "ibm01148" }; yield return new object[] { 1148, "ibm01148", "ccsid01148" }; yield return new object[] { 1148, "ibm01148", "cp01148" }; yield return new object[] { 1148, "ibm01148", "ebcdic-international-500+euro" }; yield return new object[] { 1149, "ibm01149", "ibm01149" }; yield return new object[] { 1149, "ibm01149", "ccsid01149" }; yield return new object[] { 1149, "ibm01149", "cp01149" }; yield return new object[] { 1149, "ibm01149", "ebcdic-is-871+euro" }; yield return new object[] { 1250, "windows-1250", "windows-1250" }; yield return new object[] { 1250, "windows-1250", "x-cp1250" }; yield return new object[] { 1251, "windows-1251", "windows-1251" }; yield return new object[] { 1251, "windows-1251", "x-cp1251" }; yield return new object[] { 1252, "windows-1252", "windows-1252" }; yield return new object[] { 1252, "windows-1252", "x-ansi" }; yield return new object[] { 1253, "windows-1253", "windows-1253" }; yield return new object[] { 1254, "windows-1254", "windows-1254" }; yield return new object[] { 1255, "windows-1255", "windows-1255" }; yield return new object[] { 1256, "windows-1256", "windows-1256" }; yield return new object[] { 1256, "windows-1256", "cp1256" }; yield return new object[] { 1257, "windows-1257", "windows-1257" }; yield return new object[] { 1258, "windows-1258", "windows-1258" }; yield return new object[] { 1361, "johab", "johab" }; yield return new object[] { 10000, "macintosh", "macintosh" }; yield return new object[] { 10001, "x-mac-japanese", "x-mac-japanese" }; yield return new object[] { 10002, "x-mac-chinesetrad", "x-mac-chinesetrad" }; yield return new object[] { 10003, "x-mac-korean", "x-mac-korean" }; yield return new object[] { 10004, "x-mac-arabic", "x-mac-arabic" }; yield return new object[] { 10005, "x-mac-hebrew", "x-mac-hebrew" }; yield return new object[] { 10006, "x-mac-greek", "x-mac-greek" }; yield return new object[] { 10007, "x-mac-cyrillic", "x-mac-cyrillic" }; yield return new object[] { 10008, "x-mac-chinesesimp", "x-mac-chinesesimp" }; yield return new object[] { 10010, "x-mac-romanian", "x-mac-romanian" }; yield return new object[] { 10017, "x-mac-ukrainian", "x-mac-ukrainian" }; yield return new object[] { 10021, "x-mac-thai", "x-mac-thai" }; yield return new object[] { 10029, "x-mac-ce", "x-mac-ce" }; yield return new object[] { 10079, "x-mac-icelandic", "x-mac-icelandic" }; yield return new object[] { 10081, "x-mac-turkish", "x-mac-turkish" }; yield return new object[] { 10082, "x-mac-croatian", "x-mac-croatian" }; yield return new object[] { 20000, "x-chinese-cns", "x-chinese-cns" }; yield return new object[] { 20001, "x-cp20001", "x-cp20001" }; yield return new object[] { 20002, "x-chinese-eten", "x-chinese-eten" }; yield return new object[] { 20003, "x-cp20003", "x-cp20003" }; yield return new object[] { 20004, "x-cp20004", "x-cp20004" }; yield return new object[] { 20005, "x-cp20005", "x-cp20005" }; yield return new object[] { 20105, "x-ia5", "x-ia5" }; yield return new object[] { 20105, "x-ia5", "irv" }; yield return new object[] { 20106, "x-ia5-german", "x-ia5-german" }; yield return new object[] { 20106, "x-ia5-german", "din_66003" }; yield return new object[] { 20106, "x-ia5-german", "german" }; yield return new object[] { 20107, "x-ia5-swedish", "x-ia5-swedish" }; yield return new object[] { 20107, "x-ia5-swedish", "sen_850200_b" }; yield return new object[] { 20107, "x-ia5-swedish", "swedish" }; yield return new object[] { 20108, "x-ia5-norwegian", "x-ia5-norwegian" }; yield return new object[] { 20108, "x-ia5-norwegian", "norwegian" }; yield return new object[] { 20108, "x-ia5-norwegian", "ns_4551-1" }; yield return new object[] { 20261, "x-cp20261", "x-cp20261" }; yield return new object[] { 20269, "x-cp20269", "x-cp20269" }; yield return new object[] { 20273, "ibm273", "ibm273" }; yield return new object[] { 20273, "ibm273", "cp273" }; yield return new object[] { 20273, "ibm273", "csibm273" }; yield return new object[] { 20277, "ibm277", "ibm277" }; yield return new object[] { 20277, "ibm277", "csibm277" }; yield return new object[] { 20277, "ibm277", "ebcdic-cp-dk" }; yield return new object[] { 20277, "ibm277", "ebcdic-cp-no" }; yield return new object[] { 20278, "ibm278", "ibm278" }; yield return new object[] { 20278, "ibm278", "cp278" }; yield return new object[] { 20278, "ibm278", "csibm278" }; yield return new object[] { 20278, "ibm278", "ebcdic-cp-fi" }; yield return new object[] { 20278, "ibm278", "ebcdic-cp-se" }; yield return new object[] { 20280, "ibm280", "ibm280" }; yield return new object[] { 20280, "ibm280", "cp280" }; yield return new object[] { 20280, "ibm280", "csibm280" }; yield return new object[] { 20280, "ibm280", "ebcdic-cp-it" }; yield return new object[] { 20284, "ibm284", "ibm284" }; yield return new object[] { 20284, "ibm284", "cp284" }; yield return new object[] { 20284, "ibm284", "csibm284" }; yield return new object[] { 20284, "ibm284", "ebcdic-cp-es" }; yield return new object[] { 20285, "ibm285", "ibm285" }; yield return new object[] { 20285, "ibm285", "cp285" }; yield return new object[] { 20285, "ibm285", "csibm285" }; yield return new object[] { 20285, "ibm285", "ebcdic-cp-gb" }; yield return new object[] { 20290, "ibm290", "ibm290" }; yield return new object[] { 20290, "ibm290", "cp290" }; yield return new object[] { 20290, "ibm290", "csibm290" }; yield return new object[] { 20290, "ibm290", "ebcdic-jp-kana" }; yield return new object[] { 20297, "ibm297", "ibm297" }; yield return new object[] { 20297, "ibm297", "cp297" }; yield return new object[] { 20297, "ibm297", "csibm297" }; yield return new object[] { 20297, "ibm297", "ebcdic-cp-fr" }; yield return new object[] { 20420, "ibm420", "ibm420" }; yield return new object[] { 20420, "ibm420", "cp420" }; yield return new object[] { 20420, "ibm420", "csibm420" }; yield return new object[] { 20420, "ibm420", "ebcdic-cp-ar1" }; yield return new object[] { 20423, "ibm423", "ibm423" }; yield return new object[] { 20423, "ibm423", "cp423" }; yield return new object[] { 20423, "ibm423", "csibm423" }; yield return new object[] { 20423, "ibm423", "ebcdic-cp-gr" }; yield return new object[] { 20424, "ibm424", "ibm424" }; yield return new object[] { 20424, "ibm424", "cp424" }; yield return new object[] { 20424, "ibm424", "csibm424" }; yield return new object[] { 20424, "ibm424", "ebcdic-cp-he" }; yield return new object[] { 20833, "x-ebcdic-koreanextended", "x-ebcdic-koreanextended" }; yield return new object[] { 20838, "ibm-thai", "ibm-thai" }; yield return new object[] { 20838, "ibm-thai", "csibmthai" }; yield return new object[] { 20866, "koi8-r", "koi8-r" }; yield return new object[] { 20866, "koi8-r", "cskoi8r" }; yield return new object[] { 20866, "koi8-r", "koi" }; yield return new object[] { 20866, "koi8-r", "koi8" }; yield return new object[] { 20866, "koi8-r", "koi8r" }; yield return new object[] { 20871, "ibm871", "ibm871" }; yield return new object[] { 20871, "ibm871", "cp871" }; yield return new object[] { 20871, "ibm871", "csibm871" }; yield return new object[] { 20871, "ibm871", "ebcdic-cp-is" }; yield return new object[] { 20880, "ibm880", "ibm880" }; yield return new object[] { 20880, "ibm880", "cp880" }; yield return new object[] { 20880, "ibm880", "csibm880" }; yield return new object[] { 20880, "ibm880", "ebcdic-cyrillic" }; yield return new object[] { 20905, "ibm905", "ibm905" }; yield return new object[] { 20905, "ibm905", "cp905" }; yield return new object[] { 20905, "ibm905", "csibm905" }; yield return new object[] { 20905, "ibm905", "ebcdic-cp-tr" }; yield return new object[] { 20924, "ibm00924", "ibm00924" }; yield return new object[] { 20924, "ibm00924", "ccsid00924" }; yield return new object[] { 20924, "ibm00924", "cp00924" }; yield return new object[] { 20924, "ibm00924", "ebcdic-latin9--euro" }; yield return new object[] { 20936, "x-cp20936", "x-cp20936" }; yield return new object[] { 20949, "x-cp20949", "x-cp20949" }; yield return new object[] { 21025, "cp1025", "cp1025" }; yield return new object[] { 21866, "koi8-u", "koi8-u" }; yield return new object[] { 21866, "koi8-u", "koi8-ru" }; yield return new object[] { 28592, "iso-8859-2", "iso-8859-2" }; yield return new object[] { 28592, "iso-8859-2", "csisolatin2" }; yield return new object[] { 28592, "iso-8859-2", "iso_8859-2" }; yield return new object[] { 28592, "iso-8859-2", "iso_8859-2:1987" }; yield return new object[] { 28592, "iso-8859-2", "iso8859-2" }; yield return new object[] { 28592, "iso-8859-2", "iso-ir-101" }; yield return new object[] { 28592, "iso-8859-2", "l2" }; yield return new object[] { 28592, "iso-8859-2", "latin2" }; yield return new object[] { 28593, "iso-8859-3", "iso-8859-3" }; yield return new object[] { 28593, "iso-8859-3", "csisolatin3" }; yield return new object[] { 28593, "iso-8859-3", "iso_8859-3" }; yield return new object[] { 28593, "iso-8859-3", "iso_8859-3:1988" }; yield return new object[] { 28593, "iso-8859-3", "iso-ir-109" }; yield return new object[] { 28593, "iso-8859-3", "l3" }; yield return new object[] { 28593, "iso-8859-3", "latin3" }; yield return new object[] { 28594, "iso-8859-4", "iso-8859-4" }; yield return new object[] { 28594, "iso-8859-4", "csisolatin4" }; yield return new object[] { 28594, "iso-8859-4", "iso_8859-4" }; yield return new object[] { 28594, "iso-8859-4", "iso_8859-4:1988" }; yield return new object[] { 28594, "iso-8859-4", "iso-ir-110" }; yield return new object[] { 28594, "iso-8859-4", "l4" }; yield return new object[] { 28594, "iso-8859-4", "latin4" }; yield return new object[] { 28595, "iso-8859-5", "iso-8859-5" }; yield return new object[] { 28595, "iso-8859-5", "csisolatincyrillic" }; yield return new object[] { 28595, "iso-8859-5", "cyrillic" }; yield return new object[] { 28595, "iso-8859-5", "iso_8859-5" }; yield return new object[] { 28595, "iso-8859-5", "iso_8859-5:1988" }; yield return new object[] { 28595, "iso-8859-5", "iso-ir-144" }; yield return new object[] { 28596, "iso-8859-6", "iso-8859-6" }; yield return new object[] { 28596, "iso-8859-6", "arabic" }; yield return new object[] { 28596, "iso-8859-6", "csisolatinarabic" }; yield return new object[] { 28596, "iso-8859-6", "ecma-114" }; yield return new object[] { 28596, "iso-8859-6", "iso_8859-6" }; yield return new object[] { 28596, "iso-8859-6", "iso_8859-6:1987" }; yield return new object[] { 28596, "iso-8859-6", "iso-ir-127" }; yield return new object[] { 28597, "iso-8859-7", "iso-8859-7" }; yield return new object[] { 28597, "iso-8859-7", "csisolatingreek" }; yield return new object[] { 28597, "iso-8859-7", "ecma-118" }; yield return new object[] { 28597, "iso-8859-7", "elot_928" }; yield return new object[] { 28597, "iso-8859-7", "greek" }; yield return new object[] { 28597, "iso-8859-7", "greek8" }; yield return new object[] { 28597, "iso-8859-7", "iso_8859-7" }; yield return new object[] { 28597, "iso-8859-7", "iso_8859-7:1987" }; yield return new object[] { 28597, "iso-8859-7", "iso-ir-126" }; yield return new object[] { 28598, "iso-8859-8", "iso-8859-8" }; yield return new object[] { 28598, "iso-8859-8", "csisolatinhebrew" }; yield return new object[] { 28598, "iso-8859-8", "hebrew" }; yield return new object[] { 28598, "iso-8859-8", "iso_8859-8" }; yield return new object[] { 28598, "iso-8859-8", "iso_8859-8:1988" }; yield return new object[] { 28598, "iso-8859-8", "iso-8859-8 visual" }; yield return new object[] { 28598, "iso-8859-8", "iso-ir-138" }; yield return new object[] { 28598, "iso-8859-8", "logical" }; yield return new object[] { 28598, "iso-8859-8", "visual" }; yield return new object[] { 28599, "iso-8859-9", "iso-8859-9" }; yield return new object[] { 28599, "iso-8859-9", "csisolatin5" }; yield return new object[] { 28599, "iso-8859-9", "iso_8859-9" }; yield return new object[] { 28599, "iso-8859-9", "iso_8859-9:1989" }; yield return new object[] { 28599, "iso-8859-9", "iso-ir-148" }; yield return new object[] { 28599, "iso-8859-9", "l5" }; yield return new object[] { 28599, "iso-8859-9", "latin5" }; yield return new object[] { 28603, "iso-8859-13", "iso-8859-13" }; yield return new object[] { 28605, "iso-8859-15", "iso-8859-15" }; yield return new object[] { 28605, "iso-8859-15", "csisolatin9" }; yield return new object[] { 28605, "iso-8859-15", "iso_8859-15" }; yield return new object[] { 28605, "iso-8859-15", "l9" }; yield return new object[] { 28605, "iso-8859-15", "latin9" }; yield return new object[] { 29001, "x-europa", "x-europa" }; yield return new object[] { 38598, "iso-8859-8-i", "iso-8859-8-i" }; yield return new object[] { 50220, "iso-2022-jp", "iso-2022-jp" }; yield return new object[] { 50221, "csiso2022jp", "csiso2022jp" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr" }; yield return new object[] { 50225, "iso-2022-kr", "csiso2022kr" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7bit" }; yield return new object[] { 50227, "x-cp50227", "x-cp50227" }; yield return new object[] { 50227, "x-cp50227", "cp50227" }; yield return new object[] { 51932, "euc-jp", "euc-jp" }; yield return new object[] { 51932, "euc-jp", "cseucpkdfmtjapanese" }; yield return new object[] { 51932, "euc-jp", "extended_unix_code_packed_format_for_japanese" }; yield return new object[] { 51932, "euc-jp", "iso-2022-jpeuc" }; yield return new object[] { 51932, "euc-jp", "x-euc" }; yield return new object[] { 51932, "euc-jp", "x-euc-jp" }; yield return new object[] { 51936, "euc-cn", "euc-cn" }; yield return new object[] { 51936, "euc-cn", "x-euc-cn" }; yield return new object[] { 51949, "euc-kr", "euc-kr" }; yield return new object[] { 51949, "euc-kr", "cseuckr" }; yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8" }; yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8bit" }; yield return new object[] { 52936, "hz-gb-2312", "hz-gb-2312" }; yield return new object[] { 54936, "gb18030", "gb18030" }; yield return new object[] { 57002, "x-iscii-de", "x-iscii-de" }; yield return new object[] { 57003, "x-iscii-be", "x-iscii-be" }; yield return new object[] { 57004, "x-iscii-ta", "x-iscii-ta" }; yield return new object[] { 57005, "x-iscii-te", "x-iscii-te" }; yield return new object[] { 57006, "x-iscii-as", "x-iscii-as" }; yield return new object[] { 57007, "x-iscii-or", "x-iscii-or" }; yield return new object[] { 57008, "x-iscii-ka", "x-iscii-ka" }; yield return new object[] { 57009, "x-iscii-ma", "x-iscii-ma" }; yield return new object[] { 57010, "x-iscii-gu", "x-iscii-gu" }; yield return new object[] { 57011, "x-iscii-pa", "x-iscii-pa" }; } public static IEnumerable<object[]> SpecificCodepageEncodings() { // Layout is codepage encoding, bytes, and matching unicode string. yield return new object[] { "Windows-1256", new byte[] { 0xC7, 0xE1, 0xE1, 0xE5, 0x20, 0xC7, 0xCD, 0xCF }, "\x0627\x0644\x0644\x0647\x0020\x0627\x062D\x062F" }; yield return new object[] {"Windows-1252", new byte[] { 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF } , "\x00D0\x00D1\x00D2\x00D3\x00D4\x00D5\x00D6\x00D7\x00D8\x00D9\x00DA\x00DB\x00DC\x00DD\x00DE\x00DF"}; yield return new object[] { "GB2312", new byte[] { 0xCD, 0xE2, 0xCD, 0xE3, 0xCD, 0xE4 }, "\x5916\x8C4C\x5F2F" }; yield return new object[] {"GB18030", new byte[] { 0x81, 0x30, 0x89, 0x37, 0x81, 0x30, 0x89, 0x38, 0xA8, 0xA4, 0xA8, 0xA2, 0x81, 0x30, 0x89, 0x39, 0x81, 0x30, 0x8A, 0x30 } , "\x00DE\x00DF\x00E0\x00E1\x00E2\x00E3"}; } public static IEnumerable<object[]> MultibyteCharacterEncodings() { // Layout is the encoding, bytes, and expected result. yield return new object[] { "iso-2022-jp", new byte[] { 0xA, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x0E, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x41, 0x42, 0x0E, 0x25, 0x0F, 0x43 }, new int[] { 0xA, 0x30CA, 0x30CA, 0x30CA, 0x30CA, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x30CA, 0xFF65, 0xFF8A, 0x41, 0x42, 0xFF65, 0x43} }; yield return new object[] { "GB18030", new byte[] { 0x41, 0x42, 0x43, 0x81, 0x40, 0x82, 0x80, 0x81, 0x30, 0x82, 0x31, 0x81, 0x20 }, new int[] { 0x41, 0x42, 0x43, 0x4E02, 0x500B, 0x8B, 0x3F, 0x20 } }; yield return new object[] { "shift_jis", new byte[] { 0x41, 0x42, 0x43, 0x81, 0x42, 0xE0, 0x43, 0x44, 0x45 }, new int[] { 0x41, 0x42, 0x43, 0x3002, 0x6F86, 0x44, 0x45 } }; yield return new object[] { "iso-2022-kr", new byte[] { 0x0E, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E, 0x0F, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E }, new int[] { 0xFFE2, 0xFFE2, 0x21, 0x7E, 0x21, 0x7E } }; yield return new object[] { "hz-gb-2312", new byte[] { 0x7E, 0x42, 0x7E, 0x7E, 0x7E, 0x7B, 0x21, 0x7E, 0x7E, 0x7D, 0x42, 0x42, 0x7E, 0xA, 0x43, 0x43 }, new int[] { 0x7E, 0x42, 0x7E, 0x3013, 0x42, 0x42, 0x43, 0x43, } }; } private static IEnumerable<KeyValuePair<int, string>> CrossplatformDefaultEncodings() { yield return Map(1200, "utf-16"); yield return Map(12000, "utf-32"); yield return Map(20127, "us-ascii"); yield return Map(65000, "utf-7"); yield return Map(65001, "utf-8"); } private static KeyValuePair<int, string> Map(int codePage, string webName) { return new KeyValuePair<int, string>(codePage, webName); } [Fact] [ActiveIssue(846, PlatformID.AnyUnix)] public static void TestDefaultEncodings() { ValidateDefaultEncodings(); foreach (object[] mapping in CodePageInfo()) { Assert.Throws<NotSupportedException>(() => Encoding.GetEncoding((int)mapping[0])); Assert.Throws<ArgumentException>(() => Encoding.GetEncoding((string)mapping[2])); } // Currently the class EncodingInfo isn't present in corefx, so this checks none of the code pages are present. // When it is, comment out this line and remove the previous foreach/assert. // Assert.Equal(CrossplatformDefaultEncodings, Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName))); // The default encoding should be something from the known list. Encoding defaultEncoding = Encoding.GetEncoding(0); Assert.NotNull(defaultEncoding); KeyValuePair<int, string> mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName); Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings()); // Add the code page provider. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Make sure added code pages are identical between the provider and the Encoding class. foreach (object[] mapping in CodePageInfo()) { Encoding encoding = Encoding.GetEncoding((int)mapping[0]); Encoding codePageEncoding = CodePagesEncodingProvider.Instance.GetEncoding((int)mapping[0]); Assert.Equal(encoding, codePageEncoding); Assert.Equal(encoding.CodePage, (int)mapping[0]); Assert.Equal(encoding.WebName, (string)mapping[1]); // Get encoding via query string. Assert.Equal(Encoding.GetEncoding((string)mapping[2]), CodePagesEncodingProvider.Instance.GetEncoding((string)mapping[2])); } // Adding the code page provider should keep the originals, too. ValidateDefaultEncodings(); // Currently the class EncodingInfo isn't present in corefx, so this checks the complete list // When it is, comment out this line and remove the previous foreach/assert. // Assert.Equal(CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])).OrderBy(i => i.Key)), // Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName))); // Default encoding may have changed, should still be something on the combined list. defaultEncoding = Encoding.GetEncoding(0); Assert.NotNull(defaultEncoding); mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName); Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])))); } private static void ValidateDefaultEncodings() { foreach (var mapping in CrossplatformDefaultEncodings()) { Encoding encoding = Encoding.GetEncoding(mapping.Key); Assert.NotNull(encoding); Assert.Equal(encoding, Encoding.GetEncoding(mapping.Value)); Assert.Equal(mapping.Value, encoding.WebName); } } [Theory] [MemberData("SpecificCodepageEncodings")] public static void TestRoundtrippingSpecificCodepageEncoding(string encodingName, byte[] bytes, string expected) { Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(encodingName); string encoded = encoding.GetString(bytes, 0, bytes.Length); Assert.Equal(expected, encoded); Assert.Equal(bytes, encoding.GetBytes(encoded)); byte[] resultBytes = encoding.GetBytes(encoded); } [Theory] [MemberData("CodePageInfo")] public static void TestCodepageEncoding(int codePage, string webName, string queryString) { Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(queryString); Assert.NotNull(encoding); Assert.Equal(codePage, encoding.CodePage); Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(codePage)); Assert.Equal(webName, encoding.WebName); Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName)); // Small round-trip for ASCII alphanumeric range (some code pages use different punctuation!) // Start with space. string asciiPrintable = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; char[] traveled = encoding.GetChars(encoding.GetBytes(asciiPrintable)); Assert.Equal(asciiPrintable.ToCharArray(), traveled); } [Theory] [MemberData("MultibyteCharacterEncodings")] public static void TestSpecificMultibyteCharacterEncodings(string codepageName, byte[] bytes, int[] expected) { Decoder decoder = CodePagesEncodingProvider.Instance.GetEncoding(codepageName).GetDecoder(); char[] buffer = new char[expected.Length]; for (int byteIndex = 0, charIndex = 0, charCount = 0; byteIndex < bytes.Length; byteIndex++, charIndex += charCount) { charCount = decoder.GetChars(bytes, byteIndex, 1, buffer, charIndex); } Assert.Equal(expected, buffer.Select(c => (int)c)); } [Theory] [MemberData("CodePageInfo")] public static void TestEncodingDisplayNames(int codePage, string webName, string queryString) { var encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage); string name = encoding.EncodingName; // Names can't be empty, and must be printable characters. Assert.False(string.IsNullOrWhiteSpace(name)); Assert.All(name, c => Assert.True(c >= ' ' && c < '~' + 1, "Name: " + name + " contains character: " + c)); } } public class CultureSetup : IDisposable { private readonly CultureInfo _originalUICulture; public CultureSetup() { _originalUICulture = CultureInfo.CurrentUICulture; CultureInfo.CurrentUICulture = new CultureInfo("en-US"); } public void Dispose() { CultureInfo.CurrentUICulture = _originalUICulture; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Xunit; namespace System.IO.Tests { public abstract class FileSystemWatcherTest : FileCleanupTestBase { // Events are reported asynchronously by the OS, so allow an amount of time for // them to arrive before testing an assertion. If we expect an event to occur, // we can wait for it for a relatively long time, as if it doesn't arrive, we're // going to fail the test. If we don't expect an event to occur, then we need // to keep the timeout short, as in a successful run we'll end up waiting for // the entire timeout specified. public const int WaitForExpectedEventTimeout = 500; // ms to wait for an event to happen public const int SubsequentExpectedWait = 10; // ms to wait for checks that occur after the first. public const int WaitForExpectedEventTimeout_NoRetry = 3000;// ms to wait for an event that isn't surrounded by a retry. public const int DefaultAttemptsForExpectedEvent = 3; // Number of times an expected event should be retried if failing. public const int DefaultAttemptsForUnExpectedEvent = 2; // Number of times an unexpected event should be retried if failing. /// <summary> /// Watches the Changed WatcherChangeType and unblocks the returned AutoResetEvent when a /// Changed event is thrown by the watcher. /// </summary> public static AutoResetEvent WatchChanged(FileSystemWatcher watcher, string[] expectedPaths = null) { AutoResetEvent eventOccurred = new AutoResetEvent(false); watcher.Changed += (o, e) => { Assert.Equal(WatcherChangeTypes.Changed, e.ChangeType); if (expectedPaths != null) { Assert.Contains(Path.GetFullPath(e.FullPath), expectedPaths); } eventOccurred.Set(); }; return eventOccurred; } /// <summary> /// Watches the Created WatcherChangeType and unblocks the returned AutoResetEvent when a /// Created event is thrown by the watcher. /// </summary> public static AutoResetEvent WatchCreated(FileSystemWatcher watcher, string[] expectedPaths = null) { AutoResetEvent eventOccurred = new AutoResetEvent(false); watcher.Created += (o, e) => { Assert.Equal(WatcherChangeTypes.Created, e.ChangeType); if (expectedPaths != null) { Assert.Contains(Path.GetFullPath(e.FullPath), expectedPaths); } eventOccurred.Set(); }; return eventOccurred; } /// <summary> /// Watches the Renamed WatcherChangeType and unblocks the returned AutoResetEvent when a /// Renamed event is thrown by the watcher. /// </summary> public static AutoResetEvent WatchDeleted(FileSystemWatcher watcher, string[] expectedPaths = null) { AutoResetEvent eventOccurred = new AutoResetEvent(false); watcher.Deleted += (o, e) => { Assert.Equal(WatcherChangeTypes.Deleted, e.ChangeType); if (expectedPaths != null) { Assert.Contains(Path.GetFullPath(e.FullPath), expectedPaths); } eventOccurred.Set(); }; return eventOccurred; } /// <summary> /// Watches the Renamed WatcherChangeType and unblocks the returned AutoResetEvent when a /// Renamed event is thrown by the watcher. /// </summary> public static AutoResetEvent WatchRenamed(FileSystemWatcher watcher, string[] expectedPaths = null) { AutoResetEvent eventOccurred = new AutoResetEvent(false); watcher.Renamed += (o, e) => { Assert.Equal(WatcherChangeTypes.Renamed, e.ChangeType); if (expectedPaths != null) { Assert.Contains(Path.GetFullPath(e.FullPath), expectedPaths); } eventOccurred.Set(); }; return eventOccurred; } /// <summary> /// Asserts that the given handle will be signaled within the default timeout. /// </summary> public static void ExpectEvent(WaitHandle eventOccurred, string eventName_NoRetry) { string message = String.Format("Didn't observe a {0} event within {1}ms", eventName_NoRetry, WaitForExpectedEventTimeout_NoRetry); Assert.True(eventOccurred.WaitOne(WaitForExpectedEventTimeout_NoRetry), message); } /// <summary> /// Does verification that the given watcher will throw exactly/only the events in "expectedEvents" when /// "action" is executed. /// </summary> /// <param name="watcher">The FileSystemWatcher to test</param> /// <param name="expectedEvents">All of the events that are expected to be raised by this action</param> /// <param name="action">The Action that will trigger events.</param> /// <param name="cleanup">Optional. Undoes the action and cleans up the watcher so the test may be run again if necessary.</param> public static void ExpectEvent(FileSystemWatcher watcher, WatcherChangeTypes expectedEvents, Action action, Action cleanup = null) { ExpectEvent(watcher, expectedEvents, action, cleanup, (string[])null); } /// <summary> /// Does verification that the given watcher will throw exactly/only the events in "expectedEvents" when /// "action" is executed. /// </summary> /// <param name="watcher">The FileSystemWatcher to test</param> /// <param name="expectedEvents">All of the events that are expected to be raised by this action</param> /// <param name="action">The Action that will trigger events.</param> /// <param name="cleanup">Optional. Undoes the action and cleans up the watcher so the test may be run again if necessary.</param> /// <param name="expectedPath">Optional. Adds path verification to all expected events.</param> /// <param name="attempts">Optional. Number of times the test should be executed if it's failing.</param> public static void ExpectEvent(FileSystemWatcher watcher, WatcherChangeTypes expectedEvents, Action action, Action cleanup = null, string expectedPath = null, int attempts = DefaultAttemptsForExpectedEvent) { ExpectEvent(watcher, expectedEvents, action, cleanup, expectedPath == null ? null : new string[] { expectedPath }, attempts); } /// <summary> /// Does verification that the given watcher will throw exactly/only the events in "expectedEvents" when /// "action" is executed. /// </summary> /// <param name="watcher">The FileSystemWatcher to test</param> /// <param name="expectedEvents">All of the events that are expected to be raised by this action</param> /// <param name="action">The Action that will trigger events.</param> /// <param name="cleanup">Optional. Undoes the action and cleans up the watcher so the test may be run again if necessary.</param> /// <param name="expectedPath">Optional. Adds path verification to all expected events.</param> /// <param name="attempts">Optional. Number of times the test should be executed if it's failing.</param> public static void ExpectEvent(FileSystemWatcher watcher, WatcherChangeTypes expectedEvents, Action action, Action cleanup = null, string[] expectedPaths = null, int attempts = DefaultAttemptsForExpectedEvent) { int attemptsCompleted = 0; bool result = false; while (!result && attemptsCompleted++ < attempts) { if (attemptsCompleted > 1) { // Re-create the watcher to get a clean iteration. watcher = new FileSystemWatcher() { IncludeSubdirectories = watcher.IncludeSubdirectories, NotifyFilter = watcher.NotifyFilter, Filter = watcher.Filter, Path = watcher.Path, InternalBufferSize = watcher.InternalBufferSize }; // Most intermittent failures in FSW are caused by either a shortage of resources (e.g. inotify instances) // or by insufficient time to execute (e.g. CI gets bogged down). Immediately re-running a failed test // won't resolve the first issue, so we wait a little while hoping that things clear up for the next run. Thread.Sleep(500); } result = ExecuteAndVerifyEvents(watcher, expectedEvents, action, attemptsCompleted == attempts, expectedPaths); if (cleanup != null) cleanup(); } } /// <summary> /// Helper for the ExpectEvent function. /// </summary> /// <param name="watcher">The FileSystemWatcher to test</param> /// <param name="expectedEvents">All of the events that are expected to be raised by this action</param> /// <param name="action">The Action that will trigger events.</param> /// <param name="assertExpected">True if results should be asserted. Used if there is no retry.</param> /// <param name="expectedPath"> Adds path verification to all expected events.</param> /// <returns>True if the events raised correctly; else, false.</returns> private static bool ExecuteAndVerifyEvents(FileSystemWatcher watcher, WatcherChangeTypes expectedEvents, Action action, bool assertExpected, string[] expectedPaths) { bool result = true, verifyChanged = true, verifyCreated = true, verifyDeleted = true, verifyRenamed = true; AutoResetEvent changed = null, created = null, deleted = null, renamed = null; string[] expectedFullPaths = expectedPaths == null ? null : expectedPaths.Select(e => Path.GetFullPath(e)).ToArray(); // On OSX we get a number of extra events tacked onto valid events. As such, we can not ever confidently // say that a event won't occur, only that one will occur. if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { if (verifyChanged = ((expectedEvents & WatcherChangeTypes.Changed) > 0)) changed = WatchChanged(watcher, expectedPaths); if (verifyCreated = ((expectedEvents & WatcherChangeTypes.Created) > 0)) created = WatchCreated(watcher, expectedPaths); if (verifyDeleted = ((expectedEvents & WatcherChangeTypes.Deleted) > 0)) deleted = WatchDeleted(watcher, expectedPaths); if (verifyRenamed = ((expectedEvents & WatcherChangeTypes.Renamed) > 0)) renamed = WatchRenamed(watcher, expectedPaths); } else { changed = WatchChanged(watcher, (expectedEvents & WatcherChangeTypes.Changed) > 0 ? expectedPaths : null); created = WatchCreated(watcher, (expectedEvents & WatcherChangeTypes.Created) > 0 ? expectedPaths : null); deleted = WatchDeleted(watcher, (expectedEvents & WatcherChangeTypes.Deleted) > 0 ? expectedPaths : null); renamed = WatchRenamed(watcher, (expectedEvents & WatcherChangeTypes.Renamed) > 0 ? expectedPaths : null); } watcher.EnableRaisingEvents = true; action(); // Verify Changed if (verifyChanged) { bool Changed_expected = ((expectedEvents & WatcherChangeTypes.Changed) > 0); bool Changed_actual = changed.WaitOne(WaitForExpectedEventTimeout); result = Changed_expected == Changed_actual; if (assertExpected) Assert.True(Changed_expected == Changed_actual, "Changed event did not occur as expected"); } // Verify Created if (verifyCreated) { bool Created_expected = ((expectedEvents & WatcherChangeTypes.Created) > 0); bool Created_actual = created.WaitOne(verifyChanged ? SubsequentExpectedWait : WaitForExpectedEventTimeout); result = result && Created_expected == Created_actual; if (assertExpected) Assert.True(Created_expected == Created_actual, "Created event did not occur as expected"); } // Verify Deleted if (verifyDeleted) { bool Deleted_expected = ((expectedEvents & WatcherChangeTypes.Deleted) > 0); bool Deleted_actual = deleted.WaitOne(verifyChanged || verifyCreated ? SubsequentExpectedWait : WaitForExpectedEventTimeout); result = result && Deleted_expected == Deleted_actual; if (assertExpected) Assert.True(Deleted_expected == Deleted_actual, "Deleted event did not occur as expected"); } // Verify Renamed if (verifyRenamed) { bool Renamed_expected = ((expectedEvents & WatcherChangeTypes.Renamed) > 0); bool Renamed_actual = renamed.WaitOne(verifyChanged || verifyCreated || verifyDeleted? SubsequentExpectedWait : WaitForExpectedEventTimeout); result = result && Renamed_expected == Renamed_actual; if (assertExpected) Assert.True(Renamed_expected == Renamed_actual, "Renamed event did not occur as expected"); } watcher.EnableRaisingEvents = false; return result; } /// <summary> /// Does verification that the given watcher will throw an Error when the given action is executed. /// </summary> /// <param name="watcher">The FileSystemWatcher to test</param> /// <param name="action">The Action that will trigger a failure.</param> /// <param name="cleanup">Undoes the action and cleans up the watcher so the test may be run again if necessary.</param> /// <param name="attempts">Optional. Number of times the test should be executed if it's failing.</param> public static void ExpectError(FileSystemWatcher watcher, Action action, Action cleanup, int attempts = DefaultAttemptsForExpectedEvent) { string message = string.Format("Did not observe an error event within {0}ms and {1} attempts.", WaitForExpectedEventTimeout, attempts); Assert.True(TryErrorEvent(watcher, action, cleanup, attempts, expected: true), message); } /// <summary> /// Does verification that the given watcher will <b>not</b> throw an Error when the given action is executed. /// </summary> /// <param name="watcher">The FileSystemWatcher to test</param> /// <param name="action">The Action that will not trigger a failure.</param> /// <param name="cleanup">Undoes the action and cleans up the watcher so the test may be run again if necessary.</param> /// <param name="attempts">Optional. Number of times the test should be executed if it's failing.</param> public static void ExpectNoError(FileSystemWatcher watcher, Action action, Action cleanup, int attempts = DefaultAttemptsForUnExpectedEvent) { string message = string.Format("Should not observe an error event within {0}ms. Attempted {1} times and received the event each time.", WaitForExpectedEventTimeout, attempts); Assert.False(TryErrorEvent(watcher, action, cleanup, attempts, expected: true), message); } /// /// <summary> /// Helper method for the ExpectError/ExpectNoError functions. /// </summary> /// <param name="watcher">The FileSystemWatcher to test</param> /// <param name="action">The Action to execute.</param> /// <param name="cleanup">Undoes the action and cleans up the watcher so the test may be run again if necessary.</param> /// <param name="attempts">Number of times the test should be executed if it's failing.</param> /// <param name="expected">Whether it is expected that an error event will be arisen.</param> /// <returns>True if an Error event was raised by the watcher when the given action was executed; else, false.</returns> public static bool TryErrorEvent(FileSystemWatcher watcher, Action action, Action cleanup, int attempts, bool expected) { int attemptsCompleted = 0; bool result = !expected; while (result != expected && attemptsCompleted++ < attempts) { if (attemptsCompleted > 1) { // Re-create the watcher to get a clean iteration. watcher = new FileSystemWatcher() { IncludeSubdirectories = watcher.IncludeSubdirectories, NotifyFilter = watcher.NotifyFilter, Filter = watcher.Filter, Path = watcher.Path, InternalBufferSize = watcher.InternalBufferSize }; // Most intermittent failures in FSW are caused by either a shortage of resources (e.g. inotify instances) // or by insufficient time to execute (e.g. CI gets bogged down). Immediately re-running a failed test // won't resolve the first issue, so we wait a little while hoping that things clear up for the next run. Thread.Sleep(500); } AutoResetEvent errorOccured = new AutoResetEvent(false); watcher.Error += (o, e) => { errorOccured.Set(); }; // Enable raising events but be careful with the possibility of the max user inotify instances being reached already. if (attemptsCompleted <= attempts) { try { watcher.EnableRaisingEvents = true; } catch (IOException) // Max User INotify instances. Isn't the type of error we're checking for. { continue; } } else { watcher.EnableRaisingEvents = true; } action(); result = errorOccured.WaitOne(WaitForExpectedEventTimeout); watcher.EnableRaisingEvents = false; cleanup(); } return result; } /// <summary> /// Creates a test symlink to determine if symlinks can be successfully created /// </summary> protected static bool CanCreateSymbolicLinks { get { var path = Path.GetTempFileName(); var linkPath = path + ".link"; var ret = CreateSymLink(path, linkPath, isDirectory: false); ret = ret && File.Exists(linkPath); try { File.Delete(path); } catch { } try { File.Delete(linkPath); } catch { } return ret; } } public static bool CreateSymLink(string targetPath, string linkPath, bool isDirectory) { Process symLinkProcess = new Process(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { symLinkProcess.StartInfo.FileName = "cmd"; symLinkProcess.StartInfo.Arguments = string.Format("/c mklink{0} \"{1}\" \"{2}\"", isDirectory ? " /D" : "", Path.GetFullPath(linkPath), Path.GetFullPath(targetPath)); } else { symLinkProcess.StartInfo.FileName = "ln"; symLinkProcess.StartInfo.Arguments = string.Format("-s \"{0}\" \"{1}\"", Path.GetFullPath(targetPath), Path.GetFullPath(linkPath)); } symLinkProcess.StartInfo.RedirectStandardOutput = true; symLinkProcess.Start(); if (symLinkProcess != null) { symLinkProcess.WaitForExit(); return (0 == symLinkProcess.ExitCode); } else { return false; } } public static IEnumerable<object[]> FilterTypes() { foreach (NotifyFilters filter in Enum.GetValues(typeof(NotifyFilters))) yield return new object[] { filter }; } // Linux and OSX systems have less precise filtering systems than Windows, so most // metadata filters are effectively equivalent to each other on those systems. For example // there isn't a way to filter only LastWrite events on either system; setting // Filters to LastWrite will allow events from attribute change, creation time // change, size change, etc. public const NotifyFilters LinuxFiltersForAttribute = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; public const NotifyFilters LinuxFiltersForModify = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; public const NotifyFilters OSXFiltersForModify = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml.Linq; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class EventsTests : XLinqTestCase { public partial class EventsReplaceWith : EventsBase { protected override void DetermineChildren() { VariationsForXDocument(ExecuteXDocumentVariation); VariationsForXElement(ExecuteXElementVariation); base.DetermineChildren(); } void VariationsForXDocument(TestFunc func) { AddChild(func, 0, "XDocument - empty element, text", new XElement("element"), new XText(" ")); AddChild(func, 0, "XDocument - element with attribtue, text", new XElement("element", new XAttribute("a", "aa")), new XText("")); AddChild(func, 0, "XDocument - element, empty element ", new XElement("parent", new XElement("child", "child text")), new XElement("element")); AddChild(func, 0, "XDocument - document type, comment", new XDocumentType("root", "", "", ""), new XComment("Comment")); AddChild(func, 0, "XDocument - PI, document type", new XProcessingInstruction("PI", "Data"), new XDocumentType("root", "", "", "")); AddChild(func, 0, "XDocument - comment, text", new XComment("Comment"), new XText("\t")); AddChild(func, 0, "XDocument - text node, element", new XText(" "), XElement.Parse(@"<a></a>")); } void VariationsForXElement(TestFunc func) { AddChild(func, 0, "XElement - empty element, text", new XElement("element"), new XText(" ")); AddChild(func, 0, "XElement - element with attribtue, text", new XElement("element", new XAttribute("a", "aa")), new XText("")); AddChild(func, 0, "XElement - element, empty element", new XElement("parent", new XElement("child", "child text")), new XElement("element")); AddChild(func, 0, "XElement - CData, comment", new XCData("x+y >= z-m"), new XComment("Comment")); AddChild(func, 0, "XElement - PI, element with attribute", new XProcessingInstruction("PI", "Data"), new XElement("element", new XAttribute("a", "aa"))); AddChild(func, 0, "XElement - comment, text", new XComment("Comment"), new XText("\t")); AddChild(func, 0, "XElement - text node, element", new XText("\t"), XElement.Parse(@"<a></a>")); } public void ExecuteXDocumentVariation() { XNode toReplace = Variation.Params[0] as XNode; XNode newValue = Variation.Params[1] as XNode; XDocument xDoc = new XDocument(toReplace); XDocument xDocOriginal = new XDocument(xDoc); using (UndoManager undo = new UndoManager(xDoc)) { undo.Group(); using (EventsHelper docHelper = new EventsHelper(xDoc)) { toReplace.ReplaceWith(newValue); docHelper.Verify(new XObjectChange[] { XObjectChange.Remove, XObjectChange.Add }, new XObject[] { toReplace, newValue }); } undo.Undo(); TestLog.Compare(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!"); } } public void ExecuteXElementVariation() { XNode toReplace = Variation.Params[0] as XNode; XNode newValue = Variation.Params[1] as XNode; XElement xElem = new XElement("root", toReplace); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { toReplace.ReplaceWith(newValue); xElem.Verify(); eHelper.Verify(new XObjectChange[] { XObjectChange.Remove, XObjectChange.Add }, new XObject[] { toReplace, newValue }); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } } public partial class EventsReplaceNodes : EventsBase { protected override void DetermineChildren() { VariationsForXDocument(ExecuteXDocumentVariation); VariationsForXElement(ExecuteXElementVariation); base.DetermineChildren(); } void VariationsForXDocument(TestFunc func) { AddChild(func, 0, "XDocument - empty element", new XElement("element")); AddChild(func, 0, "XDocument - element with child", new XElement("parent", new XElement("child", "child text"))); AddChild(func, 0, "XDocument - document type", new XDocumentType("root", "", "", "")); AddChild(func, 0, "XDocument - PI", new XProcessingInstruction("PI", "Data")); AddChild(func, 0, "XDocument - comment", new XComment("Comment")); } void VariationsForXElement(TestFunc func) { AddChild(func, 0, "XElement - empty element I", XElement.Parse(@"<a></a>")); AddChild(func, 0, "XElement - empty element II", new XElement("element")); AddChild(func, 0, "XElement - element with child", new XElement("parent", new XElement("child", "child text"))); AddChild(func, 0, "XElement - CData", new XCData("x+y >= z-m")); AddChild(func, 0, "XElement - PI", new XProcessingInstruction("PI", "Data")); AddChild(func, 0, "XElement - comment", new XComment("Comment")); AddChild(func, 0, "XElement - text nodes", new XText("")); } public void ExecuteXDocumentVariation() { XNode toReplace = Variation.Params[0] as XNode; XNode newValue = new XText(" "); XDocument xDoc = new XDocument(toReplace); XDocument xDocOriginal = new XDocument(xDoc); using (UndoManager undo = new UndoManager(xDoc)) { undo.Group(); using (EventsHelper docHelper = new EventsHelper(xDoc)) { xDoc.ReplaceNodes(newValue); TestLog.Compare(xDoc.Nodes().Count() == 1, "Not all content were removed"); TestLog.Compare(Object.ReferenceEquals(xDoc.FirstNode, newValue), "Did not replace correctly"); docHelper.Verify(new XObjectChange[] { XObjectChange.Remove, XObjectChange.Add }, new XObject[] { toReplace, newValue }); } undo.Undo(); TestLog.Compare(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!"); } } public void ExecuteXElementVariation() { XNode toReplace = Variation.Params[0] as XNode; XNode newValue = new XText("text"); XElement xElem = new XElement("root", InputSpace.GetAttributeElement(10, 1000).Elements().Attributes(), toReplace); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { xElem.ReplaceNodes(newValue); TestLog.Compare(xElem.Nodes().Count() == 1, "Did not replace correctly"); TestLog.Compare(Object.ReferenceEquals(xElem.FirstNode, newValue), "Did not replace correctly"); TestLog.Compare(xElem.HasAttributes, "ReplaceNodes removed attributes"); xElem.Verify(); eHelper.Verify(new XObjectChange[] { XObjectChange.Remove, XObjectChange.Add }, new XObject[] { toReplace, newValue }); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } //[Variation(Priority = 1, Desc = "XElement - Replace Nodes")] public void ReplaceNodes() { XElement xElem = new XElement(InputSpace.GetElement(1000, 2)); int count = xElem.Nodes().Count(); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { foreach (XElement x in xElem.Nodes()) { using (EventsHelper xHelper = new EventsHelper(x)) { x.ReplaceNodes("text"); xHelper.Verify(new XObjectChange[] { XObjectChange.Remove, XObjectChange.Remove, XObjectChange.Remove, XObjectChange.Add }); } eHelper.Verify(new XObjectChange[] { XObjectChange.Remove, XObjectChange.Remove, XObjectChange.Remove, XObjectChange.Add }); } undo.Undo(); TestLog.Compare(XNode.DeepEquals(xElem, xElemOriginal), "Undo did not work!"); } } } //[Variation(Priority = 1, Desc = "XElement - Replace with IEnumerable")] public void ReplaceWithIEnum() { XElement xElem = new XElement("root"); IEnumerable<XNode> newValue = InputSpace.GetElement(1000, 2).DescendantNodes(); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { xElem.ReplaceNodes(newValue); eHelper.Verify(XObjectChange.Add, newValue.ToArray()); } undo.Undo(); TestLog.Compare(XNode.DeepEquals(xElem, xElemOriginal), "Undo did not work!"); } } } public partial class EvensReplaceAttributes : EventsBase { protected override void DetermineChildren() { VariationsForXAttribute(ExecuteXAttributeVariation); base.DetermineChildren(); } void VariationsForXAttribute(TestFunc func) { AddChild(func, 0, "Only attribute", new XAttribute[] { new XAttribute("xxx", "yyy") }); AddChild(func, 0, "Only attribute with namespace", new XAttribute[] { new XAttribute("{a}xxx", "a_yyy") }); AddChild(func, 0, "Mulitple attributes", new XAttribute[] { new XAttribute("xxx", "yyy"), new XAttribute("a", "aa") }); AddChild(func, 0, "Multiple attributes with namespace", new XAttribute[] { new XAttribute("{b}xxx", "b_yyy"), new XAttribute("{a}xxx", "a_yyy") }); AddChild(func, 0, "IEnumerable of XAttributes", InputSpace.GetAttributeElement(10, 1000).Elements().Attributes().ToArray()); } public void ExecuteXAttributeVariation() { XAttribute[] content = Variation.Params as XAttribute[]; XElement xElem = new XElement("root", content); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { xElem.ReplaceAttributes(new XAttribute("a", "aa")); TestLog.Compare(XObject.ReferenceEquals(xElem.FirstAttribute, xElem.LastAttribute), "Did not replace attributes correctly"); xElem.Verify(); eHelper.Verify(content.Length + 1); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } } public partial class EventsReplaceAll : EventsBase { protected override void DetermineChildren() { VariationsForXElement(ExecuteXElementVariation); base.DetermineChildren(); } void VariationsForXElement(TestFunc func) { AddChild(func, 1, "XElement - empty element", new XObject[] { new XElement("element") }); AddChild(func, 0, "XElement - element with child", new XObject[] { new XElement("parent", new XElement("child", "child text")) }); AddChild(func, 0, "XElement - CData", new XObject[] { new XCData("x+y >= z-m") }); AddChild(func, 0, "XElement - PI", new XObject[] { new XProcessingInstruction("PI", "Data") }); AddChild(func, 0, "XElement - comment", new XObject[] { new XComment("Comment") }); AddChild(func, 0, "XElement - text nodes", new XObject[] { new XText(""), new XText(" "), new XText("\t") }); AddChild(func, 1, "XElement - IEnumerable of XNodes", InputSpace.GetElement(100, 10).DescendantNodes().ToArray()); AddChild(func, 0, "XAttribute - only attribute", new XObject[] { new XAttribute("xxx", "yyy") }); AddChild(func, 0, "XAttribute - only attribute with namespace", new XObject[] { new XAttribute("{a}xxx", "a_yyy") }); AddChild(func, 0, "XAttribute - mulitple attributes", new XObject[] { new XAttribute("xxx", "yyy"), new XAttribute("a", "aa") }); AddChild(func, 1, "XAttribute - multiple attributes with namespace", new XObject[] { new XAttribute("{b}xxx", "b_yyy"), new XAttribute("{a}xxx", "a_yyy") }); AddChild(func, 1, "XAttribute - IEnumerable of XAttributes", InputSpace.GetAttributeElement(10, 1000).Elements().Attributes().ToArray()); AddChild(func, 1, "Mixed - Nodes and attributes", new XObject[] { new XAttribute("{b}xxx", "b_yyy"), new XElement("parent", new XElement("child", "child text")) }); } public void ExecuteXElementVariation() { XObject[] toReplace = Variation.Params as XObject[]; XNode newValue = new XText("text"); XElement xElem = new XElement("root", toReplace); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { xElem.ReplaceAll(newValue); TestLog.Compare(xElem.Nodes().Count() == 1, "Did not replace correctly"); TestLog.Compare(Object.ReferenceEquals(xElem.FirstNode, newValue), "Did not replace correctly"); TestLog.Compare(!xElem.HasAttributes, "ReplaceAll did not remove attributes"); xElem.Verify(); eHelper.Verify(toReplace.Length + 1); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } //[Variation(Priority = 1, Desc = "Element with attributes, with Element with attributes")] public void ElementWithAttributes() { XElement toReplace = new XElement("Automobile", new XAttribute("axles", 2), new XElement("Make", "Ford"), new XElement("Model", "Mustang"), new XElement("Year", "2004")); XElement xElemOriginal = new XElement(toReplace); using (UndoManager undo = new UndoManager(toReplace)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(toReplace)) { toReplace.ReplaceAll(new XAttribute("axles", 2), new XElement("Make", "Chevrolet"), new XElement("Model", "Impala"), new XElement("Year", "2006")); toReplace.Verify(); } undo.Undo(); TestLog.Compare(toReplace.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(toReplace.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using SampleMetadata; using Xunit; namespace System.Reflection.Tests { public static partial class MethodTests { [Fact] public unsafe static void TestMethods1() { TestMethods1Worker(typeof(ClassWithMethods1<>).Project()); TestMethods1Worker(typeof(ClassWithMethods1<int>).Project()); TestMethods1Worker(typeof(ClassWithMethods1<string>).Project()); } private static void TestMethods1Worker(Type t) { const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodInfo m = t.GetMethod("Method1", bf); Assert.Equal("Method1", m.Name); Assert.Equal(t, m.DeclaringType); Assert.Equal(t, m.ReflectedType); Assert.False(m.IsGenericMethodDefinition); Assert.False(m.IsConstructedGenericMethod()); Assert.False(m.IsGenericMethod); Assert.Equal(MethodAttributes.Public | MethodAttributes.HideBySig, m.Attributes); Assert.Equal(MethodImplAttributes.IL, m.MethodImplementationFlags); Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, m.CallingConvention); Type theT = t.GetGenericArguments()[0]; Assert.Equal(typeof(bool).Project(), m.ReturnType); ParameterInfo rp = m.ReturnParameter; Assert.Equal(null, rp.Name); Assert.Equal(typeof(bool).Project(), rp.ParameterType); Assert.Equal(m, rp.Member); Assert.Equal(-1, rp.Position); ParameterInfo[] ps = m.GetParameters(); Assert.Equal(2, ps.Length); { ParameterInfo p = ps[0]; Assert.Equal("x", p.Name); Assert.Equal(typeof(int).Project(), p.ParameterType); Assert.Equal(m, p.Member); Assert.Equal(0, p.Position); } { ParameterInfo p = ps[1]; Assert.Equal("t", p.Name); Assert.Equal(theT, p.ParameterType); Assert.Equal(m, p.Member); Assert.Equal(1, p.Position); } TestUtils.AssertNewObjectReturnedEachTime(() => m.GetParameters()); m.TestMethodInfoInvariants(); } [Fact] public unsafe static void TestAllCoreTypes() { const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodInfo m = typeof(ClassWithMethods1<>).Project().GetMethod("TestPrimitives1", bf); Assert.Equal(typeof(void).Project(), m.ReturnParameter.ParameterType); ParameterInfo[] ps = m.GetParameters(); { ParameterInfo p = ps.Single((p1) => p1.Name == "bo"); Assert.Equal(typeof(bool).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "c"); Assert.Equal(typeof(char).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "b"); Assert.Equal(typeof(byte).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "s"); Assert.Equal(typeof(short).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "i"); Assert.Equal(typeof(int).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "l"); Assert.Equal(typeof(long).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "ip"); Assert.Equal(typeof(IntPtr).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "sb"); Assert.Equal(typeof(sbyte).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "us"); Assert.Equal(typeof(ushort).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "ui"); Assert.Equal(typeof(uint).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "ul"); Assert.Equal(typeof(ulong).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "uip"); Assert.Equal(typeof(UIntPtr).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "fl"); Assert.Equal(typeof(float).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "db"); Assert.Equal(typeof(double).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "o"); Assert.Equal(typeof(object).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "str"); Assert.Equal(typeof(string).Project(), p.ParameterType); } { ParameterInfo p = ps.Single((p1) => p1.Name == "tr"); Assert.Equal(typeof(TypedReference).Project(), p.ParameterType); } } [Fact] public static void TestGenericMethods1() { TestGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<,>).Project()); TestGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<int, string>).Project()); } private static void TestGenericMethods1Worker(Type t) { const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodInfo m = t.GetMethod("GenericMethod1", bf); Assert.Equal(m, m.GetGenericMethodDefinition()); Assert.Equal("GenericMethod1", m.Name); Assert.Equal(t, m.DeclaringType); Assert.Equal(t, m.ReflectedType); Assert.True(m.IsGenericMethodDefinition); Assert.False(m.IsConstructedGenericMethod()); Assert.True(m.IsGenericMethod); Type[] methodGenericParameters = m.GetGenericArguments(); Assert.Equal(2, methodGenericParameters.Length); Type theT = t.GetGenericArguments()[0]; Type theU = t.GetGenericArguments()[1]; Type theM = m.GetGenericArguments()[0]; Type theN = m.GetGenericArguments()[1]; theM.TestGenericMethodParameterInvariants(); theN.TestGenericMethodParameterInvariants(); ParameterInfo[] ps = m.GetParameters(); Assert.Equal(1, ps.Length); ParameterInfo p = ps[0]; Type actual = p.ParameterType; //GenericClass5<N, M[], IEnumerable<U>, T[,], int> Type expected = typeof(GenericClass5<,,,,>).Project().MakeGenericType( theN, theM.MakeArrayType(), typeof(IEnumerable<>).Project().MakeGenericType(theU), theT.MakeArrayType(2), typeof(int).Project()); Assert.Equal(expected, actual); m.TestGenericMethodInfoInvariants(); } [Fact] public static void TestConstructedGenericMethods1() { TestConstructedGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<,>).Project()); TestConstructedGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<int, string>).Project()); } private static void TestConstructedGenericMethods1Worker(Type t) { const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodInfo gm = t.GetMethod("GenericMethod1", bf); MethodInfo m = gm.MakeGenericMethod(typeof(object).Project(), typeof(string).Project()); Assert.Equal(gm, m.GetGenericMethodDefinition()); Assert.Equal("GenericMethod1", m.Name); Assert.Equal(t, m.DeclaringType); Assert.Equal(t, m.ReflectedType); Assert.False(m.IsGenericMethodDefinition); Assert.True(m.IsConstructedGenericMethod()); Assert.True(m.IsGenericMethod); Type[] methodGenericParameters = m.GetGenericArguments(); Assert.Equal(2, methodGenericParameters.Length); Type theT = t.GetGenericArguments()[0]; Type theU = t.GetGenericArguments()[1]; Type theM = m.GetGenericArguments()[0]; Type theN = m.GetGenericArguments()[1]; Assert.Equal(typeof(object).Project(), theM); Assert.Equal(typeof(string).Project(), theN); ParameterInfo[] ps = m.GetParameters(); Assert.Equal(1, ps.Length); ParameterInfo p = ps[0]; Type actual = p.ParameterType; //GenericClass5<N, M[], IEnumerable<U>, T[,], int> Type expected = typeof(GenericClass5<,,,,>).Project().MakeGenericType( theN, theM.MakeArrayType(), typeof(IEnumerable<>).Project().MakeGenericType(theU), theT.MakeArrayType(2), typeof(int).Project()); Assert.Equal(expected, actual); m.TestConstructedGenericMethodInfoInvariants(); } [Fact] public unsafe static void TestCustomModifiers1() { using (TypeLoader tl = new TypeLoader("mscorlib")) { tl.Resolving += delegate (TypeLoader sender, AssemblyName name) { if (name.Name == "mscorlib") return tl.LoadFromStream(TestUtils.CreateStreamForCoreAssembly()); return null; }; Assembly a = tl.LoadFromByteArray(TestData.s_CustomModifiersImage); Type t = a.GetType("N", throwOnError: true); Type reqA = a.GetType("ReqA", throwOnError: true); Type reqB = a.GetType("ReqB", throwOnError: true); Type reqC = a.GetType("ReqC", throwOnError: true); Type optA = a.GetType("OptA", throwOnError: true); Type optB = a.GetType("OptB", throwOnError: true); Type optC = a.GetType("OptC", throwOnError: true); MethodInfo m = t.GetMethod("MyMethod"); ParameterInfo p = m.GetParameters()[0]; Type[] req = p.GetRequiredCustomModifiers(); Type[] opt = p.GetOptionalCustomModifiers(); Assert.Equal<Type>(new Type[] { reqA, reqB, reqC }, req); Assert.Equal<Type>(new Type[] { optA, optB, optC }, opt); TestUtils.AssertNewObjectReturnedEachTime(() => p.GetRequiredCustomModifiers()); TestUtils.AssertNewObjectReturnedEachTime(() => p.GetOptionalCustomModifiers()); } } [Fact] public static void TestMethodBody1() { using (TypeLoader tl = new TypeLoader("mscorlib")) { Assembly coreAssembly = tl.LoadFromStream(TestUtils.CreateStreamForCoreAssembly()); tl.Resolving += delegate (TypeLoader sender, AssemblyName name) { if (name.Name == "mscorlib") return coreAssembly; return null; }; Assembly a = tl.LoadFromByteArray(TestData.s_AssemblyWithMethodBodyImage); //a = Assembly.Load(TestData.s_AssemblyWithMethodBodyImage); //coreAssembly = typeof(object).Assembly; Type nonsense = a.GetType("Nonsense`1", throwOnError: true); Type theT = nonsense.GetTypeInfo().GenericTypeParameters[0]; MethodInfo m = nonsense.GetMethod("Foo"); Type theM = m.GetGenericArguments()[0]; MethodBody mb = m.GetMethodBody(); byte[] il = mb.GetILAsByteArray(); Assert.Equal<byte>(TestData.s_AssemblyWithMethodBodyILBytes, il); Assert.Equal(4, mb.MaxStackSize); Assert.True(mb.InitLocals); Assert.Equal(0x11000001, mb.LocalSignatureMetadataToken); IList<LocalVariableInfo> lvis = mb.LocalVariables; Assert.Equal(10, lvis.Count); Assert.Equal(0, lvis[0].LocalIndex); Assert.False(lvis[0].IsPinned); Assert.Equal(coreAssembly.GetType("System.Single", throwOnError: true), lvis[0].LocalType); Assert.Equal(1, lvis[1].LocalIndex); Assert.False(lvis[1].IsPinned); Assert.Equal(coreAssembly.GetType("System.Double", throwOnError: true), lvis[1].LocalType); Assert.Equal(2, lvis[2].LocalIndex); Assert.False(lvis[2].IsPinned); Assert.Equal(theT, lvis[2].LocalType); Assert.Equal(3, lvis[3].LocalIndex); Assert.False(lvis[3].IsPinned); Assert.Equal(theT.MakeArrayType(), lvis[3].LocalType); Assert.Equal(4, lvis[4].LocalIndex); Assert.False(lvis[4].IsPinned); Assert.Equal(coreAssembly.GetType("System.Collections.Generic.IList`1", throwOnError: true).MakeGenericType(theM), lvis[4].LocalType); Assert.Equal(5, lvis[5].LocalIndex); Assert.False(lvis[5].IsPinned); Assert.Equal(coreAssembly.GetType("System.String", throwOnError: true), lvis[5].LocalType); Assert.Equal(6, lvis[6].LocalIndex); Assert.False(lvis[6].IsPinned); Assert.Equal(coreAssembly.GetType("System.Int32", throwOnError: true).MakeArrayType(), lvis[6].LocalType); Assert.Equal(7, lvis[7].LocalIndex); Assert.True(lvis[7].IsPinned); Assert.Equal(coreAssembly.GetType("System.Int32", throwOnError: true).MakeByRefType(), lvis[7].LocalType); Assert.Equal(8, lvis[8].LocalIndex); Assert.False(lvis[8].IsPinned); Assert.Equal(coreAssembly.GetType("System.Int32", throwOnError: true).MakeArrayType(), lvis[8].LocalType); Assert.Equal(9, lvis[9].LocalIndex); Assert.False(lvis[9].IsPinned); Assert.Equal(coreAssembly.GetType("System.Boolean", throwOnError: true), lvis[9].LocalType); IList<ExceptionHandlingClause> ehcs = mb.ExceptionHandlingClauses; Assert.Equal(2, ehcs.Count); ExceptionHandlingClause ehc = ehcs[0]; Assert.Equal(ExceptionHandlingClauseOptions.Finally, ehc.Flags); Assert.Equal(97, ehc.TryOffset); Assert.Equal(41, ehc.TryLength); Assert.Equal(138, ehc.HandlerOffset); Assert.Equal(5, ehc.HandlerLength); ehc = ehcs[1]; Assert.Equal(ExceptionHandlingClauseOptions.Filter, ehc.Flags); Assert.Equal(88, ehc.TryOffset); Assert.Equal(58, ehc.TryLength); Assert.Equal(172, ehc.HandlerOffset); Assert.Equal(16, ehc.HandlerLength); Assert.Equal(146, ehc.FilterOffset); } } [Fact] public static void TestEHClauses() { using (TypeLoader tl = new TypeLoader()) { Assembly coreAssembly = tl.LoadFromStream(TestUtils.CreateStreamForCoreAssembly()); tl.Resolving += delegate (TypeLoader sender, AssemblyName name) { if (name.Name == "mscorlib") return coreAssembly; return null; }; Assembly a = tl.LoadFromByteArray(TestData.s_AssemblyWithEhClausesImage); Type gt = a.GetType("G`1", throwOnError: true); Type et = a.GetType("MyException`2", throwOnError: true); Type gtP0 = gt.GetGenericTypeParameters()[0]; Type etP0 = et.GetGenericTypeParameters()[0]; Type etP1 = et.GetGenericTypeParameters()[1]; { MethodInfo m = gt.GetMethod("Catch"); Type theM = m.GetGenericArguments()[0]; MethodBody body = m.GetMethodBody(); IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses; Assert.Equal(1, ehs.Count); ExceptionHandlingClause eh = ehs[0]; Assert.Equal(ExceptionHandlingClauseOptions.Clause, eh.Flags); Assert.Equal(1, eh.TryOffset); Assert.Equal(15, eh.TryLength); Assert.Equal(16, eh.HandlerOffset); Assert.Equal(16, eh.HandlerLength); Assert.Throws<InvalidOperationException>(() => eh.FilterOffset); Assert.Equal(et.MakeGenericType(gtP0, theM), eh.CatchType); } { Type sysInt32 = coreAssembly.GetType("System.Int32", throwOnError: true); Type sysSingle = coreAssembly.GetType("System.Single", throwOnError: true); MethodInfo m = gt.MakeGenericType(sysInt32).GetMethod("Catch").MakeGenericMethod(sysSingle); MethodBody body = m.GetMethodBody(); IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses; Assert.Equal(1, ehs.Count); ExceptionHandlingClause eh = ehs[0]; Assert.Equal(ExceptionHandlingClauseOptions.Clause, eh.Flags); Assert.Equal(1, eh.TryOffset); Assert.Equal(15, eh.TryLength); Assert.Equal(16, eh.HandlerOffset); Assert.Equal(16, eh.HandlerLength); Assert.Throws<InvalidOperationException>(() => eh.FilterOffset); Assert.Equal(et.MakeGenericType(sysInt32, sysSingle), eh.CatchType); } { MethodInfo m = gt.GetMethod("Finally"); MethodBody body = m.GetMethodBody(); IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses; Assert.Equal(1, ehs.Count); ExceptionHandlingClause eh = ehs[0]; Assert.Equal(ExceptionHandlingClauseOptions.Finally, eh.Flags); Assert.Equal(1, eh.TryOffset); Assert.Equal(15, eh.TryLength); Assert.Equal(16, eh.HandlerOffset); Assert.Equal(14, eh.HandlerLength); Assert.Throws<InvalidOperationException>(() => eh.FilterOffset); Assert.Throws<InvalidOperationException>(() => eh.CatchType); } { MethodInfo m = gt.GetMethod("Fault"); MethodBody body = m.GetMethodBody(); IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses; Assert.Equal(1, ehs.Count); ExceptionHandlingClause eh = ehs[0]; Assert.Equal(ExceptionHandlingClauseOptions.Fault, eh.Flags); Assert.Equal(1, eh.TryOffset); Assert.Equal(15, eh.TryLength); Assert.Equal(16, eh.HandlerOffset); Assert.Equal(14, eh.HandlerLength); Assert.Throws<InvalidOperationException>(() => eh.FilterOffset); Assert.Throws<InvalidOperationException>(() => eh.CatchType); } { MethodInfo m = gt.GetMethod("Filter"); MethodBody body = m.GetMethodBody(); IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses; Assert.Equal(1, ehs.Count); ExceptionHandlingClause eh = ehs[0]; Assert.Equal(ExceptionHandlingClauseOptions.Filter, eh.Flags); Assert.Equal(1, eh.TryOffset); Assert.Equal(15, eh.TryLength); Assert.Equal(40, eh.HandlerOffset); Assert.Equal(16, eh.HandlerLength); Assert.Equal(16, eh.FilterOffset); Assert.Throws<InvalidOperationException>(() => eh.CatchType); } } } [Fact] public static void TestCallingConventions() { const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase[] mbs = (MethodBase[])(typeof(ExerciseCallingConventions).Project().GetMember("*", MemberTypes.Method | MemberTypes.Constructor, bf)); mbs = mbs.OrderBy(m => m.Name).ToArray(); Assert.Equal(5, mbs.Length); Assert.Equal(".cctor", mbs[0].Name); Assert.Equal(CallingConventions.Standard, mbs[0].CallingConvention); Assert.Equal(".ctor", mbs[1].Name); Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, mbs[1].CallingConvention); Assert.Equal("InstanceMethod", mbs[2].Name); Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, mbs[2].CallingConvention); Assert.Equal("StaticMethod", mbs[3].Name); Assert.Equal(CallingConventions.Standard, mbs[3].CallingConvention); Assert.Equal("VirtualMethod", mbs[4].Name); Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, mbs[4].CallingConvention); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.ServiceModel; using ASC.Core.Common.Notify.Jabber; namespace ASC.Core.Notify.Jabber { public class JabberServiceClient { private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2); private static DateTime lastErrorTime = default(DateTime); private static bool IsServiceProbablyNotAvailable() { return lastErrorTime != default(DateTime) && lastErrorTime + Timeout > DateTime.Now; } public bool SendMessage(int tenantId, string from, string to, string text, string subject) { if (IsServiceProbablyNotAvailable()) return false; using (var service = GetService()) { try { service.SendMessage(tenantId, from, to, text, subject); return true; } catch (Exception error) { ProcessError(error); } } return false; } public string GetVersion() { using (var service = GetService()) { try { return service.GetVersion(); } catch (Exception error) { ProcessError(error); } } return null; } public int GetNewMessagesCount() { var result = 0; if (IsServiceProbablyNotAvailable()) return result; using (var service = GetService()) { try { return service.GetNewMessagesCount(GetCurrentTenantId(), GetCurrentUserName()); } catch (Exception error) { ProcessError(error); } } return result; } public byte AddXmppConnection(string connectionId, byte state) { byte result = 4; if (IsServiceProbablyNotAvailable()) throw new Exception(); using (var service = GetService()) { try { result = service.AddXmppConnection(connectionId, GetCurrentUserName(), state, GetCurrentTenantId()); } catch (Exception error) { ProcessError(error); } return result; } } public byte RemoveXmppConnection(string connectionId) { const byte result = 4; if (IsServiceProbablyNotAvailable()) return result; using (var service = GetService()) { try { return service.RemoveXmppConnection(connectionId, GetCurrentUserName(), GetCurrentTenantId()); } catch (Exception error) { ProcessError(error); } } return result; } public byte GetState(string userName) { const byte defaultState = 0; try { if (IsServiceProbablyNotAvailable()) return defaultState; using (var service = GetService()) { return service.GetState(GetCurrentTenantId(), userName); } } catch (Exception error) { ProcessError(error); } return defaultState; } public byte SendState(byte state) { try { if (IsServiceProbablyNotAvailable()) throw new Exception(); using (var service = GetService()) { return service.SendState(GetCurrentTenantId(), GetCurrentUserName(), state); } } catch (Exception error) { ProcessError(error); } return 4; } public Dictionary<string, byte> GetAllStates() { Dictionary<string, byte> states = null; try { if (IsServiceProbablyNotAvailable()) throw new Exception(); using (var service = GetService()) { states = service.GetAllStates(GetCurrentTenantId(), GetCurrentUserName()); } } catch (Exception error) { ProcessError(error); } return states; } public MessageClass[] GetRecentMessages(string to, int id) { MessageClass[] messages = null; try { if (IsServiceProbablyNotAvailable()) throw new Exception(); using (var service = GetService()) { messages = service.GetRecentMessages(GetCurrentTenantId(), GetCurrentUserName(), to, id); } } catch (Exception error) { ProcessError(error); } return messages; } public void Ping(byte state) { try { if (IsServiceProbablyNotAvailable()) throw new Exception(); using (var service = GetService()) { service.Ping(SecurityContext.CurrentAccount.ID.ToString(), GetCurrentTenantId(), GetCurrentUserName(), state); } } catch (Exception error) { ProcessError(error); } } private static int GetCurrentTenantId() { return CoreContext.TenantManager.GetCurrentTenant().TenantId; } private static string GetCurrentUserName() { return CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).UserName; } private static void ProcessError(Exception error) { if (error is FaultException) { throw error; } if (error is CommunicationException || error is TimeoutException) { lastErrorTime = DateTime.Now; } throw error; } private JabberServiceClientWcf GetService() { return new JabberServiceClientWcf(); } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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 Jim Heising 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 CallButler.Manager.ViewControls { partial class SummaryView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SummaryView)); this.grpCallHistory = new global::Controls.GroupBoxEx(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pnlCallHistory = new System.Windows.Forms.Panel(); this.btnViewCallHistory = new global::Controls.LinkButton(); this.groupBoxEx1 = new global::Controls.GroupBoxEx(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.panel2 = new System.Windows.Forms.Panel(); this.lblCallsToday = new System.Windows.Forms.Label(); this.lblCallsTotal = new System.Windows.Forms.Label(); this.lblCallsMonth = new System.Windows.Forms.Label(); this.lblCallsWeek = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.toolTip = new System.Windows.Forms.ToolTip(this.components); this.bsVoicemail = new System.Windows.Forms.BindingSource(this.components); this.callButlerDataset = new WOSI.CallButler.Data.CallButlerDataset(); this.roundedCornerPanel1 = new global::Controls.RoundedCornerPanel(); this.pictureBox3 = new System.Windows.Forms.PictureBox(); this.quickTipsControl1 = new CallButler.Manager.Controls.QuickTipsControl(); this.lblDescription = new global::Controls.SmoothLabel(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.grpCallHistory.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.groupBoxEx1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); this.panel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.bsVoicemail)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.callButlerDataset)).BeginInit(); this.roundedCornerPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // grpCallHistory // this.grpCallHistory.AntiAliasText = false; this.grpCallHistory.Controls.Add(this.pictureBox1); this.grpCallHistory.Controls.Add(this.pnlCallHistory); this.grpCallHistory.Controls.Add(this.btnViewCallHistory); this.grpCallHistory.CornerRadius = 10; this.grpCallHistory.DividerAbove = false; resources.ApplyResources(this.grpCallHistory, "grpCallHistory"); this.grpCallHistory.DrawLeftDivider = false; this.grpCallHistory.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.grpCallHistory.HeaderColor = System.Drawing.Color.Silver; this.grpCallHistory.Name = "grpCallHistory"; // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.Color.Transparent; this.pictureBox1.Image = global::CallButler.Manager.Properties.Resources.telephone_24; resources.ApplyResources(this.pictureBox1, "pictureBox1"); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.TabStop = false; // // pnlCallHistory // resources.ApplyResources(this.pnlCallHistory, "pnlCallHistory"); this.pnlCallHistory.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.pnlCallHistory.Name = "pnlCallHistory"; this.pnlCallHistory.Resize += new System.EventHandler(this.pnlCallHistory_Resize); // // btnViewCallHistory // this.btnViewCallHistory.AntiAliasText = false; resources.ApplyResources(this.btnViewCallHistory, "btnViewCallHistory"); this.btnViewCallHistory.Cursor = System.Windows.Forms.Cursors.Hand; this.btnViewCallHistory.ForeColor = System.Drawing.Color.RoyalBlue; this.btnViewCallHistory.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnViewCallHistory.LinkImage = global::CallButler.Manager.Properties.Resources.view_16; this.btnViewCallHistory.Name = "btnViewCallHistory"; this.btnViewCallHistory.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnViewCallHistory.UnderlineOnHover = true; this.btnViewCallHistory.Click += new System.EventHandler(this.btnViewCallHistory_Click); // // groupBoxEx1 // this.groupBoxEx1.AntiAliasText = false; this.groupBoxEx1.Controls.Add(this.pictureBox2); this.groupBoxEx1.Controls.Add(this.panel2); this.groupBoxEx1.CornerRadius = 10; this.groupBoxEx1.DividerAbove = false; resources.ApplyResources(this.groupBoxEx1, "groupBoxEx1"); this.groupBoxEx1.DrawLeftDivider = false; this.groupBoxEx1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.groupBoxEx1.HeaderColor = System.Drawing.Color.Silver; this.groupBoxEx1.Name = "groupBoxEx1"; // // pictureBox2 // this.pictureBox2.BackColor = System.Drawing.Color.Transparent; this.pictureBox2.Image = global::CallButler.Manager.Properties.Resources.column_chart_24; resources.ApplyResources(this.pictureBox2, "pictureBox2"); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.TabStop = false; // // panel2 // this.panel2.Controls.Add(this.lblCallsToday); this.panel2.Controls.Add(this.lblCallsTotal); this.panel2.Controls.Add(this.lblCallsMonth); this.panel2.Controls.Add(this.lblCallsWeek); this.panel2.Controls.Add(this.label1); this.panel2.Controls.Add(this.label4); this.panel2.Controls.Add(this.label2); this.panel2.Controls.Add(this.label3); resources.ApplyResources(this.panel2, "panel2"); this.panel2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.panel2.Name = "panel2"; // // lblCallsToday // resources.ApplyResources(this.lblCallsToday, "lblCallsToday"); this.lblCallsToday.Name = "lblCallsToday"; // // lblCallsTotal // resources.ApplyResources(this.lblCallsTotal, "lblCallsTotal"); this.lblCallsTotal.Name = "lblCallsTotal"; // // lblCallsMonth // resources.ApplyResources(this.lblCallsMonth, "lblCallsMonth"); this.lblCallsMonth.Name = "lblCallsMonth"; // // lblCallsWeek // resources.ApplyResources(this.lblCallsWeek, "lblCallsWeek"); this.lblCallsWeek.Name = "lblCallsWeek"; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // bsVoicemail // this.bsVoicemail.AllowNew = false; this.bsVoicemail.DataMember = "Voicemails"; this.bsVoicemail.DataSource = this.callButlerDataset; this.bsVoicemail.Filter = "IsNew = True"; this.bsVoicemail.Sort = ""; // // callButlerDataset // this.callButlerDataset.DataSetName = "CallButlerDataset"; this.callButlerDataset.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // roundedCornerPanel1 // this.roundedCornerPanel1.BorderSize = 1F; this.roundedCornerPanel1.Controls.Add(this.pictureBox3); this.roundedCornerPanel1.Controls.Add(this.quickTipsControl1); this.roundedCornerPanel1.Controls.Add(this.lblDescription); this.roundedCornerPanel1.CornerRadius = 5; this.roundedCornerPanel1.DisplayShadow = true; resources.ApplyResources(this.roundedCornerPanel1, "roundedCornerPanel1"); this.roundedCornerPanel1.ForeColor = System.Drawing.Color.Gainsboro; this.roundedCornerPanel1.Name = "roundedCornerPanel1"; this.roundedCornerPanel1.PanelColor = System.Drawing.Color.GhostWhite; this.tableLayoutPanel1.SetRowSpan(this.roundedCornerPanel1, 2); this.roundedCornerPanel1.ShadowColor = System.Drawing.Color.Gainsboro; this.roundedCornerPanel1.ShadowOffset = 2; // // pictureBox3 // resources.ApplyResources(this.pictureBox3, "pictureBox3"); this.pictureBox3.BackColor = System.Drawing.Color.Transparent; this.pictureBox3.Image = global::CallButler.Manager.Properties.Resources.about_32; this.pictureBox3.Name = "pictureBox3"; this.pictureBox3.TabStop = false; // // quickTipsControl1 // this.quickTipsControl1.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.quickTipsControl1, "quickTipsControl1"); this.quickTipsControl1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.quickTipsControl1.Name = "quickTipsControl1"; // // lblDescription // this.lblDescription.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.lblDescription, "lblDescription"); this.lblDescription.ForeColor = System.Drawing.Color.CornflowerBlue; this.lblDescription.Name = "lblDescription"; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.roundedCornerPanel1, 1, 0); this.tableLayoutPanel1.Controls.Add(this.grpCallHistory, 0, 0); this.tableLayoutPanel1.Controls.Add(this.groupBoxEx1, 0, 1); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // SummaryView // resources.ApplyResources(this, "$this"); this.Controls.Add(this.tableLayoutPanel1); this.HeaderIcon = global::CallButler.Manager.Properties.Resources.gear_find_48_shadow; this.Name = "SummaryView"; this.Controls.SetChildIndex(this.tableLayoutPanel1, 0); this.grpCallHistory.ResumeLayout(false); this.grpCallHistory.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.groupBoxEx1.ResumeLayout(false); this.groupBoxEx1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.bsVoicemail)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.callButlerDataset)).EndInit(); this.roundedCornerPanel1.ResumeLayout(false); this.roundedCornerPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit(); this.tableLayoutPanel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private global::Controls.GroupBoxEx grpCallHistory; private System.Windows.Forms.Panel pnlCallHistory; private global::Controls.LinkButton btnViewCallHistory; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private global::Controls.GroupBoxEx groupBoxEx1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.ToolTip toolTip; private System.Windows.Forms.Label lblCallsToday; private System.Windows.Forms.Label lblCallsTotal; private System.Windows.Forms.Label lblCallsMonth; private System.Windows.Forms.Label lblCallsWeek; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox2; private WOSI.CallButler.Data.CallButlerDataset callButlerDataset; private System.Windows.Forms.BindingSource bsVoicemail; private System.Windows.Forms.DataGridViewTextBoxColumn mailboxIDDataGridViewTextBoxColumn; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private global::Controls.SmoothLabel lblDescription; private global::Controls.RoundedCornerPanel roundedCornerPanel1; private CallButler.Manager.Controls.QuickTipsControl quickTipsControl1; private System.Windows.Forms.PictureBox pictureBox3; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/bigtable/v2/bigtable.proto // Original file comments: // Copyright 2016 Google 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. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Bigtable.V2 { /// <summary> /// Service for reading from and writing to existing Bigtable tables. /// </summary> public static class Bigtable { static readonly string __ServiceName = "google.bigtable.v2.Bigtable"; static readonly Marshaller<global::Google.Bigtable.V2.ReadRowsRequest> __Marshaller_ReadRowsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.ReadRowsRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.ReadRowsResponse> __Marshaller_ReadRowsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.ReadRowsResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.SampleRowKeysRequest> __Marshaller_SampleRowKeysRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.SampleRowKeysRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.SampleRowKeysResponse> __Marshaller_SampleRowKeysResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.SampleRowKeysResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.MutateRowRequest> __Marshaller_MutateRowRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.MutateRowRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.MutateRowResponse> __Marshaller_MutateRowResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.MutateRowResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.MutateRowsRequest> __Marshaller_MutateRowsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.MutateRowsRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.MutateRowsResponse> __Marshaller_MutateRowsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.MutateRowsResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.CheckAndMutateRowRequest> __Marshaller_CheckAndMutateRowRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.CheckAndMutateRowRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.CheckAndMutateRowResponse> __Marshaller_CheckAndMutateRowResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.CheckAndMutateRowResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.ReadModifyWriteRowRequest> __Marshaller_ReadModifyWriteRowRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.ReadModifyWriteRowRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.V2.ReadModifyWriteRowResponse> __Marshaller_ReadModifyWriteRowResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.V2.ReadModifyWriteRowResponse.Parser.ParseFrom); static readonly Method<global::Google.Bigtable.V2.ReadRowsRequest, global::Google.Bigtable.V2.ReadRowsResponse> __Method_ReadRows = new Method<global::Google.Bigtable.V2.ReadRowsRequest, global::Google.Bigtable.V2.ReadRowsResponse>( MethodType.ServerStreaming, __ServiceName, "ReadRows", __Marshaller_ReadRowsRequest, __Marshaller_ReadRowsResponse); static readonly Method<global::Google.Bigtable.V2.SampleRowKeysRequest, global::Google.Bigtable.V2.SampleRowKeysResponse> __Method_SampleRowKeys = new Method<global::Google.Bigtable.V2.SampleRowKeysRequest, global::Google.Bigtable.V2.SampleRowKeysResponse>( MethodType.ServerStreaming, __ServiceName, "SampleRowKeys", __Marshaller_SampleRowKeysRequest, __Marshaller_SampleRowKeysResponse); static readonly Method<global::Google.Bigtable.V2.MutateRowRequest, global::Google.Bigtable.V2.MutateRowResponse> __Method_MutateRow = new Method<global::Google.Bigtable.V2.MutateRowRequest, global::Google.Bigtable.V2.MutateRowResponse>( MethodType.Unary, __ServiceName, "MutateRow", __Marshaller_MutateRowRequest, __Marshaller_MutateRowResponse); static readonly Method<global::Google.Bigtable.V2.MutateRowsRequest, global::Google.Bigtable.V2.MutateRowsResponse> __Method_MutateRows = new Method<global::Google.Bigtable.V2.MutateRowsRequest, global::Google.Bigtable.V2.MutateRowsResponse>( MethodType.ServerStreaming, __ServiceName, "MutateRows", __Marshaller_MutateRowsRequest, __Marshaller_MutateRowsResponse); static readonly Method<global::Google.Bigtable.V2.CheckAndMutateRowRequest, global::Google.Bigtable.V2.CheckAndMutateRowResponse> __Method_CheckAndMutateRow = new Method<global::Google.Bigtable.V2.CheckAndMutateRowRequest, global::Google.Bigtable.V2.CheckAndMutateRowResponse>( MethodType.Unary, __ServiceName, "CheckAndMutateRow", __Marshaller_CheckAndMutateRowRequest, __Marshaller_CheckAndMutateRowResponse); static readonly Method<global::Google.Bigtable.V2.ReadModifyWriteRowRequest, global::Google.Bigtable.V2.ReadModifyWriteRowResponse> __Method_ReadModifyWriteRow = new Method<global::Google.Bigtable.V2.ReadModifyWriteRowRequest, global::Google.Bigtable.V2.ReadModifyWriteRowResponse>( MethodType.Unary, __ServiceName, "ReadModifyWriteRow", __Marshaller_ReadModifyWriteRowRequest, __Marshaller_ReadModifyWriteRowResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Bigtable.V2.BigtableReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of Bigtable</summary> public abstract class BigtableBase { /// <summary> /// Streams back the contents of all requested rows, optionally /// applying the same Reader filter to each. Depending on their size, /// rows and cells may be broken up across multiple responses, but /// atomicity of each row will still be preserved. See the /// ReadRowsResponse documentation for details. /// </summary> public virtual global::System.Threading.Tasks.Task ReadRows(global::Google.Bigtable.V2.ReadRowsRequest request, IServerStreamWriter<global::Google.Bigtable.V2.ReadRowsResponse> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Returns a sample of row keys in the table. The returned row keys will /// delimit contiguous sections of the table of approximately equal size, /// which can be used to break up the data for distributed tasks like /// mapreduces. /// </summary> public virtual global::System.Threading.Tasks.Task SampleRowKeys(global::Google.Bigtable.V2.SampleRowKeysRequest request, IServerStreamWriter<global::Google.Bigtable.V2.SampleRowKeysResponse> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Mutates a row atomically. Cells already present in the row are left /// unchanged unless explicitly changed by `mutation`. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.V2.MutateRowResponse> MutateRow(global::Google.Bigtable.V2.MutateRowRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Mutates multiple rows in a batch. Each individual row is mutated /// atomically as in MutateRow, but the entire batch is not executed /// atomically. /// </summary> public virtual global::System.Threading.Tasks.Task MutateRows(global::Google.Bigtable.V2.MutateRowsRequest request, IServerStreamWriter<global::Google.Bigtable.V2.MutateRowsResponse> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Mutates a row atomically based on the output of a predicate Reader filter. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.V2.CheckAndMutateRowResponse> CheckAndMutateRow(global::Google.Bigtable.V2.CheckAndMutateRowRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Modifies a row atomically. The method reads the latest existing timestamp /// and value from the specified columns and writes a new entry based on /// pre-defined read/modify/write rules. The new value for the timestamp is the /// greater of the existing timestamp or the current server time. The method /// returns the new contents of all modified cells. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.V2.ReadModifyWriteRowResponse> ReadModifyWriteRow(global::Google.Bigtable.V2.ReadModifyWriteRowRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for Bigtable</summary> public class BigtableClient : ClientBase<BigtableClient> { /// <summary>Creates a new client for Bigtable</summary> /// <param name="channel">The channel to use to make remote calls.</param> public BigtableClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for Bigtable that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public BigtableClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected BigtableClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected BigtableClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Streams back the contents of all requested rows, optionally /// applying the same Reader filter to each. Depending on their size, /// rows and cells may be broken up across multiple responses, but /// atomicity of each row will still be preserved. See the /// ReadRowsResponse documentation for details. /// </summary> public virtual AsyncServerStreamingCall<global::Google.Bigtable.V2.ReadRowsResponse> ReadRows(global::Google.Bigtable.V2.ReadRowsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ReadRows(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Streams back the contents of all requested rows, optionally /// applying the same Reader filter to each. Depending on their size, /// rows and cells may be broken up across multiple responses, but /// atomicity of each row will still be preserved. See the /// ReadRowsResponse documentation for details. /// </summary> public virtual AsyncServerStreamingCall<global::Google.Bigtable.V2.ReadRowsResponse> ReadRows(global::Google.Bigtable.V2.ReadRowsRequest request, CallOptions options) { return CallInvoker.AsyncServerStreamingCall(__Method_ReadRows, null, options, request); } /// <summary> /// Returns a sample of row keys in the table. The returned row keys will /// delimit contiguous sections of the table of approximately equal size, /// which can be used to break up the data for distributed tasks like /// mapreduces. /// </summary> public virtual AsyncServerStreamingCall<global::Google.Bigtable.V2.SampleRowKeysResponse> SampleRowKeys(global::Google.Bigtable.V2.SampleRowKeysRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SampleRowKeys(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns a sample of row keys in the table. The returned row keys will /// delimit contiguous sections of the table of approximately equal size, /// which can be used to break up the data for distributed tasks like /// mapreduces. /// </summary> public virtual AsyncServerStreamingCall<global::Google.Bigtable.V2.SampleRowKeysResponse> SampleRowKeys(global::Google.Bigtable.V2.SampleRowKeysRequest request, CallOptions options) { return CallInvoker.AsyncServerStreamingCall(__Method_SampleRowKeys, null, options, request); } /// <summary> /// Mutates a row atomically. Cells already present in the row are left /// unchanged unless explicitly changed by `mutation`. /// </summary> public virtual global::Google.Bigtable.V2.MutateRowResponse MutateRow(global::Google.Bigtable.V2.MutateRowRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return MutateRow(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Mutates a row atomically. Cells already present in the row are left /// unchanged unless explicitly changed by `mutation`. /// </summary> public virtual global::Google.Bigtable.V2.MutateRowResponse MutateRow(global::Google.Bigtable.V2.MutateRowRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_MutateRow, null, options, request); } /// <summary> /// Mutates a row atomically. Cells already present in the row are left /// unchanged unless explicitly changed by `mutation`. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.V2.MutateRowResponse> MutateRowAsync(global::Google.Bigtable.V2.MutateRowRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return MutateRowAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Mutates a row atomically. Cells already present in the row are left /// unchanged unless explicitly changed by `mutation`. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.V2.MutateRowResponse> MutateRowAsync(global::Google.Bigtable.V2.MutateRowRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_MutateRow, null, options, request); } /// <summary> /// Mutates multiple rows in a batch. Each individual row is mutated /// atomically as in MutateRow, but the entire batch is not executed /// atomically. /// </summary> public virtual AsyncServerStreamingCall<global::Google.Bigtable.V2.MutateRowsResponse> MutateRows(global::Google.Bigtable.V2.MutateRowsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return MutateRows(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Mutates multiple rows in a batch. Each individual row is mutated /// atomically as in MutateRow, but the entire batch is not executed /// atomically. /// </summary> public virtual AsyncServerStreamingCall<global::Google.Bigtable.V2.MutateRowsResponse> MutateRows(global::Google.Bigtable.V2.MutateRowsRequest request, CallOptions options) { return CallInvoker.AsyncServerStreamingCall(__Method_MutateRows, null, options, request); } /// <summary> /// Mutates a row atomically based on the output of a predicate Reader filter. /// </summary> public virtual global::Google.Bigtable.V2.CheckAndMutateRowResponse CheckAndMutateRow(global::Google.Bigtable.V2.CheckAndMutateRowRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CheckAndMutateRow(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Mutates a row atomically based on the output of a predicate Reader filter. /// </summary> public virtual global::Google.Bigtable.V2.CheckAndMutateRowResponse CheckAndMutateRow(global::Google.Bigtable.V2.CheckAndMutateRowRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CheckAndMutateRow, null, options, request); } /// <summary> /// Mutates a row atomically based on the output of a predicate Reader filter. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.V2.CheckAndMutateRowResponse> CheckAndMutateRowAsync(global::Google.Bigtable.V2.CheckAndMutateRowRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CheckAndMutateRowAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Mutates a row atomically based on the output of a predicate Reader filter. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.V2.CheckAndMutateRowResponse> CheckAndMutateRowAsync(global::Google.Bigtable.V2.CheckAndMutateRowRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CheckAndMutateRow, null, options, request); } /// <summary> /// Modifies a row atomically. The method reads the latest existing timestamp /// and value from the specified columns and writes a new entry based on /// pre-defined read/modify/write rules. The new value for the timestamp is the /// greater of the existing timestamp or the current server time. The method /// returns the new contents of all modified cells. /// </summary> public virtual global::Google.Bigtable.V2.ReadModifyWriteRowResponse ReadModifyWriteRow(global::Google.Bigtable.V2.ReadModifyWriteRowRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ReadModifyWriteRow(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Modifies a row atomically. The method reads the latest existing timestamp /// and value from the specified columns and writes a new entry based on /// pre-defined read/modify/write rules. The new value for the timestamp is the /// greater of the existing timestamp or the current server time. The method /// returns the new contents of all modified cells. /// </summary> public virtual global::Google.Bigtable.V2.ReadModifyWriteRowResponse ReadModifyWriteRow(global::Google.Bigtable.V2.ReadModifyWriteRowRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ReadModifyWriteRow, null, options, request); } /// <summary> /// Modifies a row atomically. The method reads the latest existing timestamp /// and value from the specified columns and writes a new entry based on /// pre-defined read/modify/write rules. The new value for the timestamp is the /// greater of the existing timestamp or the current server time. The method /// returns the new contents of all modified cells. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.V2.ReadModifyWriteRowResponse> ReadModifyWriteRowAsync(global::Google.Bigtable.V2.ReadModifyWriteRowRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ReadModifyWriteRowAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Modifies a row atomically. The method reads the latest existing timestamp /// and value from the specified columns and writes a new entry based on /// pre-defined read/modify/write rules. The new value for the timestamp is the /// greater of the existing timestamp or the current server time. The method /// returns the new contents of all modified cells. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.V2.ReadModifyWriteRowResponse> ReadModifyWriteRowAsync(global::Google.Bigtable.V2.ReadModifyWriteRowRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ReadModifyWriteRow, null, options, request); } protected override BigtableClient NewInstance(ClientBaseConfiguration configuration) { return new BigtableClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(BigtableBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_ReadRows, serviceImpl.ReadRows) .AddMethod(__Method_SampleRowKeys, serviceImpl.SampleRowKeys) .AddMethod(__Method_MutateRow, serviceImpl.MutateRow) .AddMethod(__Method_MutateRows, serviceImpl.MutateRows) .AddMethod(__Method_CheckAndMutateRow, serviceImpl.CheckAndMutateRow) .AddMethod(__Method_ReadModifyWriteRow, serviceImpl.ReadModifyWriteRow).Build(); } } } #endregion
#pragma warning disable 1634, 1691 /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #pragma warning disable 1634, 1691 #pragma warning disable 56506 using System; using System.Management.Automation; using Dbg = System.Management.Automation; using System.Management.Automation.Security; using System.Security.AccessControl; using System.Security.Principal; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Globalization; using System.ComponentModel; #if CORECLR // Use stub for SystemException using Microsoft.PowerShell.CoreClr.Stubs; using System.Reflection; #endif namespace Microsoft.PowerShell.Commands { /// <summary> /// Defines the base class from which all Security Descriptor commands /// are derived. /// </summary> public abstract class SecurityDescriptorCommandsBase : PSCmdlet { /// <summary> /// Gets or sets the filter property. The filter /// property allows for provider-specific filtering of results. /// </summary> [Parameter] public string Filter { get { return _filter; } set { _filter = value; } } /// <summary> /// Gets or sets the include property. The include property /// specifies the items on which the command will act. /// </summary> [Parameter] public string[] Include { get { return _include; } set { _include = value; } } /// <summary> /// Gets or sets the exclude property. The exclude property /// specifies the items on which the command will not act. /// </summary> [Parameter] public string[] Exclude { get { return _exclude; } set { _exclude = value; } } /// <summary> /// The context for the command that is passed to the core command providers. /// </summary> internal CmdletProviderContext CmdletProviderContext { get { CmdletProviderContext coreCommandContext = new CmdletProviderContext(this); Collection<string> includeFilter = SessionStateUtilities.ConvertArrayToCollection<string>(Include); Collection<string> excludeFilter = SessionStateUtilities.ConvertArrayToCollection<string>(Exclude); coreCommandContext.SetFilters(includeFilter, excludeFilter, Filter); return coreCommandContext; } } // CmdletProviderContext #region brokered properties /// <summary> /// Add brokered properties for easy access to important properties /// of security descriptor /// </summary> static internal void AddBrokeredProperties( Collection<PSObject> results, bool audit, bool allCentralAccessPolicies) { foreach (PSObject result in results) { if (audit) { //Audit result.Properties.Add ( new PSCodeProperty ( "Audit", typeof(SecurityDescriptorCommandsBase).GetMethod("GetAudit") ) ); } //CentralAccessPolicyId retrieval does not require elevation, so we always add this property. result.Properties.Add ( new PSCodeProperty ( "CentralAccessPolicyId", typeof(SecurityDescriptorCommandsBase).GetMethod("GetCentralAccessPolicyId") ) ); #if !CORECLR //GetAllCentralAccessPolicies and GetCentralAccessPolicyName are not supported in OneCore powershell //because function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. if (allCentralAccessPolicies) { //AllCentralAccessPolicies result.Properties.Add ( new PSCodeProperty ( "AllCentralAccessPolicies", typeof(SecurityDescriptorCommandsBase).GetMethod("GetAllCentralAccessPolicies") ) ); } //CentralAccessPolicyName retrieval does not require elevation, so we always add this property. result.Properties.Add ( new PSCodeProperty ( "CentralAccessPolicyName", typeof(SecurityDescriptorCommandsBase).GetMethod("GetCentralAccessPolicyName") ) ); #endif } } /// <summary> /// Gets the Path of the provided PSObject. /// </summary> /// <param name="instance"> /// The PSObject for which to obtain the path. /// </param> /// <returns> /// The path of the provided PSObject. /// </returns> public static string GetPath(PSObject instance) { if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } else { // These are guaranteed to not be null, but even checking // them for null causes a presharp warning #pragma warning disable 56506 //Get path return instance.Properties["PSPath"].Value.ToString(); #pragma warning enable 56506 } } /// <summary> /// Gets the Owner of the provided PSObject. /// </summary> /// <param name="instance"> /// The PSObject for which to obtain the Owner. /// </param> /// <returns> /// The Owner of the provided PSObject. /// </returns> public static string GetOwner(PSObject instance) { if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; if (sd == null) { throw PSTraceSource.NewArgumentNullException("instance"); } //Get owner try { IdentityReference ir = sd.GetOwner(typeof(NTAccount)); return ir.ToString(); } catch (IdentityNotMappedException) { // All Acl cmdlets returning SIDs will return a string // representation of the SID in all cases where the SID // cannot be mapped to a proper user or group name. } // We are here since we cannot get IdentityReference from sd.. // So return sddl.. return sd.GetSecurityDescriptorSddlForm(AccessControlSections.Owner); } /// <summary> /// Gets the Group of the provided PSObject. /// </summary> /// <param name="instance"> /// The PSObject for which to obtain the Group. /// </param> /// <returns> /// The Group of the provided PSObject. /// </returns> public static string GetGroup(PSObject instance) { if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; if (sd == null) { throw PSTraceSource.NewArgumentNullException("instance"); } //Get Group try { IdentityReference ir = sd.GetGroup(typeof(NTAccount)); return ir.ToString(); } catch (IdentityNotMappedException) { // All Acl cmdlets returning SIDs will return a string // representation of the SID in all cases where the SID // cannot be mapped to a proper user or group name. } // We are here since we cannot get IdentityReference from sd.. // So return sddl.. return sd.GetSecurityDescriptorSddlForm(AccessControlSections.Group); } /// <summary> /// Gets the access rules of the provided PSObject. /// </summary> /// <param name="instance"> /// The PSObject for which to obtain the access rules. /// </param> /// <returns> /// The access rules of the provided PSObject. /// </returns> public static AuthorizationRuleCollection GetAccess(PSObject instance) { if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; if (sd == null) { PSTraceSource.NewArgumentException("instance"); } //Get DACL AuthorizationRuleCollection dacl; CommonObjectSecurity cos = sd as CommonObjectSecurity; if (cos != null) { dacl = cos.GetAccessRules(true, true, typeof(NTAccount)); } else { DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity; Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); dacl = dos.GetAccessRules(true, true, typeof(NTAccount)); } return dacl; } /// <summary> /// Gets the audit rules of the provided PSObject. /// </summary> /// <param name="instance"> /// The PSObject for which to obtain the audit rules. /// </param> /// <returns> /// The audit rules of the provided PSObject. /// </returns> public static AuthorizationRuleCollection GetAudit(PSObject instance) { if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; if (sd == null) { PSTraceSource.NewArgumentException("instance"); } AuthorizationRuleCollection sacl; CommonObjectSecurity cos = sd as CommonObjectSecurity; if (cos != null) { sacl = cos.GetAuditRules(true, true, typeof(NTAccount)); } else { DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity; Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); sacl = dos.GetAuditRules(true, true, typeof(NTAccount)); } return sacl; } /// <summary> /// Gets the central access policy ID of the provided PSObject. /// </summary> /// <param name="instance"> /// The PSObject for which to obtain the central access policy ID. /// </param> /// <returns> /// The central access policy ID of the provided PSObject. /// </returns> public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) { SessionState sessionState = new SessionState(); string path = sessionState.Path.GetUnresolvedProviderPathFromPSPath( GetPath(instance)); IntPtr pOwner = IntPtr.Zero, pGroup = IntPtr.Zero; IntPtr pDacl = IntPtr.Zero, pSacl = IntPtr.Zero, pSd = IntPtr.Zero; try { // Get the file's SACL containing the CAPID ACE. uint rs = NativeMethods.GetNamedSecurityInfo( path, NativeMethods.SeObjectType.SE_FILE_OBJECT, NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION, out pOwner, out pGroup, out pDacl, out pSacl, out pSd); if (rs != NativeMethods.ERROR_SUCCESS) { throw new Win32Exception((int)rs); } if (pSacl == IntPtr.Zero) { return null; } NativeMethods.ACL sacl = new NativeMethods.ACL(); sacl = ClrFacade.PtrToStructure<NativeMethods.ACL>(pSacl); if (sacl.AceCount == 0) { return null; } // Extract the first CAPID from the SACL that does not have INHERIT_ONLY_ACE flag set. IntPtr pAce = pSacl + Marshal.SizeOf(new NativeMethods.ACL()); for (uint aceIdx = 0; aceIdx < sacl.AceCount; aceIdx++) { NativeMethods.ACE_HEADER ace = new NativeMethods.ACE_HEADER(); ace = ClrFacade.PtrToStructure<NativeMethods.ACE_HEADER>(pAce); Dbg.Diagnostics.Assert(ace.AceType == NativeMethods.SYSTEM_SCOPED_POLICY_ID_ACE_TYPE, "Unexpected ACE type: " + ace.AceType.ToString(CultureInfo.CurrentCulture)); if ((ace.AceFlags & NativeMethods.INHERIT_ONLY_ACE) == 0) { break; } pAce += ace.AceSize; } IntPtr pSid = pAce + Marshal.SizeOf(new NativeMethods.SYSTEM_AUDIT_ACE()) - Marshal.SizeOf(new uint()); bool ret = NativeMethods.IsValidSid(pSid); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return new SecurityIdentifier(pSid); } finally { NativeMethods.LocalFree(pSd); } } #if !CORECLR /// <summary> /// Gets the central access policy name of the provided PSObject. /// </summary> /// <remarks> /// Function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. /// </remarks> /// <param name="instance"> /// The PSObject for which to obtain the central access policy name. /// </param> /// <returns> /// The central access policy name of the provided PSObject. /// </returns> public static string GetCentralAccessPolicyName(PSObject instance) { SecurityIdentifier capId = GetCentralAccessPolicyId(instance); if (capId == null) { return null; // file does not have the scope ace } int capIdSize = capId.BinaryLength; byte[] capIdArray = new byte[capIdSize]; capId.GetBinaryForm(capIdArray, 0); IntPtr caps = IntPtr.Zero; IntPtr pCapId = Marshal.AllocHGlobal(capIdSize); try { // Retrieve the CAP by CAPID. Marshal.Copy(capIdArray, 0, pCapId, capIdSize); IntPtr[] ppCapId = new IntPtr[1]; ppCapId[0] = pCapId; uint capCount = 0; uint rs = NativeMethods.LsaQueryCAPs( ppCapId, 1, out caps, out capCount); if (rs != NativeMethods.STATUS_SUCCESS) { throw new Win32Exception((int)rs); } if (capCount == 0 || caps == IntPtr.Zero) { return null; } // Get the CAP name. NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY(); cap = ClrFacade.PtrToStructure<NativeMethods.CENTRAL_ACCESS_POLICY>(caps); // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. return Marshal.PtrToStringUni(cap.Name.Buffer, cap.Name.Length / 2); } finally { Marshal.FreeHGlobal(pCapId); uint rs = NativeMethods.LsaFreeMemory(caps); Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS, "LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture)); } } /// <summary> /// Gets the names and IDs of all central access policies available on the machine. /// </summary> /// <remarks> /// Function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. /// </remarks> /// <param name="instance"> /// The PSObject argument is ignored. /// </param> /// <returns> /// The names and IDs of all central access policies available on the machine. /// </returns> public static string[] GetAllCentralAccessPolicies(PSObject instance) { IntPtr caps = IntPtr.Zero; try { // Retrieve all CAPs. uint capCount = 0; uint rs = NativeMethods.LsaQueryCAPs( null, 0, out caps, out capCount); if (rs != NativeMethods.STATUS_SUCCESS) { throw new Win32Exception((int)rs); } Dbg.Diagnostics.Assert(capCount < 0xFFFF, "Too many central access policies"); if (capCount == 0 || caps == IntPtr.Zero) { return null; } // Add CAP names and IDs to a string array. string[] policies = new string[capCount]; NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY(); IntPtr capPtr = caps; for (uint capIdx = 0; capIdx < capCount; capIdx++) { // Retrieve CAP name. Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero, "Invalid central access policies array"); cap = ClrFacade.PtrToStructure<NativeMethods.CENTRAL_ACCESS_POLICY>(capPtr); // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. policies[capIdx] = "\"" + Marshal.PtrToStringUni( cap.Name.Buffer, cap.Name.Length / 2) + "\""; // Retrieve CAPID. IntPtr pCapId = cap.CAPID; Dbg.Diagnostics.Assert(pCapId != IntPtr.Zero, "Invalid central access policies array"); bool ret = NativeMethods.IsValidSid(pCapId); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } SecurityIdentifier sid = new SecurityIdentifier(pCapId); policies[capIdx] += " (" + sid.ToString() + ")"; capPtr += Marshal.SizeOf(cap); } return policies; } finally { uint rs = NativeMethods.LsaFreeMemory(caps); Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS, "LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture)); } } #endif /// <summary> /// Gets the security descriptor (in SDDL form) of the /// provided PSObject. SDDL form is the Security Descriptor /// Definition Language. /// </summary> /// <param name="instance"> /// The PSObject for which to obtain the security descriptor. /// </param> /// <returns> /// The security descriptor of the provided PSObject, in SDDL form. /// </returns> public static string GetSddl(PSObject instance) { if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; if (sd == null) { throw PSTraceSource.NewArgumentNullException("instance"); } string sddl = sd.GetSecurityDescriptorSddlForm(AccessControlSections.All); return sddl; } #endregion brokered properties /// <summary> /// The filter to be used to when globbing to get the item. /// </summary> private string _filter; /// <summary> /// The glob string used to determine which items are included. /// </summary> private string[] _include = new string[0]; /// <summary> /// The glob string used to determine which items are excluded. /// </summary> private string[] _exclude = new string[0]; } /// <summary> /// Defines the implementation of the 'get-acl' cmdlet. /// This cmdlet gets the security descriptor of an item at the specified path. /// </summary> [Cmdlet(VerbsCommon.Get, "Acl", SupportsTransactions = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113305")] public sealed class GetAclCommand : SecurityDescriptorCommandsBase { /// <summary> /// Initializes a new instance of the GetAclCommand /// class. Sets the default path to the current location. /// </summary> public GetAclCommand() { //Default for path is the current location _path = new string[] { "." }; } #region parameters private string[] _path; /// <summary> /// Gets or sets the path of the item for which to obtain the /// security descriptor. Default is the current location. /// </summary> [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] [ValidateNotNullOrEmpty()] public string[] Path { get { return _path; } set { _path = value; } } private PSObject _inputObject = null; /// <summary> /// InputObject Parameter /// Gets or sets the inputObject for which to obtain the security descriptor /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ByInputObject")] public PSObject InputObject { get { return _inputObject; } set { _inputObject = value; } } /// <summary> /// Gets or sets the literal path of the item for which to obtain the /// security descriptor. Default is the current location. /// </summary> [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath")] [ValidateNotNullOrEmpty()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { get { return _path; } set { _path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// Gets or sets the audit flag of the command. This flag /// determines if audit rules should also be retrieved. /// </summary> [Parameter()] public SwitchParameter Audit { get { return _audit; } set { _audit = value; } } private SwitchParameter _audit; #if CORECLR /// <summary> /// Parameter '-AllCentralAccessPolicies' is not supported in OneCore powershell, /// because function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. /// </summary> private SwitchParameter AllCentralAccessPolicies { get; set; } #else /// <summary> /// Gets or sets the AllCentralAccessPolicies flag of the command. This flag /// determines whether the information about all central access policies /// available on the machine should be displayed. /// </summary> [Parameter()] public SwitchParameter AllCentralAccessPolicies { get { return allCentralAccessPolicies; } set { allCentralAccessPolicies = value; } } private SwitchParameter allCentralAccessPolicies; #endif #endregion /// <summary> /// Processes records from the input pipeline. /// For each input file, the command retrieves its /// corresponding security descriptor. /// </summary> protected override void ProcessRecord() { Collection<PSObject> sd = null; AccessControlSections sections = AccessControlSections.Owner | AccessControlSections.Group | AccessControlSections.Access; if (_audit) { sections |= AccessControlSections.Audit; } if (_inputObject != null) { PSMethodInfo methodInfo = _inputObject.Methods["GetSecurityDescriptor"]; if (methodInfo != null) { object customDescriptor = null; try { customDescriptor = PSObject.Base(methodInfo.Invoke()); if (!(customDescriptor is FileSystemSecurity)) { customDescriptor = new CommonSecurityDescriptor(false, false, customDescriptor.ToString()); } } catch (Exception e) { // Calling user code, Catch-all OK CommandProcessorBase.CheckForSevereException(e); ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.MethodInvokeFail, "GetAcl_OperationNotSupported" ); WriteError(er); return; } WriteObject(customDescriptor, true); } else { ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.GetMethodNotFound, "GetAcl_OperationNotSupported" ); WriteError(er); } } else { foreach (string p in Path) { List<string> pathsToProcess = new List<string>(); string currentPath = null; try { if (_isLiteralPath) { pathsToProcess.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); } else { Collection<PathInfo> resolvedPaths = SessionState.Path.GetResolvedPSPathFromPSPath(p, CmdletProviderContext); foreach (PathInfo pi in resolvedPaths) { pathsToProcess.Add(pi.Path); } } foreach (string rp in pathsToProcess) { currentPath = rp; CmdletProviderContext context = new CmdletProviderContext(this.Context); context.SuppressWildcardExpansion = true; if (!InvokeProvider.Item.Exists(rp, false, _isLiteralPath)) { ErrorRecord er = SecurityUtils.CreatePathNotFoundErrorRecord( rp, "GetAcl_PathNotFound" ); WriteError(er); continue; } InvokeProvider.SecurityDescriptor.Get(rp, sections, context); sd = context.GetAccumulatedObjects(); if (sd != null) { AddBrokeredProperties( sd, _audit, AllCentralAccessPolicies); WriteObject(sd, true); } } } catch (NotSupportedException) { ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.OperationNotSupportedOnPath, "GetAcl_OperationNotSupported", currentPath ); WriteError(er); } catch (ItemNotFoundException) { ErrorRecord er = SecurityUtils.CreatePathNotFoundErrorRecord( p, "GetAcl_PathNotFound_Exception" ); WriteError(er); continue; } } } } } // class GetAclCommand : PSCmdlet /// <summary> /// Defines the implementation of the 'set-acl' cmdlet. /// This cmdlet sets the security descriptor of an item at the specified path. /// </summary> [Cmdlet(VerbsCommon.Set, "Acl", SupportsShouldProcess = true, SupportsTransactions = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113389")] public sealed class SetAclCommand : SecurityDescriptorCommandsBase { private string[] _path; /// <summary> /// Gets or sets the path of the item for which to set the /// security descriptor. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] public string[] Path { get { return _path; } set { _path = value; } } private PSObject _inputObject = null; /// <summary> /// InputObject Parameter /// Gets or sets the inputObject for which to set the security descriptor /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByInputObject")] public PSObject InputObject { get { return _inputObject; } set { _inputObject = value; } } /// <summary> /// Gets or sets the literal path of the item for which to set the /// security descriptor. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { get { return _path; } set { _path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; private object _securityDescriptor; /// <summary> /// Gets or sets the security descriptor object to be /// set on the target item(s). /// </summary> [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByPath")] [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByLiteralPath")] [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByInputObject")] public object AclObject { get { return _securityDescriptor; } set { _securityDescriptor = PSObject.Base(value); } } #if CORECLR /// <summary> /// Parameter '-CentralAccessPolicy' is not supported in OneCore powershell, /// because function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. /// </summary> private string CentralAccessPolicy { get; set; } #else private string centralAccessPolicy; /// <summary> /// Gets or sets the central access policy to be /// set on the target item(s). /// </summary> [Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] [Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] public string CentralAccessPolicy { get { return centralAccessPolicy; } set { centralAccessPolicy = value; } } #endif private SwitchParameter _clearCentralAccessPolicy; /// <summary> /// Clears the central access policy applied on the target item(s). /// </summary> [Parameter(Mandatory = false, ParameterSetName = "ByPath")] [Parameter(Mandatory = false, ParameterSetName = "ByLiteralPath")] public SwitchParameter ClearCentralAccessPolicy { get { return _clearCentralAccessPolicy; } set { _clearCentralAccessPolicy = value; } } private SwitchParameter _passthru; /// <summary> /// Gets or sets the Passthru flag for the operation. /// If true, the security descriptor is also passed /// down the output pipeline. /// </summary> [Parameter()] public SwitchParameter Passthru { get { return _passthru; } set { _passthru = value; } } /// <summary> /// Returns a newly allocated SACL with no ACEs in it. /// Free the returned SACL by calling Marshal.FreeHGlobal. /// </summary> private IntPtr GetEmptySacl() { IntPtr pSacl = IntPtr.Zero; bool ret = true; try { // Calculate the size of the empty SACL, align to DWORD. uint saclSize = (uint)(Marshal.SizeOf(new NativeMethods.ACL()) + Marshal.SizeOf(new uint()) - 1) & 0xFFFFFFFC; Dbg.Diagnostics.Assert(saclSize < 0xFFFF, "Acl size must be less than max SD size of 0xFFFF"); // Allocate and initialize the SACL. pSacl = Marshal.AllocHGlobal((int)saclSize); ret = NativeMethods.InitializeAcl( pSacl, saclSize, NativeMethods.ACL_REVISION); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } finally { if (!ret) { Marshal.FreeHGlobal(pSacl); pSacl = IntPtr.Zero; } } return pSacl; } /// <summary> /// Returns a newly allocated SACL with the supplied CAPID in it. /// Free the returned SACL by calling Marshal.FreeHGlobal. /// </summary> /// <remarks> /// Function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. /// So the parameter "-CentralAccessPolicy" is not supported on OneCore powershell, /// and thus this method won't be hit in OneCore powershell. /// </remarks> private IntPtr GetSaclWithCapId(string capStr) { IntPtr pCapId = IntPtr.Zero, pSacl = IntPtr.Zero; IntPtr caps = IntPtr.Zero; bool ret = true, freeCapId = true; uint rs = NativeMethods.STATUS_SUCCESS; try { // Convert the supplied SID from string to binary form. ret = NativeMethods.ConvertStringSidToSid(capStr, out pCapId); if (!ret) { // We may have got a CAP friendly name instead of CAPID. // Enumerate all CAPs on the system and try to find one with // a matching friendly name. // If we retrieve the CAPID from the LSA, the CAPID need not // be deallocated separately (but with the entire buffer // returned by LsaQueryCAPs). freeCapId = false; uint capCount = 0; rs = NativeMethods.LsaQueryCAPs( null, 0, out caps, out capCount); if (rs != NativeMethods.STATUS_SUCCESS) { throw new Win32Exception((int)rs); } Dbg.Diagnostics.Assert(capCount < 0xFFFF, "Too many central access policies"); if (capCount == 0 || caps == IntPtr.Zero) { return IntPtr.Zero; } // Find the supplied string among available CAP names, use the corresponding CAPID. NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY(); IntPtr capPtr = caps; for (uint capIdx = 0; capIdx < capCount; capIdx++) { Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero, "Invalid central access policies array"); cap = ClrFacade.PtrToStructure<NativeMethods.CENTRAL_ACCESS_POLICY>(capPtr); // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. string capName = Marshal.PtrToStringUni( cap.Name.Buffer, cap.Name.Length / 2); if (capName.Equals(capStr, StringComparison.OrdinalIgnoreCase)) { pCapId = cap.CAPID; break; } capPtr += Marshal.SizeOf(cap); } } if (pCapId == IntPtr.Zero) { Exception e = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyIdentifier); WriteError(new ErrorRecord( e, "SetAcl_CentralAccessPolicy", ErrorCategory.InvalidArgument, AclObject)); return IntPtr.Zero; } ret = NativeMethods.IsValidSid(pCapId); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } uint sidSize = NativeMethods.GetLengthSid(pCapId); // Calculate the size of the SACL with one CAPID ACE, align to DWORD. uint saclSize = (uint)(Marshal.SizeOf(new NativeMethods.ACL()) + Marshal.SizeOf(new NativeMethods.SYSTEM_AUDIT_ACE()) + sidSize - 1) & 0xFFFFFFFC; Dbg.Diagnostics.Assert(saclSize < 0xFFFF, "Acl size must be less than max SD size of 0xFFFF"); // Allocate and initialize the SACL. pSacl = Marshal.AllocHGlobal((int)saclSize); ret = NativeMethods.InitializeAcl( pSacl, saclSize, NativeMethods.ACL_REVISION); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Add CAPID to the SACL. rs = NativeMethods.RtlAddScopedPolicyIDAce( pSacl, NativeMethods.ACL_REVISION, NativeMethods.SUB_CONTAINERS_AND_OBJECTS_INHERIT, 0, pCapId); if (rs != NativeMethods.STATUS_SUCCESS) { if (rs == NativeMethods.STATUS_INVALID_PARAMETER) { throw new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyIdentifier); } else { throw new Win32Exception((int)rs); } } } finally { if (!ret || rs != NativeMethods.STATUS_SUCCESS) { Marshal.FreeHGlobal(pSacl); pSacl = IntPtr.Zero; } rs = NativeMethods.LsaFreeMemory(caps); Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS, "LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture)); if (freeCapId) { NativeMethods.LocalFree(pCapId); } } return pSacl; } /// <summary> /// Returns the current thread or process token with the specified privilege enabled /// and the previous state of this privilege. Free the returned token /// by calling NativeMethods.CloseHandle. /// </summary> private IntPtr GetTokenWithEnabledPrivilege( string privilege, NativeMethods.TOKEN_PRIVILEGE previousState) { IntPtr pToken = IntPtr.Zero; bool ret = true; try { // First try to open the thread token for privilege adjustment. ret = NativeMethods.OpenThreadToken( NativeMethods.GetCurrentThread(), NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_ADJUST_PRIVILEGES, true, out pToken); if (!ret) { if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_NO_TOKEN) { // Client is not impersonating. Open the process token. ret = NativeMethods.OpenProcessToken( NativeMethods.GetCurrentProcess(), NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_ADJUST_PRIVILEGES, out pToken); } if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } // Get the LUID of the specified privilege. NativeMethods.LUID luid = new NativeMethods.LUID(); ret = NativeMethods.LookupPrivilegeValue( null, privilege, ref luid); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Enable the privilege. NativeMethods.TOKEN_PRIVILEGE newState = new NativeMethods.TOKEN_PRIVILEGE(); newState.PrivilegeCount = 1; newState.Privilege.Attributes = NativeMethods.SE_PRIVILEGE_ENABLED; newState.Privilege.Luid = luid; uint previousSize = 0; ret = NativeMethods.AdjustTokenPrivileges( pToken, false, ref newState, (uint)Marshal.SizeOf(previousState), ref previousState, ref previousSize); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } finally { if (!ret) { NativeMethods.CloseHandle(pToken); pToken = IntPtr.Zero; } } return pToken; } /// Processes records from the input pipeline. /// For each input file, the command sets its /// security descriptor to the specified /// Access Control List (ACL). protected override void ProcessRecord() { ObjectSecurity aclObjectSecurity = _securityDescriptor as ObjectSecurity; if (_inputObject != null) { PSMethodInfo methodInfo = _inputObject.Methods["SetSecurityDescriptor"]; if (methodInfo != null) { CommonSecurityDescriptor aclCommonSD = _securityDescriptor as CommonSecurityDescriptor; string sddl; if (aclObjectSecurity != null) { sddl = aclObjectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All); } else if (aclCommonSD != null) { sddl = aclCommonSD.GetSddlForm(AccessControlSections.All); } else { Exception e = new ArgumentException("AclObject"); WriteError(new ErrorRecord( e, "SetAcl_AclObject", ErrorCategory.InvalidArgument, AclObject)); return; } try { methodInfo.Invoke(sddl); } catch (Exception e) { // Calling user code, Catch-all OK CommandProcessorBase.CheckForSevereException(e); ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.MethodInvokeFail, "SetAcl_OperationNotSupported" ); WriteError(er); return; } } else { ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.SetMethodNotFound, "SetAcl_OperationNotSupported" ); WriteError(er); } } else { if (Path == null) { Exception e = new ArgumentException("Path"); WriteError(new ErrorRecord( e, "SetAcl_Path", ErrorCategory.InvalidArgument, AclObject)); return; } if (aclObjectSecurity == null) { Exception e = new ArgumentException("AclObject"); WriteError(new ErrorRecord( e, "SetAcl_AclObject", ErrorCategory.InvalidArgument, AclObject)); return; } if (CentralAccessPolicy != null || ClearCentralAccessPolicy) { if (!DownLevelHelper.IsWin8AndAbove()) { Exception e = new ParameterBindingException(); WriteError(new ErrorRecord( e, "SetAcl_OperationNotSupported", ErrorCategory.InvalidArgument, null)); return; } } if (CentralAccessPolicy != null && ClearCentralAccessPolicy) { Exception e = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyParameters); ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord( e, "SetAcl_OperationNotSupported" ); WriteError(er); return; } IntPtr pSacl = IntPtr.Zero; NativeMethods.TOKEN_PRIVILEGE previousState = new NativeMethods.TOKEN_PRIVILEGE(); try { if (CentralAccessPolicy != null) { pSacl = GetSaclWithCapId(CentralAccessPolicy); if (pSacl == IntPtr.Zero) { SystemException e = new SystemException( UtilsStrings.GetSaclWithCapIdFail); WriteError(new ErrorRecord(e, "SetAcl_CentralAccessPolicy", ErrorCategory.InvalidResult, null)); return; } } else if (ClearCentralAccessPolicy) { pSacl = GetEmptySacl(); if (pSacl == IntPtr.Zero) { SystemException e = new SystemException( UtilsStrings.GetEmptySaclFail); WriteError(new ErrorRecord(e, "SetAcl_ClearCentralAccessPolicy", ErrorCategory.InvalidResult, null)); return; } } foreach (string p in Path) { Collection<PathInfo> pathsToProcess = new Collection<PathInfo>(); CmdletProviderContext context = this.CmdletProviderContext; context.PassThru = Passthru; if (_isLiteralPath) { ProviderInfo Provider = null; PSDriveInfo Drive = null; string pathStr = SessionState.Path.GetUnresolvedProviderPathFromPSPath(p, out Provider, out Drive); pathsToProcess.Add(new PathInfo(Drive, Provider, pathStr, SessionState)); context.SuppressWildcardExpansion = true; } else { pathsToProcess = SessionState.Path.GetResolvedPSPathFromPSPath(p, CmdletProviderContext); } foreach (PathInfo pathInfo in pathsToProcess) { if (ShouldProcess(pathInfo.Path)) { try { InvokeProvider.SecurityDescriptor.Set(pathInfo.Path, aclObjectSecurity, context); if (CentralAccessPolicy != null || ClearCentralAccessPolicy) { if (!pathInfo.Provider.NameEquals(Context.ProviderNames.FileSystem)) { Exception e = new ArgumentException("Path"); WriteError(new ErrorRecord( e, "SetAcl_Path", ErrorCategory.InvalidArgument, AclObject)); continue; } // Enable the security privilege required to set SCOPE_SECURITY_INFORMATION. IntPtr pToken = GetTokenWithEnabledPrivilege("SeSecurityPrivilege", previousState); if (pToken == IntPtr.Zero) { SystemException e = new SystemException( UtilsStrings.GetTokenWithEnabledPrivilegeFail); WriteError(new ErrorRecord(e, "SetAcl_AdjustTokenPrivileges", ErrorCategory.InvalidResult, null)); return; } // Set the file's CAPID. uint rs = NativeMethods.SetNamedSecurityInfo( pathInfo.ProviderPath, NativeMethods.SeObjectType.SE_FILE_OBJECT, NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, pSacl); // Restore privileges to the previous state. if (pToken != IntPtr.Zero) { NativeMethods.TOKEN_PRIVILEGE newState = new NativeMethods.TOKEN_PRIVILEGE(); uint newSize = 0; NativeMethods.AdjustTokenPrivileges( pToken, false, ref previousState, (uint)Marshal.SizeOf(newState), ref newState, ref newSize); NativeMethods.CloseHandle(pToken); pToken = IntPtr.Zero; } if (rs != NativeMethods.ERROR_SUCCESS) { Exception e = new Win32Exception( (int)rs, UtilsStrings.SetCentralAccessPolicyFail); WriteError(new ErrorRecord(e, "SetAcl_SetNamedSecurityInfo", ErrorCategory.InvalidResult, null)); } } } catch (NotSupportedException) { ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.OperationNotSupportedOnPath, "SetAcl_OperationNotSupported", pathInfo.Path ); WriteError(er); } } } } } finally { Marshal.FreeHGlobal(pSacl); } } } } // class SetAclCommand }// namespace Microsoft.PowerShell.Commands #pragma warning restore 56506
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Mirage.Urbanization.Simulation; using Mirage.Urbanization.Simulation.Datameters; using Mirage.Urbanization.Tilesets; using Mirage.Urbanization.Web.ClientMessages; namespace Mirage.Urbanization.Web { public struct ClientDataMeterZoneInfo { public static ClientDataMeterZoneInfo Create(IReadOnlyZoneInfo zoneInfo, ZoneInfoDataMeter zoneInfoDataMeter) { return new ClientDataMeterZoneInfo { colour = DatameterColourDefinitions .Instance .GetColorFor(zoneInfoDataMeter.GetDataMeterResult(zoneInfo).ValueCategory) .Pipe(x => x.HasValue ? x.Value.ToHex() : string.Empty), x = zoneInfo.Point.X, y = zoneInfo.Point.Y }; } public int x { get; set; } public int y { get; set; } public string colour { get; set; } } public class DataMeterPublishState { public ZoneInfoDataMeter DataMeter { get; } private readonly Func<IEnumerable<IReadOnlyZoneInfo>> _getZoneInfos; public DataMeterPublishState(ZoneInfoDataMeter dataMeter, Func<IEnumerable<IReadOnlyZoneInfo>> getZoneInfos) { DataMeter = dataMeter; _getZoneInfos = getZoneInfos; } public IEnumerable<ClientDataMeterZoneInfo> GetChanged() { var currentClientDataMeterStates = _getZoneInfos() .Select(x => ClientDataMeterZoneInfo.Create(x, DataMeter)) .ToHashSet(); foreach (var x in currentClientDataMeterStates .Except(_previousClientDataMeterStates)) yield return x; _previousClientDataMeterStates = currentClientDataMeterStates; } private ISet<ClientDataMeterZoneInfo> _previousClientDataMeterStates = new HashSet<ClientDataMeterZoneInfo>(); } public class DataMeterPublishStateManager { public IList<DataMeterPublishState> DataMeterPublishStates { get; } public DataMeterPublishStateManager(ISimulationSession session) { DataMeterPublishStates = DataMeterInstances .DataMeters .Select(x => new DataMeterPublishState(x, session.Area.EnumerateZoneInfos)) .ToList(); } } public class GameServer : IDisposable { public static GameServer Instance; private readonly ISimulationSession _simulationSession; private readonly string _url; private readonly bool _controlVehicles; private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private readonly NeverEndingTask _looper, _dataMeterStateLooper; public ISimulationSession SimulationSession => _simulationSession; public GameServer(ISimulationSession simulationSession, string url, bool controlVehicles) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentException("", nameof(url)); _simulationSession = simulationSession ?? throw new ArgumentNullException(nameof(simulationSession)); _url = url; _controlVehicles = controlVehicles; List<ClientZoneInfo> previous = null; _simulationSession.OnAreaMessage += SimulationSession_OnAreaMessage; _simulationSession.OnYearAndOrMonthChanged += SimulationSession_OnYearAndOrMonthChanged; _simulationSession.OnCityBudgetValueChanged += SimulationSession_OnCityBudgetValueChanged; _simulationSession.OnAreaHotMessage += SimulationSession_OnAreaHotMessage; var zoneInfoBatchLooper = new LoopBatchEnumerator<IReadOnlyZoneInfo>(_simulationSession.Area.EnumerateZoneInfos().ToList()); var dataMeterStateManager = new DataMeterPublishStateManager(simulationSession); _dataMeterStateLooper = new NeverEndingTask("Data meter state submission", async () => { foreach (var x in dataMeterStateManager.DataMeterPublishStates) { await Startup.WithSimulationHub(async hub => { foreach (var batch in x.GetChanged().GetBatched(100)) { await hub .Clients .Group(SimulationHub.GetDataMeterGroupName(x.DataMeter.WebId)) .SendAsync("submitDataMeterInfos", batch); } }); } }, _cancellationTokenSource.Token, 10); _looper = new NeverEndingTask("SignalR Game state submission", async () => { await Startup.WithSimulationHub(async simulationHub => { await simulationHub .Clients .All .SendAsync("submitZoneInfos", zoneInfoBatchLooper.GetBatch().Select(ClientZoneInfo.Create), _cancellationTokenSource.Token); var zoneInfos = _simulationSession.Area.EnumerateZoneInfos() .Select(ClientZoneInfo.Create) .ToList(); var toBeSubmitted = zoneInfos; if (previous != null) { var previousUids = previous.Select(x => x.GetIdentityString()).ToHashSet(); toBeSubmitted = zoneInfos.Where(z => !previousUids.Contains(z.GetIdentityString())).ToList(); } foreach (var toBeSubmittedBatch in toBeSubmitted.GetBatched(20)) { await simulationHub .Clients .All .SendAsync("submitZoneInfos", toBeSubmittedBatch); } previous = zoneInfos; try { var list = new List<ClientVehiclePositionInfo>(); foreach (var vehicleController in _simulationSession.Area.EnumerateVehicleControllers()) { vehicleController .ForEachActiveVehicle(_controlVehicles, vehicle => { list.AddRange(TilesetProvider .GetBitmapsAndPointsFor(vehicle) .Select(ClientVehiclePositionInfo.Create) ); }); } await simulationHub .Clients .All .SendAsync("submitVehicleStates", list); } catch (Exception ex) { Logger.Instance.WriteLine("Possible race condition-based exception:: " + ex); } }); }, _cancellationTokenSource.Token, 10); if (Instance == null) Instance = this; else throw new InvalidOperationException(); } private async void SimulationSession_OnAreaHotMessage(object sender, SimulationSessionHotMessageEventArgs e) { try { await Startup.WithSimulationHub(async simulationHub => { await simulationHub .Clients .All .SendAsync("submitAreaHotMessage", new { title = e.Title, message = e.Message }); }); } catch (Exception ex) { Logger.Instance.WriteLine(ex); } } private readonly CityBudgetPanelPublisher _cityBudgetPanelPublisher = new CityBudgetPanelPublisher(); private async void SimulationSession_OnCityBudgetValueChanged(object sender, CityBudgetValueChangedEventArgs e) { try { await Startup.WithSimulationHub(async simulationHub => { await simulationHub .Clients .All .SendAsync("submitCityBudgetValue", new { cityBudgetState = _cityBudgetPanelPublisher.GenerateCityBudgetState(_simulationSession), currentAmount = e.EventData.CurrentAmount, projectedIncome = e.EventData.ProjectedIncome }); }); } catch (Exception ex) { Logger.Instance.WriteLine(ex); } } private async void SimulationSession_OnYearAndOrMonthChanged(object sender, EventArgsWithData<IYearAndMonth> e) { try { await Startup.WithSimulationHub(async simulationHub => { await SimulationSession.GetRecentStatistics().WithResultIfHasMatch(cityStatistics => { var cityStatisticsView = new CityStatisticsView(cityStatistics); return simulationHub .Clients .All .SendAsync("onYearAndMonthChanged", new YearAndMonthChangedState { yearAndMonthDescription = e.EventData.GetCurrentDescription(), overallLabelsAndValues = new[] { new LabelAndValue { label = "Population", value = cityStatisticsView.Population.ToString("N0") }, new LabelAndValue { label = "Assessed value", value = cityStatisticsView.AssessedValue.ToString("C0") }, new LabelAndValue { label = "Category", value = cityStatisticsView.CityCategory } }, generalOpinion = new[] { new { Opinion = cityStatisticsView.GetPositiveOpinion(), Label = "Positive" }, new { Opinion = cityStatisticsView.GetNegativeOpinion(), Label = "Negative" } } .OrderByDescending(y => y.Opinion) .Select(y => new LabelAndValue { label = $"{y.Label}", value = $"{y.Opinion:P1}" }) .ToArray(), cityBudgetLabelsAndValues = new[] { new LabelAndValue { label = "Current funds", value = cityStatisticsView.CurrentAmountOfFunds.ToString()}, new LabelAndValue { label = "Projected income", value = cityStatisticsView.CurrentProjectedAmountOfFunds.ToString()}, }, issueLabelAndValues = cityStatisticsView .GetIssueDataMeterResults() .Select(x => new LabelAndValue() { label = x.Name, value = $"{x.ValueCategory} ({x.PercentageScoreString}%)" }) .ToArray() }); }); }); } catch (Exception ex) { Logger.Instance.WriteLine(ex); } } private static async void SimulationSession_OnAreaMessage(object sender, SimulationSessionMessageEventArgs e) { try { await Startup.WithSimulationHub(async simulationHub => { await simulationHub .Clients .All .SendAsync("submitAreaMessage", e.Message); }); } catch (Exception ex) { Logger.Instance.WriteLine(ex); } } public void StartServer() { _looper.Start(); _dataMeterStateLooper.Start(); } public void Dispose() { _simulationSession.OnAreaMessage -= SimulationSession_OnAreaMessage; _simulationSession.OnYearAndOrMonthChanged -= SimulationSession_OnYearAndOrMonthChanged; _simulationSession.OnCityBudgetValueChanged -= SimulationSession_OnCityBudgetValueChanged; _simulationSession.OnAreaHotMessage -= SimulationSession_OnAreaHotMessage; _cancellationTokenSource.Cancel(); _looper.Wait(); _dataMeterStateLooper.Wait(); Instance = null; } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Data; using Nop.Core.Domain.Blogs; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Stores; using Nop.Services.Events; namespace Nop.Services.Blogs { /// <summary> /// Blog service /// </summary> public partial class BlogService : IBlogService { #region Fields private readonly IRepository<BlogPost> _blogPostRepository; private readonly IRepository<BlogComment> _blogCommentRepository; private readonly IRepository<StoreMapping> _storeMappingRepository; private readonly CatalogSettings _catalogSettings; private readonly IEventPublisher _eventPublisher; #endregion #region Ctor public BlogService(IRepository<BlogPost> blogPostRepository, IRepository<BlogComment> blogCommentRepository, IRepository<StoreMapping> storeMappingRepository, CatalogSettings catalogSettings, IEventPublisher eventPublisher) { this._blogPostRepository = blogPostRepository; this._blogCommentRepository = blogCommentRepository; this._storeMappingRepository = storeMappingRepository; this._catalogSettings = catalogSettings; this._eventPublisher = eventPublisher; } #endregion #region Methods #region Blog posts /// <summary> /// Deletes a blog post /// </summary> /// <param name="blogPost">Blog post</param> public virtual void DeleteBlogPost(BlogPost blogPost) { if (blogPost == null) throw new ArgumentNullException("blogPost"); _blogPostRepository.Delete(blogPost); //event notification _eventPublisher.EntityDeleted(blogPost); } /// <summary> /// Gets a blog post /// </summary> /// <param name="blogPostId">Blog post identifier</param> /// <returns>Blog post</returns> public virtual BlogPost GetBlogPostById(int blogPostId) { if (blogPostId == 0) return null; return _blogPostRepository.GetById(blogPostId); } /// <summary> /// Gets blog posts /// </summary> /// <param name="blogPostIds">Blog post identifiers</param> /// <returns>Blog posts</returns> public virtual IList<BlogPost> GetBlogPostsByIds(int[] blogPostIds) { var query = _blogPostRepository.Table; return query.Where(bp => blogPostIds.Contains(bp.Id)).ToList(); } /// <summary> /// Gets all blog posts /// </summary> /// <param name="storeId">The store identifier; pass 0 to load all records</param> /// <param name="languageId">Language identifier; 0 if you want to get all records</param> /// <param name="dateFrom">Filter by created date; null if you want to get all records</param> /// <param name="dateTo">Filter by created date; null if you want to get all records</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Blog posts</returns> public virtual IPagedList<BlogPost> GetAllBlogPosts(int storeId = 0, int languageId = 0, DateTime? dateFrom = null, DateTime? dateTo = null, int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false) { var query = _blogPostRepository.Table; if (dateFrom.HasValue) query = query.Where(b => dateFrom.Value <= (b.StartDateUtc ?? b.CreatedOnUtc)); if (dateTo.HasValue) query = query.Where(b => dateTo.Value >= (b.StartDateUtc ?? b.CreatedOnUtc)); if (languageId > 0) query = query.Where(b => languageId == b.LanguageId); if (!showHidden) { //The function 'CurrentUtcDateTime' is not supported by SQL Server Compact. //That's why we pass the date value var utcNow = DateTime.UtcNow; query = query.Where(b => !b.StartDateUtc.HasValue || b.StartDateUtc <= utcNow); query = query.Where(b => !b.EndDateUtc.HasValue || b.EndDateUtc >= utcNow); } if (storeId > 0 && !_catalogSettings.IgnoreStoreLimitations) { //Store mapping query = from bp in query join sm in _storeMappingRepository.Table on new { c1 = bp.Id, c2 = "BlogPost" } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into bp_sm from sm in bp_sm.DefaultIfEmpty() where !bp.LimitedToStores || storeId == sm.StoreId select bp; //only distinct blog posts (group by ID) query = from bp in query group bp by bp.Id into bpGroup orderby bpGroup.Key select bpGroup.FirstOrDefault(); } query = query.OrderByDescending(b => b.StartDateUtc ?? b.CreatedOnUtc); var blogPosts = new PagedList<BlogPost>(query, pageIndex, pageSize); return blogPosts; } /// <summary> /// Gets all blog posts /// </summary> /// <param name="storeId">The store identifier; pass 0 to load all records</param> /// <param name="languageId">Language identifier. 0 if you want to get all blog posts</param> /// <param name="tag">Tag</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Blog posts</returns> public virtual IPagedList<BlogPost> GetAllBlogPostsByTag(int storeId = 0, int languageId = 0, string tag = "", int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false) { tag = tag.Trim(); //we load all records and only then filter them by tag var blogPostsAll = GetAllBlogPosts(storeId: storeId, languageId: languageId, showHidden: showHidden); var taggedBlogPosts = new List<BlogPost>(); foreach (var blogPost in blogPostsAll) { var tags = blogPost.ParseTags(); if (!String.IsNullOrEmpty(tags.FirstOrDefault(t => t.Equals(tag, StringComparison.InvariantCultureIgnoreCase)))) taggedBlogPosts.Add(blogPost); } //server-side paging var result = new PagedList<BlogPost>(taggedBlogPosts, pageIndex, pageSize); return result; } /// <summary> /// Gets all blog post tags /// </summary> /// <param name="storeId">The store identifier; pass 0 to load all records</param> /// <param name="languageId">Language identifier. 0 if you want to get all blog posts</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Blog post tags</returns> public virtual IList<BlogPostTag> GetAllBlogPostTags(int storeId, int languageId, bool showHidden = false) { var blogPostTags = new List<BlogPostTag>(); var blogPosts = GetAllBlogPosts(storeId: storeId, languageId: languageId, showHidden: showHidden); foreach (var blogPost in blogPosts) { var tags = blogPost.ParseTags(); foreach (string tag in tags) { var foundBlogPostTag = blogPostTags.Find(bpt => bpt.Name.Equals(tag, StringComparison.InvariantCultureIgnoreCase)); if (foundBlogPostTag == null) { foundBlogPostTag = new BlogPostTag { Name = tag, BlogPostCount = 1 }; blogPostTags.Add(foundBlogPostTag); } else foundBlogPostTag.BlogPostCount++; } } return blogPostTags; } /// <summary> /// Inserts an blog post /// </summary> /// <param name="blogPost">Blog post</param> public virtual void InsertBlogPost(BlogPost blogPost) { if (blogPost == null) throw new ArgumentNullException("blogPost"); _blogPostRepository.Insert(blogPost); //event notification _eventPublisher.EntityInserted(blogPost); } /// <summary> /// Updates the blog post /// </summary> /// <param name="blogPost">Blog post</param> public virtual void UpdateBlogPost(BlogPost blogPost) { if (blogPost == null) throw new ArgumentNullException("blogPost"); _blogPostRepository.Update(blogPost); //event notification _eventPublisher.EntityUpdated(blogPost); } #endregion #region Blog comments /// <summary> /// Gets all comments /// </summary> /// <param name="customerId">Customer identifier; 0 to load all records</param> /// <param name="storeId">Store identifier; pass 0 to load all records</param> /// <param name="blogPostId">Blog post ID; 0 or null to load all records</param> /// <param name="approved">A value indicating whether to content is approved; null to load all records</param> /// <param name="fromUtc">Item creation from; null to load all records</param> /// <param name="toUtc">Item creation to; null to load all records</param> /// <param name="commentText">Search comment text; null to load all records</param> /// <returns>Comments</returns> public virtual IList<BlogComment> GetAllComments(int customerId = 0, int storeId = 0, int? blogPostId = null, bool? approved = null, DateTime? fromUtc = null, DateTime? toUtc = null, string commentText = null) { var query = _blogCommentRepository.Table; if (approved.HasValue) query = query.Where(comment => comment.IsApproved == approved); if (blogPostId > 0) query = query.Where(comment => comment.BlogPostId == blogPostId); if (customerId > 0) query = query.Where(comment => comment.CustomerId == customerId); if (storeId > 0) query = query.Where(comment => comment.StoreId == storeId); if (fromUtc.HasValue) query = query.Where(comment => fromUtc.Value <= comment.CreatedOnUtc); if (toUtc.HasValue) query = query.Where(comment => toUtc.Value >= comment.CreatedOnUtc); if (!string.IsNullOrEmpty(commentText)) query = query.Where(c => c.CommentText.Contains(commentText)); query = query.OrderBy(comment => comment.CreatedOnUtc); return query.ToList(); } /// <summary> /// Gets a blog comment /// </summary> /// <param name="blogCommentId">Blog comment identifier</param> /// <returns>Blog comment</returns> public virtual BlogComment GetBlogCommentById(int blogCommentId) { if (blogCommentId == 0) return null; return _blogCommentRepository.GetById(blogCommentId); } /// <summary> /// Get blog comments by identifiers /// </summary> /// <param name="commentIds">Blog comment identifiers</param> /// <returns>Blog comments</returns> public virtual IList<BlogComment> GetBlogCommentsByIds(int[] commentIds) { if (commentIds == null || commentIds.Length == 0) return new List<BlogComment>(); var query = from bc in _blogCommentRepository.Table where commentIds.Contains(bc.Id) select bc; var comments = query.ToList(); //sort by passed identifiers var sortedComments = new List<BlogComment>(); foreach (int id in commentIds) { var comment = comments.Find(x => x.Id == id); if (comment != null) sortedComments.Add(comment); } return sortedComments; } /// <summary> /// Get the count of blog comments /// </summary> /// <param name="blogPost">Blog post</param> /// <param name="storeId">Store identifier; pass 0 to load all records</param> /// <param name="isApproved">A value indicating whether to count only approved or not approved comments; pass null to get number of all comments</param> /// <returns>Number of blog comments</returns> public virtual int GetBlogCommentsCount(BlogPost blogPost, int storeId = 0, bool? isApproved = null) { var query = _blogCommentRepository.Table.Where(comment => comment.BlogPostId == blogPost.Id); if (storeId > 0) query = query.Where(comment => comment.StoreId == storeId); if (isApproved.HasValue) query = query.Where(comment => comment.IsApproved == isApproved.Value); return query.Count(); } /// <summary> /// Deletes a blog comment /// </summary> /// <param name="blogComment">Blog comment</param> public virtual void DeleteBlogComment(BlogComment blogComment) { if (blogComment == null) throw new ArgumentNullException("blogComment"); _blogCommentRepository.Delete(blogComment); //event notification _eventPublisher.EntityDeleted(blogComment); } /// <summary> /// Deletes blog comments /// </summary> /// <param name="blogComments">Blog comments</param> public virtual void DeleteBlogComments(IList<BlogComment> blogComments) { if (blogComments == null) throw new ArgumentNullException("blogComments"); foreach (var blogComment in blogComments) { DeleteBlogComment(blogComment); } } #endregion #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 osu.Framework; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Scoring; using osu.Game.Screens.Ranking.Expanded; using osuTK; using osuTK.Graphics; namespace osu.Game.Screens.Ranking { public class ScorePanel : CompositeDrawable, IStateful<PanelState> { /// <summary> /// Width of the panel when contracted. /// </summary> private const float contracted_width = 160; /// <summary> /// Height of the panel when contracted. /// </summary> private const float contracted_height = 320; /// <summary> /// Width of the panel when expanded. /// </summary> private const float expanded_width = 360; /// <summary> /// Height of the panel when expanded. /// </summary> private const float expanded_height = 560; /// <summary> /// Height of the top layer when the panel is expanded. /// </summary> private const float expanded_top_layer_height = 53; /// <summary> /// Height of the top layer when the panel is contracted. /// </summary> private const float contracted_top_layer_height = 40; /// <summary> /// Duration for the panel to resize into its expanded/contracted size. /// </summary> private const double resize_duration = 200; /// <summary> /// Delay after <see cref="resize_duration"/> before the top layer is expanded. /// </summary> private const double top_layer_expand_delay = 100; /// <summary> /// Duration for the top layer expansion. /// </summary> private const double top_layer_expand_duration = 200; /// <summary> /// Duration for the panel contents to fade in. /// </summary> private const double content_fade_duration = 50; private static readonly ColourInfo expanded_top_layer_colour = ColourInfo.GradientVertical(Color4Extensions.FromHex("#444"), Color4Extensions.FromHex("#333")); private static readonly ColourInfo expanded_middle_layer_colour = ColourInfo.GradientVertical(Color4Extensions.FromHex("#555"), Color4Extensions.FromHex("#333")); private static readonly Color4 contracted_top_layer_colour = Color4Extensions.FromHex("#353535"); private static readonly Color4 contracted_middle_layer_colour = Color4Extensions.FromHex("#444"); public event Action<PanelState> StateChanged; private readonly ScoreInfo score; private Container topLayerContainer; private Drawable topLayerBackground; private Container topLayerContentContainer; private Drawable topLayerContent; private Container middleLayerContainer; private Drawable middleLayerBackground; private Container middleLayerContentContainer; private Drawable middleLayerContent; public ScorePanel(ScoreInfo score) { this.score = score; } [BackgroundDependencyLoader] private void load() { InternalChildren = new Drawable[] { topLayerContainer = new Container { Name = "Top layer", RelativeSizeAxes = Axes.X, Height = 120, Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, CornerRadius = 20, CornerExponent = 2.5f, Masking = true, Child = topLayerBackground = new Box { RelativeSizeAxes = Axes.Both } }, topLayerContentContainer = new Container { RelativeSizeAxes = Axes.Both } } }, middleLayerContainer = new Container { Name = "Middle layer", RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, CornerRadius = 20, CornerExponent = 2.5f, Masking = true, Child = middleLayerBackground = new Box { RelativeSizeAxes = Axes.Both } }, middleLayerContentContainer = new Container { RelativeSizeAxes = Axes.Both } } } }; } protected override void LoadComplete() { base.LoadComplete(); if (state == PanelState.Expanded) { topLayerBackground.FadeColour(expanded_top_layer_colour); middleLayerBackground.FadeColour(expanded_middle_layer_colour); } else { topLayerBackground.FadeColour(contracted_top_layer_colour); middleLayerBackground.FadeColour(contracted_middle_layer_colour); } updateState(); } private PanelState state = PanelState.Contracted; public PanelState State { get => state; set { if (state == value) return; state = value; if (LoadState >= LoadState.Ready) updateState(); StateChanged?.Invoke(value); } } private void updateState() { topLayerContainer.MoveToY(0, resize_duration, Easing.OutQuint); middleLayerContainer.MoveToY(0, resize_duration, Easing.OutQuint); topLayerContent?.FadeOut(content_fade_duration).Expire(); middleLayerContent?.FadeOut(content_fade_duration).Expire(); switch (state) { case PanelState.Expanded: this.ResizeTo(new Vector2(expanded_width, expanded_height), resize_duration, Easing.OutQuint); topLayerBackground.FadeColour(expanded_top_layer_colour, resize_duration, Easing.OutQuint); middleLayerBackground.FadeColour(expanded_middle_layer_colour, resize_duration, Easing.OutQuint); topLayerContentContainer.Add(middleLayerContent = new ExpandedPanelTopContent(score.User).With(d => d.Alpha = 0)); middleLayerContentContainer.Add(topLayerContent = new ExpandedPanelMiddleContent(score).With(d => d.Alpha = 0)); break; case PanelState.Contracted: this.ResizeTo(new Vector2(contracted_width, contracted_height), resize_duration, Easing.OutQuint); topLayerBackground.FadeColour(contracted_top_layer_colour, resize_duration, Easing.OutQuint); middleLayerBackground.FadeColour(contracted_middle_layer_colour, resize_duration, Easing.OutQuint); break; } using (BeginDelayedSequence(resize_duration + top_layer_expand_delay, true)) { switch (state) { case PanelState.Expanded: topLayerContainer.MoveToY(-expanded_top_layer_height / 2, top_layer_expand_duration, Easing.OutQuint); middleLayerContainer.MoveToY(expanded_top_layer_height / 2, top_layer_expand_duration, Easing.OutQuint); break; case PanelState.Contracted: topLayerContainer.MoveToY(-contracted_top_layer_height / 2, top_layer_expand_duration, Easing.OutQuint); middleLayerContainer.MoveToY(contracted_top_layer_height / 2, top_layer_expand_duration, Easing.OutQuint); break; } topLayerContent?.FadeIn(content_fade_duration); middleLayerContent?.FadeIn(content_fade_duration); } } } }
// // Copyright (c) 2004-2017 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.Conditions { using System; using System.Text; using NLog.Internal; /// <summary> /// Hand-written tokenizer for conditions. /// </summary> internal sealed class ConditionTokenizer { private static readonly ConditionTokenType[] charIndexToTokenType = BuildCharIndexToTokenType(); private readonly SimpleStringReader _stringReader; /// <summary> /// Initializes a new instance of the <see cref="ConditionTokenizer"/> class. /// </summary> /// <param name="stringReader">The string reader.</param> public ConditionTokenizer(SimpleStringReader stringReader) { _stringReader = stringReader; TokenType = ConditionTokenType.BeginningOfInput; GetNextToken(); } /// <summary> /// Gets the type of the token. /// </summary> /// <value>The type of the token.</value> public ConditionTokenType TokenType { get; private set; } /// <summary> /// Gets the token value. /// </summary> /// <value>The token value.</value> public string TokenValue { get; private set; } /// <summary> /// Gets the value of a string token. /// </summary> /// <value>The string token value.</value> public string StringTokenValue { get { string s = TokenValue; return s.Substring(1, s.Length - 2).Replace("''", "'"); } } /// <summary> /// Asserts current token type and advances to the next token. /// </summary> /// <param name="tokenType">Expected token type.</param> /// <remarks>If token type doesn't match, an exception is thrown.</remarks> public void Expect(ConditionTokenType tokenType) { if (TokenType != tokenType) { throw new ConditionParseException($"Expected token of type: {tokenType}, got {TokenType} ({TokenValue})."); } GetNextToken(); } /// <summary> /// Asserts that current token is a keyword and returns its value and advances to the next token. /// </summary> /// <returns>Keyword value.</returns> public string EatKeyword() { if (TokenType != ConditionTokenType.Keyword) { throw new ConditionParseException("Identifier expected"); } string s = TokenValue; GetNextToken(); return s; } /// <summary> /// Gets or sets a value indicating whether current keyword is equal to the specified value. /// </summary> /// <param name="keyword">The keyword.</param> /// <returns> /// A value of <c>true</c> if current keyword is equal to the specified value; otherwise, <c>false</c>. /// </returns> public bool IsKeyword(string keyword) { if (TokenType != ConditionTokenType.Keyword) { return false; } return TokenValue.Equals(keyword, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Gets or sets a value indicating whether the tokenizer has reached the end of the token stream. /// </summary> /// <returns> /// A value of <c>true</c> if the tokenizer has reached the end of the token stream; otherwise, <c>false</c>. /// </returns> public bool IsEOF() { return TokenType == ConditionTokenType.EndOfInput; } /// <summary> /// Gets or sets a value indicating whether current token is a number. /// </summary> /// <returns> /// A value of <c>true</c> if current token is a number; otherwise, <c>false</c>. /// </returns> public bool IsNumber() { return TokenType == ConditionTokenType.Number; } /// <summary> /// Gets or sets a value indicating whether the specified token is of specified type. /// </summary> /// <param name="tokenType">The token type.</param> /// <returns> /// A value of <c>true</c> if current token is of specified type; otherwise, <c>false</c>. /// </returns> public bool IsToken(ConditionTokenType tokenType) { return TokenType == tokenType; } /// <summary> /// Gets the next token and sets <see cref="TokenType"/> and <see cref="TokenValue"/> properties. /// </summary> public void GetNextToken() { if (TokenType == ConditionTokenType.EndOfInput) { throw new ConditionParseException("Cannot read past end of stream."); } SkipWhitespace(); int i = PeekChar(); if (i == -1) { TokenType = ConditionTokenType.EndOfInput; return; } char ch = (char)i; if (char.IsDigit(ch)) { ParseNumber(ch); return; } if (ch == '\'') { ParseSingleQuotedString(ch); return; } if (ch == '_' || char.IsLetter(ch)) { ParseKeyword(ch); return; } if (ch == '}' || ch == ':') { // when condition is embedded TokenType = ConditionTokenType.EndOfInput; return; } TokenValue = ch.ToString(); var success = TryGetComparisonToken(ch); if (success) return; success = TryGetLogicalToken(ch); if (success) return; if (ch >= 32 && ch < 128) { ConditionTokenType tt = charIndexToTokenType[ch]; if (tt != ConditionTokenType.Invalid) { TokenType = tt; TokenValue = new string(ch, 1); ReadChar(); return; } throw new ConditionParseException($"Invalid punctuation: {ch}"); } throw new ConditionParseException($"Invalid token: {ch}"); } /// <summary> /// Try the comparison tokens (greater, smaller, greater-equals, smaller-equals) /// </summary> /// <param name="ch">current char</param> /// <returns>is match</returns> private bool TryGetComparisonToken(char ch) { if (ch == '<') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '>') { TokenType = ConditionTokenType.NotEqual; TokenValue = "<>"; ReadChar(); return true; } if (nextChar == '=') { TokenType = ConditionTokenType.LessThanOrEqualTo; TokenValue = "<="; ReadChar(); return true; } TokenType = ConditionTokenType.LessThan; TokenValue = "<"; return true; } if (ch == '>') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '=') { TokenType = ConditionTokenType.GreaterThanOrEqualTo; TokenValue = ">="; ReadChar(); return true; } TokenType = ConditionTokenType.GreaterThan; TokenValue = ">"; return true; } return false; } /// <summary> /// Try the logical tokens (and, or, not, equals) /// </summary> /// <param name="ch">current char</param> /// <returns>is match</returns> private bool TryGetLogicalToken(char ch) { if (ch == '!') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '=') { TokenType = ConditionTokenType.NotEqual; TokenValue = "!="; ReadChar(); return true; } TokenType = ConditionTokenType.Not; TokenValue = "!"; return true; } if (ch == '&') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '&') { TokenType = ConditionTokenType.And; TokenValue = "&&"; ReadChar(); return true; } throw new ConditionParseException("Expected '&&' but got '&'"); } if (ch == '|') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '|') { TokenType = ConditionTokenType.Or; TokenValue = "||"; ReadChar(); return true; } throw new ConditionParseException("Expected '||' but got '|'"); } if (ch == '=') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '=') { TokenType = ConditionTokenType.EqualTo; TokenValue = "=="; ReadChar(); return true; } TokenType = ConditionTokenType.EqualTo; TokenValue = "="; return true; } return false; } private static ConditionTokenType[] BuildCharIndexToTokenType() { CharToTokenType[] charToTokenType = { new CharToTokenType('(', ConditionTokenType.LeftParen), new CharToTokenType(')', ConditionTokenType.RightParen), new CharToTokenType('.', ConditionTokenType.Dot), new CharToTokenType(',', ConditionTokenType.Comma), new CharToTokenType('!', ConditionTokenType.Not), new CharToTokenType('-', ConditionTokenType.Minus), }; var result = new ConditionTokenType[128]; for (int i = 0; i < 128; ++i) { result[i] = ConditionTokenType.Invalid; } foreach (CharToTokenType cht in charToTokenType) { result[(int)cht.Character] = cht.TokenType; } return result; } private void ParseSingleQuotedString(char ch) { int i; TokenType = ConditionTokenType.String; StringBuilder sb = new StringBuilder(); sb.Append(ch); ReadChar(); while ((i = PeekChar()) != -1) { ch = (char)i; sb.Append((char)ReadChar()); if (ch == '\'') { if (PeekChar() == (int)'\'') { sb.Append('\''); ReadChar(); } else { break; } } } if (i == -1) { throw new ConditionParseException("String literal is missing a closing quote character."); } TokenValue = sb.ToString(); } private void ParseKeyword(char ch) { int i; TokenType = ConditionTokenType.Keyword; StringBuilder sb = new StringBuilder(); sb.Append(ch); ReadChar(); while ((i = PeekChar()) != -1) { if ((char)i == '_' || (char)i == '-' || char.IsLetterOrDigit((char)i)) { sb.Append((char)ReadChar()); } else { break; } } TokenValue = sb.ToString(); } private void ParseNumber(char ch) { int i; TokenType = ConditionTokenType.Number; StringBuilder sb = new StringBuilder(); sb.Append(ch); ReadChar(); while ((i = PeekChar()) != -1) { ch = (char)i; if (char.IsDigit(ch) || (ch == '.')) { sb.Append((char)ReadChar()); } else { break; } } TokenValue = sb.ToString(); } private void SkipWhitespace() { int ch; while ((ch = PeekChar()) != -1) { if (!char.IsWhiteSpace((char)ch)) { break; } ReadChar(); } } private int PeekChar() { return _stringReader.Peek(); } private int ReadChar() { return _stringReader.Read(); } /// <summary> /// Mapping between characters and token types for punctuations. /// </summary> private struct CharToTokenType { public readonly char Character; public readonly ConditionTokenType TokenType; /// <summary> /// Initializes a new instance of the CharToTokenType struct. /// </summary> /// <param name="character">The character.</param> /// <param name="tokenType">Type of the token.</param> public CharToTokenType(char character, ConditionTokenType tokenType) { Character = character; TokenType = tokenType; } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.ConfigService.Model; using Amazon.ConfigService.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.ConfigService { /// <summary> /// Implementation for accessing ConfigService /// /// AWS Config /// <para> /// AWS Config provides a way to keep track of the configurations of all the AWS resources /// associated with your AWS account. You can use AWS Config to get the current and historical /// configurations of each AWS resource and also to get information about the relationship /// between the resources. An AWS resource can be an Amazon Compute Cloud (Amazon EC2) /// instance, an Elastic Block Store (EBS) volume, an Elastic network Interface (ENI), /// or a security group. For a complete list of resources currently supported by AWS Config, /// see <a href="http://docs.aws.amazon.com/config/latest/developerguide/resource-config-reference.html#supported-resources">Supported /// AWS Resources</a>. /// </para> /// /// <para> /// You can access and manage AWS Config through the AWS Management Console, the AWS Command /// Line Interface (AWS CLI), the AWS Config API, or the AWS SDKs for AWS Config /// </para> /// /// <para> /// This reference guide contains documentation for the AWS Config API and the AWS CLI /// commands that you can use to manage AWS Config. /// </para> /// /// <para> /// The AWS Config API uses the Signature Version 4 protocol for signing requests. For /// more information about how to sign a request with this protocol, see <a href="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature /// Version 4 Signing Process</a>. /// </para> /// /// <para> /// For detailed information about AWS Config features and their associated actions or /// commands, as well as how to work with AWS Management Console, see <a href="http://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html">What /// Is AWS Config?</a> in the <i>AWS Config Developer Guide</i>. /// </para> /// </summary> public partial class AmazonConfigServiceClient : AmazonServiceClient, IAmazonConfigService { #region Constructors /// <summary> /// Constructs AmazonConfigServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonConfigServiceClient(AWSCredentials credentials) : this(credentials, new AmazonConfigServiceConfig()) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonConfigServiceClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonConfigServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Credentials and an /// AmazonConfigServiceClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonConfigServiceClient Configuration Object</param> public AmazonConfigServiceClient(AWSCredentials credentials, AmazonConfigServiceConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonConfigServiceConfig()) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonConfigServiceConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonConfigServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonConfigServiceClient Configuration Object</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonConfigServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonConfigServiceConfig()) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonConfigServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonConfigServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonConfigServiceClient Configuration Object</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonConfigServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region DeleteConfigRule internal DeleteConfigRuleResponse DeleteConfigRule(DeleteConfigRuleRequest request) { var marshaller = new DeleteConfigRuleRequestMarshaller(); var unmarshaller = DeleteConfigRuleResponseUnmarshaller.Instance; return Invoke<DeleteConfigRuleRequest,DeleteConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteConfigRule operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteConfigRuleResponse> DeleteConfigRuleAsync(DeleteConfigRuleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteConfigRuleRequestMarshaller(); var unmarshaller = DeleteConfigRuleResponseUnmarshaller.Instance; return InvokeAsync<DeleteConfigRuleRequest,DeleteConfigRuleResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteDeliveryChannel internal DeleteDeliveryChannelResponse DeleteDeliveryChannel(DeleteDeliveryChannelRequest request) { var marshaller = new DeleteDeliveryChannelRequestMarshaller(); var unmarshaller = DeleteDeliveryChannelResponseUnmarshaller.Instance; return Invoke<DeleteDeliveryChannelRequest,DeleteDeliveryChannelResponse>(request, marshaller, unmarshaller); } /// <summary> /// Deletes the specified delivery channel. /// /// /// <para> /// The delivery channel cannot be deleted if it is the only delivery channel and the /// configuration recorder is still running. To delete the delivery channel, stop the /// running configuration recorder using the <a>StopConfigurationRecorder</a> action. /// </para> /// </summary> /// <param name="deliveryChannelName">The name of the delivery channel to delete.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteDeliveryChannel service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.LastDeliveryChannelDeleteFailedException"> /// You cannot delete the delivery channel you specified because the configuration recorder /// is running. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> public Task<DeleteDeliveryChannelResponse> DeleteDeliveryChannelAsync(string deliveryChannelName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var request = new DeleteDeliveryChannelRequest(); request.DeliveryChannelName = deliveryChannelName; return DeleteDeliveryChannelAsync(request, cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DeleteDeliveryChannel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDeliveryChannel operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteDeliveryChannelResponse> DeleteDeliveryChannelAsync(DeleteDeliveryChannelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteDeliveryChannelRequestMarshaller(); var unmarshaller = DeleteDeliveryChannelResponseUnmarshaller.Instance; return InvokeAsync<DeleteDeliveryChannelRequest,DeleteDeliveryChannelResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeliverConfigSnapshot internal DeliverConfigSnapshotResponse DeliverConfigSnapshot(DeliverConfigSnapshotRequest request) { var marshaller = new DeliverConfigSnapshotRequestMarshaller(); var unmarshaller = DeliverConfigSnapshotResponseUnmarshaller.Instance; return Invoke<DeliverConfigSnapshotRequest,DeliverConfigSnapshotResponse>(request, marshaller, unmarshaller); } /// <summary> /// Schedules delivery of a configuration snapshot to the Amazon S3 bucket in the specified /// delivery channel. After the delivery has started, AWS Config sends following notifications /// using an Amazon SNS topic that you have specified. /// /// <ul> <li>Notification of starting the delivery.</li> <li>Notification of delivery /// completed, if the delivery was successfully completed.</li> <li>Notification of delivery /// failure, if the delivery failed to complete.</li> </ul> /// </summary> /// <param name="deliveryChannelName">The name of the delivery channel through which the snapshot is delivered.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeliverConfigSnapshot service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoAvailableConfigurationRecorderException"> /// There are no configuration recorders available to provide the role needed to describe /// your resources. Create a configuration recorder. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoRunningConfigurationRecorderException"> /// There is no configuration recorder running. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> public Task<DeliverConfigSnapshotResponse> DeliverConfigSnapshotAsync(string deliveryChannelName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var request = new DeliverConfigSnapshotRequest(); request.DeliveryChannelName = deliveryChannelName; return DeliverConfigSnapshotAsync(request, cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DeliverConfigSnapshot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeliverConfigSnapshot operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeliverConfigSnapshotResponse> DeliverConfigSnapshotAsync(DeliverConfigSnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeliverConfigSnapshotRequestMarshaller(); var unmarshaller = DeliverConfigSnapshotResponseUnmarshaller.Instance; return InvokeAsync<DeliverConfigSnapshotRequest,DeliverConfigSnapshotResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeComplianceByConfigRule internal DescribeComplianceByConfigRuleResponse DescribeComplianceByConfigRule(DescribeComplianceByConfigRuleRequest request) { var marshaller = new DescribeComplianceByConfigRuleRequestMarshaller(); var unmarshaller = DescribeComplianceByConfigRuleResponseUnmarshaller.Instance; return Invoke<DescribeComplianceByConfigRuleRequest,DescribeComplianceByConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeComplianceByConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeComplianceByConfigRule operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeComplianceByConfigRuleResponse> DescribeComplianceByConfigRuleAsync(DescribeComplianceByConfigRuleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeComplianceByConfigRuleRequestMarshaller(); var unmarshaller = DescribeComplianceByConfigRuleResponseUnmarshaller.Instance; return InvokeAsync<DescribeComplianceByConfigRuleRequest,DescribeComplianceByConfigRuleResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeComplianceByResource internal DescribeComplianceByResourceResponse DescribeComplianceByResource(DescribeComplianceByResourceRequest request) { var marshaller = new DescribeComplianceByResourceRequestMarshaller(); var unmarshaller = DescribeComplianceByResourceResponseUnmarshaller.Instance; return Invoke<DescribeComplianceByResourceRequest,DescribeComplianceByResourceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeComplianceByResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeComplianceByResource operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeComplianceByResourceResponse> DescribeComplianceByResourceAsync(DescribeComplianceByResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeComplianceByResourceRequestMarshaller(); var unmarshaller = DescribeComplianceByResourceResponseUnmarshaller.Instance; return InvokeAsync<DescribeComplianceByResourceRequest,DescribeComplianceByResourceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeConfigRuleEvaluationStatus internal DescribeConfigRuleEvaluationStatusResponse DescribeConfigRuleEvaluationStatus(DescribeConfigRuleEvaluationStatusRequest request) { var marshaller = new DescribeConfigRuleEvaluationStatusRequestMarshaller(); var unmarshaller = DescribeConfigRuleEvaluationStatusResponseUnmarshaller.Instance; return Invoke<DescribeConfigRuleEvaluationStatusRequest,DescribeConfigRuleEvaluationStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigRuleEvaluationStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigRuleEvaluationStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeConfigRuleEvaluationStatusResponse> DescribeConfigRuleEvaluationStatusAsync(DescribeConfigRuleEvaluationStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeConfigRuleEvaluationStatusRequestMarshaller(); var unmarshaller = DescribeConfigRuleEvaluationStatusResponseUnmarshaller.Instance; return InvokeAsync<DescribeConfigRuleEvaluationStatusRequest,DescribeConfigRuleEvaluationStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeConfigRules internal DescribeConfigRulesResponse DescribeConfigRules(DescribeConfigRulesRequest request) { var marshaller = new DescribeConfigRulesRequestMarshaller(); var unmarshaller = DescribeConfigRulesResponseUnmarshaller.Instance; return Invoke<DescribeConfigRulesRequest,DescribeConfigRulesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigRules operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigRules operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeConfigRulesResponse> DescribeConfigRulesAsync(DescribeConfigRulesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeConfigRulesRequestMarshaller(); var unmarshaller = DescribeConfigRulesResponseUnmarshaller.Instance; return InvokeAsync<DescribeConfigRulesRequest,DescribeConfigRulesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeConfigurationRecorders internal DescribeConfigurationRecordersResponse DescribeConfigurationRecorders() { return DescribeConfigurationRecorders(new DescribeConfigurationRecordersRequest()); } internal DescribeConfigurationRecordersResponse DescribeConfigurationRecorders(DescribeConfigurationRecordersRequest request) { var marshaller = new DescribeConfigurationRecordersRequestMarshaller(); var unmarshaller = DescribeConfigurationRecordersResponseUnmarshaller.Instance; return Invoke<DescribeConfigurationRecordersRequest,DescribeConfigurationRecordersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns the name of one or more specified configuration recorders. If the recorder /// name is not specified, this action returns the names of all the configuration recorders /// associated with the account. /// /// <note> /// <para> /// Currently, you can specify only one configuration recorder per account. /// </para> /// </note> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeConfigurationRecorders service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> public Task<DescribeConfigurationRecordersResponse> DescribeConfigurationRecordersAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeConfigurationRecordersAsync(new DescribeConfigurationRecordersRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigurationRecorders operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationRecorders operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeConfigurationRecordersResponse> DescribeConfigurationRecordersAsync(DescribeConfigurationRecordersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeConfigurationRecordersRequestMarshaller(); var unmarshaller = DescribeConfigurationRecordersResponseUnmarshaller.Instance; return InvokeAsync<DescribeConfigurationRecordersRequest,DescribeConfigurationRecordersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeConfigurationRecorderStatus internal DescribeConfigurationRecorderStatusResponse DescribeConfigurationRecorderStatus() { return DescribeConfigurationRecorderStatus(new DescribeConfigurationRecorderStatusRequest()); } internal DescribeConfigurationRecorderStatusResponse DescribeConfigurationRecorderStatus(DescribeConfigurationRecorderStatusRequest request) { var marshaller = new DescribeConfigurationRecorderStatusRequestMarshaller(); var unmarshaller = DescribeConfigurationRecorderStatusResponseUnmarshaller.Instance; return Invoke<DescribeConfigurationRecorderStatusRequest,DescribeConfigurationRecorderStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns the current status of the specified configuration recorder. If a configuration /// recorder is not specified, this action returns the status of all configuration recorder /// associated with the account. /// /// <note>Currently, you can specify only one configuration recorder per account.</note> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeConfigurationRecorderStatus service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> public Task<DescribeConfigurationRecorderStatusResponse> DescribeConfigurationRecorderStatusAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeConfigurationRecorderStatusAsync(new DescribeConfigurationRecorderStatusRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigurationRecorderStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationRecorderStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeConfigurationRecorderStatusResponse> DescribeConfigurationRecorderStatusAsync(DescribeConfigurationRecorderStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeConfigurationRecorderStatusRequestMarshaller(); var unmarshaller = DescribeConfigurationRecorderStatusResponseUnmarshaller.Instance; return InvokeAsync<DescribeConfigurationRecorderStatusRequest,DescribeConfigurationRecorderStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeDeliveryChannels internal DescribeDeliveryChannelsResponse DescribeDeliveryChannels() { return DescribeDeliveryChannels(new DescribeDeliveryChannelsRequest()); } internal DescribeDeliveryChannelsResponse DescribeDeliveryChannels(DescribeDeliveryChannelsRequest request) { var marshaller = new DescribeDeliveryChannelsRequestMarshaller(); var unmarshaller = DescribeDeliveryChannelsResponseUnmarshaller.Instance; return Invoke<DescribeDeliveryChannelsRequest,DescribeDeliveryChannelsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns details about the specified delivery channel. If a delivery channel is not /// specified, this action returns the details of all delivery channels associated with /// the account. /// /// <note> /// <para> /// Currently, you can specify only one delivery channel per account. /// </para> /// </note> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeDeliveryChannels service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> public Task<DescribeDeliveryChannelsResponse> DescribeDeliveryChannelsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeDeliveryChannelsAsync(new DescribeDeliveryChannelsRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeDeliveryChannels operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryChannels operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeDeliveryChannelsResponse> DescribeDeliveryChannelsAsync(DescribeDeliveryChannelsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeDeliveryChannelsRequestMarshaller(); var unmarshaller = DescribeDeliveryChannelsResponseUnmarshaller.Instance; return InvokeAsync<DescribeDeliveryChannelsRequest,DescribeDeliveryChannelsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeDeliveryChannelStatus internal DescribeDeliveryChannelStatusResponse DescribeDeliveryChannelStatus() { return DescribeDeliveryChannelStatus(new DescribeDeliveryChannelStatusRequest()); } internal DescribeDeliveryChannelStatusResponse DescribeDeliveryChannelStatus(DescribeDeliveryChannelStatusRequest request) { var marshaller = new DescribeDeliveryChannelStatusRequestMarshaller(); var unmarshaller = DescribeDeliveryChannelStatusResponseUnmarshaller.Instance; return Invoke<DescribeDeliveryChannelStatusRequest,DescribeDeliveryChannelStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns the current status of the specified delivery channel. If a delivery channel /// is not specified, this action returns the current status of all delivery channels /// associated with the account. /// /// <note>Currently, you can specify only one delivery channel per account.</note> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeDeliveryChannelStatus service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> public Task<DescribeDeliveryChannelStatusResponse> DescribeDeliveryChannelStatusAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeDeliveryChannelStatusAsync(new DescribeDeliveryChannelStatusRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeDeliveryChannelStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryChannelStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeDeliveryChannelStatusResponse> DescribeDeliveryChannelStatusAsync(DescribeDeliveryChannelStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeDeliveryChannelStatusRequestMarshaller(); var unmarshaller = DescribeDeliveryChannelStatusResponseUnmarshaller.Instance; return InvokeAsync<DescribeDeliveryChannelStatusRequest,DescribeDeliveryChannelStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetComplianceDetailsByConfigRule internal GetComplianceDetailsByConfigRuleResponse GetComplianceDetailsByConfigRule(GetComplianceDetailsByConfigRuleRequest request) { var marshaller = new GetComplianceDetailsByConfigRuleRequestMarshaller(); var unmarshaller = GetComplianceDetailsByConfigRuleResponseUnmarshaller.Instance; return Invoke<GetComplianceDetailsByConfigRuleRequest,GetComplianceDetailsByConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetComplianceDetailsByConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetComplianceDetailsByConfigRule operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetComplianceDetailsByConfigRuleResponse> GetComplianceDetailsByConfigRuleAsync(GetComplianceDetailsByConfigRuleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetComplianceDetailsByConfigRuleRequestMarshaller(); var unmarshaller = GetComplianceDetailsByConfigRuleResponseUnmarshaller.Instance; return InvokeAsync<GetComplianceDetailsByConfigRuleRequest,GetComplianceDetailsByConfigRuleResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetComplianceDetailsByResource internal GetComplianceDetailsByResourceResponse GetComplianceDetailsByResource(GetComplianceDetailsByResourceRequest request) { var marshaller = new GetComplianceDetailsByResourceRequestMarshaller(); var unmarshaller = GetComplianceDetailsByResourceResponseUnmarshaller.Instance; return Invoke<GetComplianceDetailsByResourceRequest,GetComplianceDetailsByResourceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetComplianceDetailsByResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetComplianceDetailsByResource operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetComplianceDetailsByResourceResponse> GetComplianceDetailsByResourceAsync(GetComplianceDetailsByResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetComplianceDetailsByResourceRequestMarshaller(); var unmarshaller = GetComplianceDetailsByResourceResponseUnmarshaller.Instance; return InvokeAsync<GetComplianceDetailsByResourceRequest,GetComplianceDetailsByResourceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetComplianceSummaryByConfigRule internal GetComplianceSummaryByConfigRuleResponse GetComplianceSummaryByConfigRule(GetComplianceSummaryByConfigRuleRequest request) { var marshaller = new GetComplianceSummaryByConfigRuleRequestMarshaller(); var unmarshaller = GetComplianceSummaryByConfigRuleResponseUnmarshaller.Instance; return Invoke<GetComplianceSummaryByConfigRuleRequest,GetComplianceSummaryByConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetComplianceSummaryByConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetComplianceSummaryByConfigRule operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetComplianceSummaryByConfigRuleResponse> GetComplianceSummaryByConfigRuleAsync(GetComplianceSummaryByConfigRuleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetComplianceSummaryByConfigRuleRequestMarshaller(); var unmarshaller = GetComplianceSummaryByConfigRuleResponseUnmarshaller.Instance; return InvokeAsync<GetComplianceSummaryByConfigRuleRequest,GetComplianceSummaryByConfigRuleResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetComplianceSummaryByResourceType internal GetComplianceSummaryByResourceTypeResponse GetComplianceSummaryByResourceType(GetComplianceSummaryByResourceTypeRequest request) { var marshaller = new GetComplianceSummaryByResourceTypeRequestMarshaller(); var unmarshaller = GetComplianceSummaryByResourceTypeResponseUnmarshaller.Instance; return Invoke<GetComplianceSummaryByResourceTypeRequest,GetComplianceSummaryByResourceTypeResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetComplianceSummaryByResourceType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetComplianceSummaryByResourceType operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetComplianceSummaryByResourceTypeResponse> GetComplianceSummaryByResourceTypeAsync(GetComplianceSummaryByResourceTypeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetComplianceSummaryByResourceTypeRequestMarshaller(); var unmarshaller = GetComplianceSummaryByResourceTypeResponseUnmarshaller.Instance; return InvokeAsync<GetComplianceSummaryByResourceTypeRequest,GetComplianceSummaryByResourceTypeResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetResourceConfigHistory internal GetResourceConfigHistoryResponse GetResourceConfigHistory(GetResourceConfigHistoryRequest request) { var marshaller = new GetResourceConfigHistoryRequestMarshaller(); var unmarshaller = GetResourceConfigHistoryResponseUnmarshaller.Instance; return Invoke<GetResourceConfigHistoryRequest,GetResourceConfigHistoryResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetResourceConfigHistory operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetResourceConfigHistory operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetResourceConfigHistoryResponse> GetResourceConfigHistoryAsync(GetResourceConfigHistoryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetResourceConfigHistoryRequestMarshaller(); var unmarshaller = GetResourceConfigHistoryResponseUnmarshaller.Instance; return InvokeAsync<GetResourceConfigHistoryRequest,GetResourceConfigHistoryResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListDiscoveredResources internal ListDiscoveredResourcesResponse ListDiscoveredResources(ListDiscoveredResourcesRequest request) { var marshaller = new ListDiscoveredResourcesRequestMarshaller(); var unmarshaller = ListDiscoveredResourcesResponseUnmarshaller.Instance; return Invoke<ListDiscoveredResourcesRequest,ListDiscoveredResourcesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListDiscoveredResources operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDiscoveredResources operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListDiscoveredResourcesResponse> ListDiscoveredResourcesAsync(ListDiscoveredResourcesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListDiscoveredResourcesRequestMarshaller(); var unmarshaller = ListDiscoveredResourcesResponseUnmarshaller.Instance; return InvokeAsync<ListDiscoveredResourcesRequest,ListDiscoveredResourcesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region PutConfigRule internal PutConfigRuleResponse PutConfigRule(PutConfigRuleRequest request) { var marshaller = new PutConfigRuleRequestMarshaller(); var unmarshaller = PutConfigRuleResponseUnmarshaller.Instance; return Invoke<PutConfigRuleRequest,PutConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutConfigRule operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<PutConfigRuleResponse> PutConfigRuleAsync(PutConfigRuleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PutConfigRuleRequestMarshaller(); var unmarshaller = PutConfigRuleResponseUnmarshaller.Instance; return InvokeAsync<PutConfigRuleRequest,PutConfigRuleResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region PutConfigurationRecorder internal PutConfigurationRecorderResponse PutConfigurationRecorder(PutConfigurationRecorderRequest request) { var marshaller = new PutConfigurationRecorderRequestMarshaller(); var unmarshaller = PutConfigurationRecorderResponseUnmarshaller.Instance; return Invoke<PutConfigurationRecorderRequest,PutConfigurationRecorderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutConfigurationRecorder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutConfigurationRecorder operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<PutConfigurationRecorderResponse> PutConfigurationRecorderAsync(PutConfigurationRecorderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PutConfigurationRecorderRequestMarshaller(); var unmarshaller = PutConfigurationRecorderResponseUnmarshaller.Instance; return InvokeAsync<PutConfigurationRecorderRequest,PutConfigurationRecorderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region PutDeliveryChannel internal PutDeliveryChannelResponse PutDeliveryChannel(PutDeliveryChannelRequest request) { var marshaller = new PutDeliveryChannelRequestMarshaller(); var unmarshaller = PutDeliveryChannelResponseUnmarshaller.Instance; return Invoke<PutDeliveryChannelRequest,PutDeliveryChannelResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutDeliveryChannel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutDeliveryChannel operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<PutDeliveryChannelResponse> PutDeliveryChannelAsync(PutDeliveryChannelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PutDeliveryChannelRequestMarshaller(); var unmarshaller = PutDeliveryChannelResponseUnmarshaller.Instance; return InvokeAsync<PutDeliveryChannelRequest,PutDeliveryChannelResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region PutEvaluations internal PutEvaluationsResponse PutEvaluations(PutEvaluationsRequest request) { var marshaller = new PutEvaluationsRequestMarshaller(); var unmarshaller = PutEvaluationsResponseUnmarshaller.Instance; return Invoke<PutEvaluationsRequest,PutEvaluationsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutEvaluations operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutEvaluations operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<PutEvaluationsResponse> PutEvaluationsAsync(PutEvaluationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PutEvaluationsRequestMarshaller(); var unmarshaller = PutEvaluationsResponseUnmarshaller.Instance; return InvokeAsync<PutEvaluationsRequest,PutEvaluationsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StartConfigurationRecorder internal StartConfigurationRecorderResponse StartConfigurationRecorder(StartConfigurationRecorderRequest request) { var marshaller = new StartConfigurationRecorderRequestMarshaller(); var unmarshaller = StartConfigurationRecorderResponseUnmarshaller.Instance; return Invoke<StartConfigurationRecorderRequest,StartConfigurationRecorderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Starts recording configurations of the AWS resources you have selected to record in /// your AWS account. /// /// /// <para> /// You must have created at least one delivery channel to successfully start the configuration /// recorder. /// </para> /// </summary> /// <param name="configurationRecorderName">The name of the recorder object that records each configuration change made to the resources.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StartConfigurationRecorder service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoAvailableDeliveryChannelException"> /// There is no delivery channel available to record configurations. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> public Task<StartConfigurationRecorderResponse> StartConfigurationRecorderAsync(string configurationRecorderName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var request = new StartConfigurationRecorderRequest(); request.ConfigurationRecorderName = configurationRecorderName; return StartConfigurationRecorderAsync(request, cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the StartConfigurationRecorder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartConfigurationRecorder operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<StartConfigurationRecorderResponse> StartConfigurationRecorderAsync(StartConfigurationRecorderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new StartConfigurationRecorderRequestMarshaller(); var unmarshaller = StartConfigurationRecorderResponseUnmarshaller.Instance; return InvokeAsync<StartConfigurationRecorderRequest,StartConfigurationRecorderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StopConfigurationRecorder internal StopConfigurationRecorderResponse StopConfigurationRecorder(StopConfigurationRecorderRequest request) { var marshaller = new StopConfigurationRecorderRequestMarshaller(); var unmarshaller = StopConfigurationRecorderResponseUnmarshaller.Instance; return Invoke<StopConfigurationRecorderRequest,StopConfigurationRecorderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Stops recording configurations of the AWS resources you have selected to record in /// your AWS account. /// </summary> /// <param name="configurationRecorderName">The name of the recorder object that records each configuration change made to the resources.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StopConfigurationRecorder service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> public Task<StopConfigurationRecorderResponse> StopConfigurationRecorderAsync(string configurationRecorderName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var request = new StopConfigurationRecorderRequest(); request.ConfigurationRecorderName = configurationRecorderName; return StopConfigurationRecorderAsync(request, cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the StopConfigurationRecorder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StopConfigurationRecorder operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<StopConfigurationRecorderResponse> StopConfigurationRecorderAsync(StopConfigurationRecorderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new StopConfigurationRecorderRequestMarshaller(); var unmarshaller = StopConfigurationRecorderResponseUnmarshaller.Instance; return InvokeAsync<StopConfigurationRecorderRequest,StopConfigurationRecorderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
#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; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Web; using Subtext.Framework.Web; namespace Subtext.Framework.UI.Skinning { /// <summary> /// Provides rendering facilities for stylesheet elements in the head element of the page /// </summary> public class StyleSheetElementCollectionRenderer { private readonly SkinEngine _skinEngine; public StyleSheetElementCollectionRenderer(SkinEngine skinEngine) { _skinEngine = skinEngine; } private IDictionary<string, SkinTemplate> Templates { get { var templates = _templates; if (templates == null) { templates = _skinEngine.GetSkinTemplates(false /* mobile */); _templates = templates; } return templates; } } IDictionary<string, SkinTemplate> _templates; private static string RenderStyleAttribute(string attributeName, string attributeValue) { return attributeValue != null ? string.Format(" {0}=\"{1}\"", attributeName, attributeValue) : String.Empty; } private static string RenderStyleElement(string skinPath, Style style) { return RenderStyleElement(skinPath, style, string.Empty, string.Empty); } private static string RenderStyleElement(string skinPath, string cssFilename) { string element = string.Empty; element += "<link"; element += string.Format("{0}{1}{2} />{3}", RenderStyleAttribute("type", "text/css"), RenderStyleAttribute("rel", "stylesheet"), RenderStyleAttribute("href", skinPath + cssFilename), Environment.NewLine); return element; } private static string RenderStyleElement(string skinPath, Style style, string skinName, string cssRequestParam) { string element = string.Empty; if (!String.IsNullOrEmpty(style.Conditional)) { element = string.Format(CultureInfo.InvariantCulture, "<!--[{0}]>{1}", style.Conditional, Environment.NewLine); } element += "<link"; if (!string.IsNullOrEmpty(style.Media) && !style.Media.Equals("all", StringComparison.OrdinalIgnoreCase)) { element += RenderStyleAttribute("media", style.Media); } element += RenderStyleAttribute("type", "text/css") + RenderStyleAttribute("rel", "stylesheet") + RenderStyleAttribute("title", style.Title); if (string.IsNullOrEmpty(skinName)) { element += string.Format("{0} />{1}", RenderStyleAttribute("href", GetStylesheetHrefPath(skinPath, style)), Environment.NewLine); } else { element += string.Format("{0} />{1}", RenderStyleAttribute("href", GetStylesheetHrefPath(skinPath, style, skinName, cssRequestParam)), Environment.NewLine); } if (!String.IsNullOrEmpty(style.Conditional)) { element += string.Format("<![endif]-->{0}", Environment.NewLine); } return element; } /// <summary> /// Gets the stylesheet href path. /// </summary> /// <param name="skinPath">The skin path.</param> /// <param name="style">The style.</param> /// <returns></returns> public static string GetStylesheetHrefPath(string skinPath, Style style) { if (style.Href.StartsWith("~")) { return HttpHelper.ExpandTildePath(style.Href); } return style.Href.StartsWith("/") || style.Href.StartsWith("http://") || style.Href.StartsWith("https://") ? style.Href : skinPath + style.Href; } /// <summary> /// Gets the stylesheet href path. /// </summary> /// <param name="skinName">The skin name as in the key.</param> /// <param name="skinPath">The skin path.</param> /// <param name="style">The style.</param> /// <param name="cssRequestParam">The parameters used to request the css via the css handler.</param> /// <returns></returns> public static string GetStylesheetHrefPath(string skinPath, Style style, string skinName, string cssRequestParam) { if (IsStyleRemote(style)) { return style.Href; } return string.Format("{0}css.axd?name={1}&{2}", skinPath, skinName, cssRequestParam); } private static string CreateStylePath(string skinTemplateFolder) { string applicationPath = HttpContext.Current.Request.ApplicationPath; string path = string.Format("{0}/Skins/{1}/", (applicationPath == "/" ? String.Empty : applicationPath), skinTemplateFolder); return path; } public string RenderStyleElementCollection(string skinName) { SkinTemplate skinTemplate = Templates.GetValueOrDefault(skinName); return RenderStyleElementCollection(skinName, skinTemplate); } public string RenderStyleElementCollection(string skinName, SkinTemplate skinTemplate) { var templateDefinedStyles = new StringBuilder(); string finalStyleDefinition = string.Empty; var addedStyle = new List<string>(); if (skinTemplate != null) { string skinPath = CreateStylePath(skinTemplate.TemplateFolder); // If skin doesn't want to be merged, just write plain css if (skinTemplate.StyleMergeMode == StyleMergeMode.None) { if (skinTemplate.Styles != null) { foreach (Style style in skinTemplate.Styles) { templateDefinedStyles.Append(RenderStyleElement(skinPath, style)); } } if (!skinTemplate.ExcludeDefaultStyle) { templateDefinedStyles.Append(RenderStyleElement(skinPath, "style.css")); } if (skinTemplate.HasSkinStylesheet) { templateDefinedStyles.Append(RenderStyleElement(skinPath, skinTemplate.StyleSheet)); } finalStyleDefinition = templateDefinedStyles.ToString(); } else if (skinTemplate.StyleMergeMode == StyleMergeMode.MergedAfter || skinTemplate.StyleMergeMode == StyleMergeMode.MergedFirst) { foreach (Style style in skinTemplate.Styles) { if (!CanStyleBeMerged(style)) { string styleKey = BuildStyleKey(style); if (!addedStyle.Contains(styleKey) || IsStyleRemote(style)) { templateDefinedStyles.Append(RenderStyleElement(skinPath, style, skinName, styleKey)); addedStyle.Add(styleKey); } } } string mergedStyleLink = RenderStyleElement(skinPath, string.Format("css.axd?name={0}", skinName)); if (skinTemplate.StyleMergeMode == StyleMergeMode.MergedAfter) { finalStyleDefinition = templateDefinedStyles + mergedStyleLink; } else if (skinTemplate.StyleMergeMode == StyleMergeMode.MergedFirst) { finalStyleDefinition = mergedStyleLink + templateDefinedStyles; } } } return Environment.NewLine + finalStyleDefinition; } private static string BuildStyleKey(Style style) { var keyBuilder = new StringBuilder(); if (!String.IsNullOrEmpty(style.Media) && !style.Media.Equals("all", StringComparison.OrdinalIgnoreCase)) { keyBuilder.AppendFormat("media={0}&", style.Media); } if (!String.IsNullOrEmpty(style.Title)) { keyBuilder.AppendFormat("title={0}&", style.Title); } if (!String.IsNullOrEmpty(style.Conditional)) { keyBuilder.AppendFormat("conditional={0}&", HttpUtility.UrlEncode(style.Conditional)); } string key = keyBuilder.ToString(); if (key.Length > 0) { return key.Substring(0, key.Length - 1); } return string.Empty; } public ICollection<StyleDefinition> GetStylesToBeMerged(string name) { return GetStylesToBeMerged(name, null, null, null); } public ICollection<StyleDefinition> GetStylesToBeMerged(string skinName, string media, string title, string conditional) { bool normalCss = false; var styles = new List<StyleDefinition>(); SkinTemplate skinTemplate = Templates.GetValueOrDefault(skinName); if ((string.IsNullOrEmpty(media)) && string.IsNullOrEmpty(title) && string.IsNullOrEmpty(conditional)) { normalCss = true; } if (skinTemplate != null) { string skinPath = CreateStylePath(skinTemplate.TemplateFolder); if (skinTemplate.Styles != null) { foreach (Style style in skinTemplate.Styles) { if (normalCss) { if (CanStyleBeMerged(style)) { string tmpHref; if (style.Href.StartsWith("~")) { tmpHref = HttpHelper.ExpandTildePath(style.Href); } else { tmpHref = skinPath + style.Href; } styles.Add(new StyleDefinition(tmpHref, style.Media)); } } else { string tmpMedia = style.Media; if (tmpMedia != null && tmpMedia.Equals("all")) { tmpMedia = null; } if (string.Compare(media, tmpMedia, StringComparison.OrdinalIgnoreCase) == 0 && string.Compare(title, style.Title, StringComparison.OrdinalIgnoreCase) == 0 && string.Compare(conditional, style.Conditional, StringComparison.OrdinalIgnoreCase) == 0) { string tmpHref; if (style.Href.StartsWith("~")) { tmpHref = HttpHelper.ExpandTildePath(style.Href); } else { tmpHref = skinPath + style.Href; } styles.Add(new StyleDefinition(tmpHref, style.Media)); } } } } if (normalCss) { //Main style if (!skinTemplate.ExcludeDefaultStyle) { styles.Add(new StyleDefinition(skinPath + "style.css")); } //Secondary Style if (skinTemplate.HasSkinStylesheet) { styles.Add(new StyleDefinition(skinPath + skinTemplate.StyleSheet)); } } } return styles; } public static bool CanStyleBeMerged(Style style) { if (!String.IsNullOrEmpty(style.Conditional)) { return false; } if (!string.IsNullOrEmpty(style.Title)) { return false; } if (IsStyleRemote(style)) { return false; } return true; } private static bool IsStyleRemote(Style style) { if (style.Href.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || style.Href.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; namespace System.DirectoryServices.AccountManagement { public class PrincipalValueCollection<T> : IList<T>, IList // T must be a ValueType or immutable ref type (such as string) { // // IList // bool IList.IsFixedSize { get { return IsFixedSize; } } bool IList.IsReadOnly { get { return IsReadOnly; } } int IList.Add(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); _inner.Add((T)value); return Count; } void IList.Clear() { Clear(); } bool IList.Contains(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); return _inner.Contains((T)value); } int IList.IndexOf(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); return IndexOf((T)value); } void IList.Insert(int index, object value) { if (value == null) throw new ArgumentNullException(nameof(value)); Insert(index, (T)value); } void IList.Remove(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); _inner.Remove((T)value); } void IList.RemoveAt(int index) { RemoveAt(index); } object IList.this[int index] { get { return this[index]; } set { if (value == null) throw new ArgumentNullException(nameof(value)); this[index] = (T)value; } } // // ICollection // void ICollection.CopyTo(Array array, int index) { ((ICollection)_inner).CopyTo(array, index); } int ICollection.Count { get { return _inner.Count; } } bool ICollection.IsSynchronized { get { return IsSynchronized; } } object ICollection.SyncRoot { get { return SyncRoot; } } public bool IsSynchronized { get { return ((ICollection)_inner).IsSynchronized; } } public object SyncRoot { get { return this; } } // // IEnumerable // IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } // // IList<T> // public bool IsFixedSize { get { return false; } } public bool IsReadOnly { get { return false; } } // Adds obj to the end of the list by inserting it into insertedValues. public void Add(T value) { if (value == null) throw new ArgumentNullException(nameof(value)); _inner.Add(value); } public void Clear() { _inner.Clear(); } public bool Contains(T value) { if (value == null) throw new ArgumentNullException(nameof(value)); return _inner.Contains(value); } public int IndexOf(T value) { if (value == null) throw new ArgumentNullException(nameof(value)); int index = 0; foreach (TrackedCollection<T>.ValueEl el in _inner.combinedValues) { if (el.isInserted && el.insertedValue.Equals(value)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "IndexOf: found {0} on inserted at {1}", value, index); return index; } if (!el.isInserted && el.originalValue.Right.Equals(value)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "IndexOf: found {0} on original at {1}", value, index); return index; } index++; } return -1; } public void Insert(int index, T value) { _inner.MarkChange(); if (value == null) throw new ArgumentNullException(nameof(value)); if ((index < 0) || (index > _inner.combinedValues.Count)) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalValueCollection", "Insert({0}): out of range (count={1})", index, _inner.combinedValues.Count); throw new ArgumentOutOfRangeException(nameof(index)); } TrackedCollection<T>.ValueEl el = new TrackedCollection<T>.ValueEl(); el.isInserted = true; el.insertedValue = value; _inner.combinedValues.Insert(index, el); } public bool Remove(T value) { if (value == null) throw new ArgumentNullException(nameof(value)); return _inner.Remove(value); } public void RemoveAt(int index) { _inner.MarkChange(); if ((index < 0) || (index >= _inner.combinedValues.Count)) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalValueCollection", "RemoveAt({0}): out of range (count={1})", index, _inner.combinedValues.Count); throw new ArgumentOutOfRangeException(nameof(index)); } TrackedCollection<T>.ValueEl el = _inner.combinedValues[index]; if (el.isInserted) { // We're removing an inserted value. GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "RemoveAt({0}): removing inserted", index); _inner.combinedValues.RemoveAt(index); } else { // We're removing an original value. GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "RemoveAt({0}): removing original", index); Pair<T, T> pair = _inner.combinedValues[index].originalValue; _inner.combinedValues.RemoveAt(index); _inner.removedValues.Add(pair.Left); } } public T this[int index] { get { if ((index < 0) || (index >= _inner.combinedValues.Count)) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalValueCollection", "this[{0}].get: out of range (count={1})", index, _inner.combinedValues.Count); throw new ArgumentOutOfRangeException(nameof(index)); } TrackedCollection<T>.ValueEl el = _inner.combinedValues[index]; if (el.isInserted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "this[{0}].get: is inserted {1}", index, el.insertedValue); return el.insertedValue; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "this[{0}].get: is original {1}", index, el.originalValue.Right); return el.originalValue.Right; // Right == current value } } set { _inner.MarkChange(); if ((index < 0) || (index >= _inner.combinedValues.Count)) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalValueCollection", "this[{0}].set: out of range (count={1})", index, _inner.combinedValues.Count); throw new ArgumentOutOfRangeException(nameof(index)); } if (value == null) throw new ArgumentNullException(nameof(value)); TrackedCollection<T>.ValueEl el = _inner.combinedValues[index]; if (el.isInserted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "this[{0}].set: is inserted {1}", index, value); el.insertedValue = value; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "this[{0}].set: is original {1}", index, value); el.originalValue.Right = value; } } } // // ICollection<T> // public void CopyTo(T[] array, int index) { ((ICollection)this).CopyTo((Array)array, index); } public int Count { get { return _inner.Count; } } // // IEnumerable<T> // public IEnumerator<T> GetEnumerator() { return new ValueCollectionEnumerator<T>(_inner, _inner.combinedValues); } // // Private implementation // private readonly TrackedCollection<T> _inner = new TrackedCollection<T>(); // // Internal constructor // internal PrincipalValueCollection() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "Ctor"); // Nothing to do here } // // Load/Store implementation // internal void Load(List<T> values) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "Load, count={0}", values.Count); // To support reload _inner.combinedValues.Clear(); _inner.removedValues.Clear(); foreach (T value in values) { // If T was a mutable reference type, would need to make a copy of value // for the left-side of the Pair, so that changes to the value in the // right-side wouldn't also change the left-side value (due to aliasing). // However, we constrain T to be either a value type or a immutable ref type (e.g., string) // to avoid this problem. TrackedCollection<T>.ValueEl el = new TrackedCollection<T>.ValueEl(); el.isInserted = false; el.originalValue = new Pair<T, T>(value, value); _inner.combinedValues.Add(el); } } internal List<T> Inserted { get { return _inner.Inserted; } } internal List<T> Removed { get { return _inner.Removed; } } internal List<Pair<T, T>> ChangedValues { get { return _inner.ChangedValues; } } internal bool Changed { get { return _inner.Changed; } } // Resets the change-tracking of the collection to 'unchanged', by clearing out the removedValues, // changing inserted values into original values, and for all Pairs<T,T> in originalValues for which // the left-side does not equal the right-side, copying the right-side over the left-side internal void ResetTracking() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "Entering ResetTracking"); _inner.removedValues.Clear(); foreach (TrackedCollection<T>.ValueEl el in _inner.combinedValues) { if (el.isInserted) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "PrincipalValueCollection", "ResetTracking: moving {0} (type {1}) from inserted to original", el.insertedValue, el.insertedValue.GetType()); el.isInserted = false; el.originalValue = new Pair<T, T>(el.insertedValue, el.insertedValue); //el.insertedValue = T.default; } else { Pair<T, T> pair = el.originalValue; if (!pair.Left.Equals(pair.Right)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "PrincipalValueCollection", "ResetTracking: found changed original, left={0}, right={1}, type={2}", pair.Left, pair.Right, pair.Left.GetType()); pair.Left = pair.Right; } } } } } }
// 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.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Byte : IComparable, IConvertible, IFormattable, IComparable<Byte>, IEquatable<Byte>, ISpanFormattable { private byte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 255. public const byte MaxValue = (byte)0xFF; // The minimum value that a Byte may represent: 0. public const byte MinValue = 0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type byte, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Byte)) { throw new ArgumentException(SR.Arg_MustBeByte); } return m_value - (((Byte)value).m_value); } public int CompareTo(Byte value) { return m_value - value; } // Determines whether two Byte objects are equal. public override bool Equals(Object obj) { if (!(obj is Byte)) { return false; } return m_value == ((Byte)obj).m_value; } [NonVersionable] public bool Equals(Byte obj) { return m_value == obj; } // Gets a hash code for this instance. public override int GetHashCode() { return m_value; } public static byte Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static byte Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.CurrentInfo); } public static byte Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses an unsigned byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. public static byte Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider)); } public static byte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static byte Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { int i = 0; try { i = Number.ParseInt32(s, style, info); } catch (OverflowException e) { throw new OverflowException(SR.Overflow_Byte, e); } if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Byte); return (byte)i; } public static bool TryParse(String s, out Byte result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan<char> s, out byte result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Byte result) { result = 0; int i; if (!Number.TryParseInt32(s, style, info, out i)) { return false; } if (i < MinValue || i > MaxValue) { return false; } result = (byte)i; return true; } public override String ToString() { return Number.FormatInt32(m_value, null, null); } public String ToString(String format) { return Number.FormatInt32(m_value, format, null); } public String ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, provider); } public String ToString(String format, IFormatProvider provider) { return Number.FormatInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) { return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Byte; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return m_value; } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using System; using System.Collections.Concurrent; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading; using Orleans.Concurrency; using Orleans.Runtime; namespace Orleans.Serialization { using System.Runtime.CompilerServices; internal static class TypeUtilities { internal static bool IsOrleansPrimitive(this Type t) { return t.IsPrimitive || t.IsEnum || t == typeof(string) || t == typeof(DateTime) || t == typeof(Decimal) || (t.IsArray && t.GetElementType().IsOrleansPrimitive()); } static readonly ConcurrentDictionary<Type, bool> shallowCopyableTypes = new ConcurrentDictionary<Type, bool>(); static readonly ConcurrentDictionary<Type, string> typeNameCache = new ConcurrentDictionary<Type, string>(); static readonly ConcurrentDictionary<Type, string> typeKeyStringCache = new ConcurrentDictionary<Type, string>(); static readonly ConcurrentDictionary<Type, byte[]> typeKeyCache = new ConcurrentDictionary<Type, byte[]>(); static TypeUtilities() { shallowCopyableTypes[typeof(Decimal)] = true; shallowCopyableTypes[typeof(DateTime)] = true; shallowCopyableTypes[typeof(TimeSpan)] = true; shallowCopyableTypes[typeof(IPAddress)] = true; shallowCopyableTypes[typeof(IPEndPoint)] = true; shallowCopyableTypes[typeof(SiloAddress)] = true; shallowCopyableTypes[typeof(GrainId)] = true; shallowCopyableTypes[typeof(ActivationId)] = true; shallowCopyableTypes[typeof(ActivationAddress)] = true; shallowCopyableTypes[typeof(CorrelationId)] = true; shallowCopyableTypes[typeof(string)] = true; shallowCopyableTypes[typeof(Immutable<>)] = true; shallowCopyableTypes[typeof(CancellationToken)] = true; } internal static bool IsOrleansShallowCopyable(this Type t) { bool result; if (shallowCopyableTypes.TryGetValue(t, out result)) { return result; } var typeInfo = t.GetTypeInfo(); if (typeInfo.IsPrimitive || typeInfo.IsEnum) { shallowCopyableTypes[t] = true; return true; } if (typeInfo.GetCustomAttributes(typeof(ImmutableAttribute), false).Any()) { shallowCopyableTypes[t] = true; return true; } if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Immutable<>)) { shallowCopyableTypes[t] = true; return true; } if (typeof(Exception).IsAssignableFrom(typeInfo)) { shallowCopyableTypes[t] = true; return true; } if (typeInfo.IsValueType && !typeInfo.IsGenericType && !typeInfo.IsGenericTypeDefinition) { result = IsValueTypeFieldsShallowCopyable(typeInfo); shallowCopyableTypes[t] = result; return result; } shallowCopyableTypes[t] = false; return false; } private static bool IsValueTypeFieldsShallowCopyable(TypeInfo typeInfo) { return typeInfo.GetFields().All(f => f.FieldType != typeInfo.AsType() && IsOrleansShallowCopyable(f.FieldType)); } internal static bool IsSpecializationOf(this Type t, Type match) { var typeInfo = t.GetTypeInfo(); return typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == match; } internal static string OrleansTypeName(this Type t) { string name; if (typeNameCache.TryGetValue(t, out name)) return name; name = TypeUtils.GetTemplatedName(t, _ => !_.IsGenericParameter); typeNameCache[t] = name; return name; } public static byte[] OrleansTypeKey(this Type t) { byte[] key; if (typeKeyCache.TryGetValue(t, out key)) return key; key = Encoding.UTF8.GetBytes(t.OrleansTypeKeyString()); typeKeyCache[t] = key; return key; } public static string OrleansTypeKeyString(this Type t) { string key; if (typeKeyStringCache.TryGetValue(t, out key)) return key; var typeInfo = t.GetTypeInfo(); var sb = new StringBuilder(); if (typeInfo.IsGenericTypeDefinition) { sb.Append(GetBaseTypeKey(t)); sb.Append('\''); sb.Append(typeInfo.GetGenericArguments().Length); } else if (typeInfo.IsGenericType) { sb.Append(GetBaseTypeKey(t)); sb.Append('<'); var first = true; foreach (var genericArgument in t.GetGenericArguments()) { if (!first) { sb.Append(','); } first = false; sb.Append(OrleansTypeKeyString(genericArgument)); } sb.Append('>'); } else if (t.IsArray) { sb.Append(OrleansTypeKeyString(t.GetElementType())); sb.Append('['); if (t.GetArrayRank() > 1) { sb.Append(',', t.GetArrayRank() - 1); } sb.Append(']'); } else { sb.Append(GetBaseTypeKey(t)); } key = sb.ToString(); typeKeyStringCache[t] = key; return key; } private static string GetBaseTypeKey(Type t) { var typeInfo = t.GetTypeInfo(); string namespacePrefix = ""; if ((typeInfo.Namespace != null) && !typeInfo.Namespace.StartsWith("System.") && !typeInfo.Namespace.Equals("System")) { namespacePrefix = typeInfo.Namespace + '.'; } if (typeInfo.IsNestedPublic) { return namespacePrefix + OrleansTypeKeyString(typeInfo.DeclaringType) + "." + typeInfo.Name; } return namespacePrefix + typeInfo.Name; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static string GetLocationSafe(this Assembly a) { if (a.IsDynamic) { return "dynamic"; } try { return a.Location; } catch (Exception) { return "unknown"; } } /// <summary> /// Returns <see langword="true"/> if a type is accessible from C# code from the specified assembly, and <see langword="false"/> otherwise. /// </summary> /// <param name="type"></param> /// <param name="assembly"></param> /// <returns></returns> public static bool IsAccessibleFromAssembly(Type type, Assembly assembly) { if (type.IsSpecialName) return false; if (type.GetCustomAttribute<CompilerGeneratedAttribute>() != null) return false; // Obsolete types can be accessed, however obsolete types which have IsError set cannot. var obsoleteAttr = type.GetCustomAttribute<ObsoleteAttribute>(); if (obsoleteAttr != null && obsoleteAttr.IsError) return false; // Arrays are accessible if their element type is accessible. if (type.IsArray) return IsAccessibleFromAssembly(type.GetElementType(), assembly); // Pointer and ref types are not accessible. if (type.IsPointer || type.IsByRef) return false; // Generic types are only accessible if their generic arguments are accessible. var typeInfo = type.GetTypeInfo(); if (type.IsConstructedGenericType) { foreach (var parameter in type.GetGenericArguments()) { if (!IsAccessibleFromAssembly(parameter, assembly)) return false; } } else if (typeInfo.IsGenericTypeDefinition) { // Guard against unrepresentable type constraints, which appear when generating code for some languages, such as F#. foreach (var parameter in typeInfo.GenericTypeParameters) { foreach (var constraint in parameter.GetTypeInfo().GetGenericParameterConstraints()) { if (constraint == typeof(Array) || constraint == typeof(Delegate) || constraint == typeof(Enum)) return false; } } } // Internal types are accessible only if the declaring assembly exposes its internals to the target assembly. if (typeInfo.IsNotPublic || typeInfo.IsNestedAssembly || typeInfo.IsNestedFamORAssem) { if (!AreInternalsVisibleTo(typeInfo.Assembly, assembly)) return false; } // Nested types which are private or protected are not accessible. if (typeInfo.IsNestedPrivate || typeInfo.IsNestedFamily || typeInfo.IsNestedFamANDAssem) return false; // Nested types are otherwise accessible if their declaring type is accessible. if (typeInfo.IsNested) { return IsAccessibleFromAssembly(type.DeclaringType, assembly); } return true; } /// <summary> /// Returns true if <paramref name="fromAssembly"/> has exposed its internals to <paramref name="toAssembly"/>, false otherwise. /// </summary> /// <param name="fromAssembly">The assembly containing internal types.</param> /// <param name="toAssembly">The assembly requiring access to internal types.</param> /// <returns> /// true if <paramref name="fromAssembly"/> has exposed its internals to <paramref name="toAssembly"/>, false otherwise /// </returns> private static bool AreInternalsVisibleTo(Assembly fromAssembly, Assembly toAssembly) { // If the to-assembly is null, it cannot have internals visible to it. if (toAssembly == null) { return false; } if (Equals(fromAssembly, toAssembly)) return true; // Check InternalsVisibleTo attributes on the from-assembly, pointing to the to-assembly. var fullName = toAssembly.GetName().FullName; var shortName = toAssembly.GetName().Name; var internalsVisibleTo = fromAssembly.GetCustomAttributes<InternalsVisibleToAttribute>(); foreach (var attr in internalsVisibleTo) { if (string.Equals(attr.AssemblyName, fullName, StringComparison.Ordinal)) return true; if (string.Equals(attr.AssemblyName, shortName, StringComparison.Ordinal)) return true; } return false; } } }
using System; using System.ComponentModel; namespace CslaGenerator.Metadata { public class ProjectParameters : INotifyPropertyChanged { #region State Fields Stored Procedures string _spGeneralPrefix = string.Empty; string _spGetPrefix = "Get"; string _spDeletePrefix = "Delete"; string _spUpdatePrefix = "Update"; string _spAddPrefix = "Add"; string _spGeneralSuffix = string.Empty; string _spGetSuffix = string.Empty; string _spDeleteSuffix = string.Empty; string _spUpdateSuffix = string.Empty; string _spAddSuffix = string.Empty; bool _regenSpNameOnObjectRename = true; string _spBoolSoftDeleteColumn = string.Empty; string _spIntSoftDeleteColumn = string.Empty; bool _spIgnoreFilterWhenSoftDeleteIsParam = true; bool _spRemoveChildBeforeParent = true; private string _orbChildPropertySuffix = string.Empty; private string _orbCollectionSuffix = string.Empty; private string _orbSingleSPSuffix = string.Empty; private bool _orbItemsUseSingleSP; #endregion #region State Fields New Object Defaults private string _defaultNamespace = String.Empty; private string _defaultFolder = String.Empty; bool _smartDateDefault = true; private bool _autoCriteria = true; private bool _autoTimestampCriteria = true; private bool _datesDefaultStringWithTypeConversion = true; private PropertyDeclaration _createTimestampPropertyMode = PropertyDeclaration.NoProperty; private bool _readOnlyObjectsCopyAuditing; private bool _readOnlyObjectsCopyTimestamp; private PropertyDeclaration _createReadOnlyObjectsPropertyMode = PropertyDeclaration.AutoProperty; TransactionType _defaultTransactionType = TransactionType.None; PersistenceType _defaultPersistenceType = PersistenceType.SqlConnectionManager; private string _defaultDatabaseContextObject = string.Empty; private string _defaultDataBase = String.Empty; #endregion #region State Fields Advanced private string _idGuidDefaultValue = "Guid.NewGuid()"; private string _idInt16DefaultValue = "-1"; private string _idInt32DefaultValue = "-1"; private string _idInt64DefaultValue = "-1"; private string _fieldNamePrefix = "m_"; private string _delegateNamePrefix = "d_"; private string _creationDateColumn = string.Empty; private string _creationUserColumn = string.Empty; private string _changedDateColumn = string.Empty; private string _changedUserColumn = string.Empty; private bool _logDateAndTime = true; private string _getUserMethod = string.Empty; #endregion #region Properties New Object Defaults public string DefaultNamespace { get { return _defaultNamespace; } set { value = PropertyHelper.TidyFilename(value); if (_defaultNamespace == value) return; _defaultNamespace = value; OnPropertyChanged(""); } } public string DefaultFolder { get { return _defaultFolder; } set { value = PropertyHelper.Tidy(value); if (_defaultFolder == value) return; _defaultFolder = value; OnPropertyChanged(""); } } public bool SmartDateDefault { get { return _smartDateDefault; } set { if (_smartDateDefault == value) return; _smartDateDefault = value; OnPropertyChanged(""); } } public bool AutoCriteria { get { return _autoCriteria; } set { if (_autoCriteria == value) return; _autoCriteria = value; OnPropertyChanged(""); } } /// <summary> /// Gets or sets a value indicating whether to add a Delete CriteriaTS whem DB type "timestamp" is found. /// </summary> /// <value> /// <c>true</c> if [auto timestamp criteria]; otherwise, <c>false</c>. /// </value> public bool AutoTimestampCriteria { get { return _autoTimestampCriteria; } set { if (_autoTimestampCriteria == value) return; _autoTimestampCriteria = value; OnPropertyChanged(""); } } public bool DatesDefaultStringWithTypeConversion { get { return _datesDefaultStringWithTypeConversion; } set { if (_datesDefaultStringWithTypeConversion == value) return; _datesDefaultStringWithTypeConversion = value; OnPropertyChanged(""); } } /// <summary> /// Gets or sets the PropertyMode for timestamp Value Property creation. /// </summary> /// <value> /// The create timestamp property mode. /// </value> public PropertyDeclaration CreateTimestampPropertyMode { get { return _createTimestampPropertyMode; } set { if (_createTimestampPropertyMode == value) return; _createTimestampPropertyMode = value; OnPropertyChanged(""); } } public bool ReadOnlyObjectsCopyAuditing { get { return _readOnlyObjectsCopyAuditing; } set { if (_readOnlyObjectsCopyAuditing == value) return; _readOnlyObjectsCopyAuditing = value; OnPropertyChanged(""); } } public bool ReadOnlyObjectsCopyTimestamp { get { return _readOnlyObjectsCopyTimestamp; } set { if (_readOnlyObjectsCopyTimestamp == value) return; _readOnlyObjectsCopyTimestamp = value; OnPropertyChanged(""); } } public PropertyDeclaration CreateReadOnlyObjectsPropertyMode { get { return _createReadOnlyObjectsPropertyMode; } set { if (_createReadOnlyObjectsPropertyMode == value) return; _createReadOnlyObjectsPropertyMode = value; OnPropertyChanged(""); } } public string DefaultDataBase { get { return _defaultDataBase; } set { value = PropertyHelper.Tidy(value); if (_defaultDataBase == value) return; _defaultDataBase = value; GeneratorController.Current.CurrentUnit.GenerationParams.DatabaseConnection = value; OnPropertyChanged(""); } } public TransactionType DefaultTransactionType { get { if (GeneratorController.Current.CurrentUnit.GenerationParams.UseDal) if (_defaultTransactionType == TransactionType.ADO) DefaultTransactionType = TransactionType.TransactionScope; return _defaultTransactionType; } set { if (value == TransactionType.TransactionalAttribute) { _defaultTransactionType = TransactionType.TransactionScope; } else if (value == TransactionType.ADO && GeneratorController.Current.CurrentUnit.GenerationParams.UseDal) { _defaultTransactionType = TransactionType.TransactionScope; } else { if (_defaultTransactionType == value) return; _defaultTransactionType = value; } OnPropertyChanged(""); } } public PersistenceType DefaultPersistenceType { get { if (GeneratorController.Current.CurrentUnit.GenerationParams.UseDal) if (_defaultPersistenceType == PersistenceType.SqlConnectionUnshared) DefaultPersistenceType = PersistenceType.SqlConnectionManager; return _defaultPersistenceType; } set { if (value == PersistenceType.SqlConnectionUnshared && GeneratorController.Current.CurrentUnit.GenerationParams.UseDal) { _defaultPersistenceType = PersistenceType.SqlConnectionManager; } else { if (_defaultPersistenceType == value) return; _defaultPersistenceType = value; } OnPropertyChanged(""); if (_defaultPersistenceType == value) return; _defaultPersistenceType = value; OnPropertyChanged(""); } } public string DefaultDatabaseContextObject { get { return _defaultDatabaseContextObject; } set { value = PropertyHelper.Tidy(value); if (_defaultDatabaseContextObject == value) return; _defaultDatabaseContextObject = value; OnPropertyChanged(""); } } #endregion #region Object Relations Builder public string ORBChildPropertySuffix { get { return _orbChildPropertySuffix; } set { value = PropertyHelper.Tidy(value); if (_orbChildPropertySuffix == value) return; _orbChildPropertySuffix = value; OnPropertyChanged(""); } } public string ORBCollectionSuffix { get { return _orbCollectionSuffix; } set { value = PropertyHelper.Tidy(value); if (_orbCollectionSuffix == value) return; _orbCollectionSuffix = value; OnPropertyChanged(""); } } public string ORBSingleSPSuffix { get { return _orbSingleSPSuffix; } set { value = PropertyHelper.Tidy(value); if (_orbSingleSPSuffix == value) return; _orbSingleSPSuffix = value; OnPropertyChanged(""); } } public bool ORBItemsUseSingleSP { get { return _orbItemsUseSingleSP; } set { if (_orbItemsUseSingleSP == value) return; _orbItemsUseSingleSP = value; OnPropertyChanged(""); } } #endregion #region Properties Stored Procedures public string SpAddPrefix { get { return _spAddPrefix; } set { value = PropertyHelper.Tidy(value); if (_spAddPrefix == value) return; _spAddPrefix = value; OnPropertyChanged(""); } } public string SpDeletePrefix { get { return _spDeletePrefix; } set { value = PropertyHelper.Tidy(value); if (_spDeletePrefix == value) return; _spDeletePrefix = value; OnPropertyChanged(""); } } public string SpUpdatePrefix { get { return _spUpdatePrefix; } set { value = PropertyHelper.Tidy(value); if (_spUpdatePrefix == value) return; _spUpdatePrefix = value; OnPropertyChanged(""); } } public string SpGetPrefix { get { return _spGetPrefix; } set { value = PropertyHelper.Tidy(value); if (_spGetPrefix == value) return; _spGetPrefix = value; OnPropertyChanged(""); } } public string SpGeneralPrefix { get { return _spGeneralPrefix; } set { value = PropertyHelper.Tidy(value); if (_spGeneralPrefix == value) return; _spGeneralPrefix = value; OnPropertyChanged(""); } } public string SpAddSuffix { get { return _spAddSuffix; } set { value = PropertyHelper.Tidy(value); if (_spAddSuffix == value) return; _spAddSuffix = value; OnPropertyChanged(""); } } public string SpDeleteSuffix { get { return _spDeleteSuffix; } set { value = PropertyHelper.Tidy(value); if (_spDeleteSuffix == value) return; _spDeleteSuffix = value; OnPropertyChanged(""); } } public string SpUpdateSuffix { get { return _spUpdateSuffix; } set { value = PropertyHelper.Tidy(value); if (_spUpdateSuffix == value) return; _spUpdateSuffix = value; OnPropertyChanged(""); } } public string SpGetSuffix { get { return _spGetSuffix; } set { value = PropertyHelper.Tidy(value); if (_spGetSuffix == value) return; _spGetSuffix = value; OnPropertyChanged(""); } } public string SpGeneralSuffix { get { return _spGeneralSuffix; } set { value = PropertyHelper.Tidy(value); if (_spGeneralSuffix == value) return; _spGeneralSuffix = value; OnPropertyChanged(""); } } public bool RegenSpNameOnObjectRename { get { return _regenSpNameOnObjectRename; } set { if (_regenSpNameOnObjectRename == value) return; _regenSpNameOnObjectRename = value; OnPropertyChanged(""); } } public string SpBoolSoftDeleteColumn { get { return _spBoolSoftDeleteColumn; } set { value = PropertyHelper.Tidy(value); if (_spBoolSoftDeleteColumn == value) return; _spBoolSoftDeleteColumn = value; OnPropertyChanged(""); } } public string SpIntSoftDeleteColumn { get { return _spIntSoftDeleteColumn; } set { value = PropertyHelper.Tidy(value); if (_spIntSoftDeleteColumn == value) return; _spIntSoftDeleteColumn = value; OnPropertyChanged(""); } } public bool SpIgnoreFilterWhenSoftDeleteIsParam { get { return _spIgnoreFilterWhenSoftDeleteIsParam; } set { if (_spIgnoreFilterWhenSoftDeleteIsParam == value) return; _spIgnoreFilterWhenSoftDeleteIsParam = value; OnPropertyChanged(""); } } public bool SpRemoveChildBeforeParent { get { return _spRemoveChildBeforeParent; } set { if (_spRemoveChildBeforeParent == value) return; _spRemoveChildBeforeParent = value; OnPropertyChanged(""); } } public string GetDeleteProcName(string name) { return string.Concat(_spGeneralPrefix, _spDeletePrefix, name, _spDeleteSuffix, _spGeneralSuffix); } public string GetAddProcName(string name) { return string.Concat(_spGeneralPrefix, _spAddPrefix, name, _spAddSuffix, _spGeneralSuffix); } public string GetGetProcName(string name) { return string.Concat(_spGeneralPrefix, _spGetPrefix, name, _spGetSuffix, _spGeneralSuffix); } public string GetUpdateProcName(string name) { return string.Concat(_spGeneralPrefix, _spUpdatePrefix, name, _spUpdateSuffix, _spGeneralSuffix); } #endregion #region Properties Advanced public string IDGuidDefaultValue { get { return _idGuidDefaultValue; } set { value = PropertyHelper.Tidy(value); if (_idGuidDefaultValue == value) return; _idGuidDefaultValue = value; OnPropertyChanged(""); } } public string IDInt16DefaultValue { get { return _idInt16DefaultValue; } set { value = PropertyHelper.Tidy(value); if (_idInt16DefaultValue == value) return; _idInt16DefaultValue = value; OnPropertyChanged(""); } } public string IDInt32DefaultValue { get { return _idInt32DefaultValue; } set { value = PropertyHelper.Tidy(value); if (_idInt32DefaultValue == value) return; _idInt32DefaultValue = value; OnPropertyChanged(""); } } public string IDInt64DefaultValue { get { return _idInt64DefaultValue; } set { value = PropertyHelper.Tidy(value); if (_idInt64DefaultValue == value) return; _idInt64DefaultValue = value; OnPropertyChanged(""); } } public string FieldNamePrefix { get { return _fieldNamePrefix; } set { value = PropertyHelper.Tidy(value); if (_fieldNamePrefix == value) return; _fieldNamePrefix = value; OnPropertyChanged(""); } } public string DelegateNamePrefix { get { return _delegateNamePrefix; } set { value = PropertyHelper.Tidy(value); if (_delegateNamePrefix == value) return; _delegateNamePrefix = value; OnPropertyChanged(""); } } public string CreationDateColumn { get { return _creationDateColumn; } set { value = PropertyHelper.Tidy(value); if (_creationDateColumn == value) return; _creationDateColumn = value; OnPropertyChanged(""); } } public string CreationUserColumn { get { return _creationUserColumn; } set { value = PropertyHelper.Tidy(value); if (_creationUserColumn == value) return; _creationUserColumn = value; OnPropertyChanged(""); } } public string ChangedDateColumn { get { return _changedDateColumn; } set { value = PropertyHelper.Tidy(value); if (_changedDateColumn == value) return; _changedDateColumn = value; OnPropertyChanged(""); } } public string ChangedUserColumn { get { return _changedUserColumn; } set { value = PropertyHelper.Tidy(value); if (_changedUserColumn == value) return; _changedUserColumn = value; OnPropertyChanged(""); } } public bool LogDateAndTime { get { return _logDateAndTime; } set { if (_logDateAndTime == value) return; _logDateAndTime = value; OnPropertyChanged(""); } } public string GetUserMethod { get { return _getUserMethod; } set { value = PropertyHelper.Tidy(value); if (_getUserMethod == value) return; _getUserMethod = value; OnPropertyChanged(""); } } #endregion [Browsable(false)] internal bool Dirty { get; set; } internal ProjectParameters Clone() { ProjectParameters obj = null; try { obj = (ProjectParameters)Util.ObjectCloner.CloneShallow(this); obj.Dirty = false; } catch (Exception ex) { Console.WriteLine(ex.Message); } return obj; } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged(string propertyName) { Dirty = true; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Microsoft.PythonTools.Parsing { /// <summary> /// Provides options for formatting code when calling Node.ToCodeString. /// /// By default a newly created CodeFormattingOptions will result in any /// source code being formatted to be round tripped identical to the original /// input code. Modifying any of the options from the defaults may result in /// the code being formatted according to the option. /// /// For boolean options setting to true will enable altering the code as described, /// and setting them to false will leave the code unmodified. /// /// For bool? options setting the option to true will modify the code one way, setting /// it to false will modify it another way, and setting it to null will leave the code /// unmodified. /// </summary> public sealed class CodeFormattingOptions { internal static CodeFormattingOptions Default = new CodeFormattingOptions(); // singleton with no options set, internal so no one mutates it private static Regex _commentRegex = new Regex("^[\t ]*#+[\t ]*"); private const string _sentenceTerminators = ".!?"; public string NewLineFormat { get; set; } #region Class Definition Options /// <summary> /// Space before the parenthesis in a class declaration. [CodeFormattingExample("class X (object): pass", "class X(object): pass")] [CodeFormattingCategory(CodeFormattingCategory.Classes)] [CodeFormattingDescription("SpaceBeforeClassDeclarationParenShort", "SpaceBeforeClassDeclarationParenLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceBeforeClassDeclarationParen { get; set; } /// <summary> /// Space after the opening paren and before the closing paren in a class definition. /// </summary> [CodeFormattingExample("class X( object ): pass", "class X(object): pass")] [CodeFormattingCategory(CodeFormattingCategory.Classes)] [CodeFormattingDescription("SpaceWithinClassDeclarationParensShort", "SpaceWithinClassDeclarationParensLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinClassDeclarationParens { get; set; } /// <summary> /// Space within empty base class list for a class definition. /// </summary> [CodeFormattingExample("class X( ): pass", "class X(): pass")] [CodeFormattingCategory(CodeFormattingCategory.Classes)] [CodeFormattingDescription("SpaceWithinEmptyBaseClassListShort", "SpaceWithinEmptyBaseClassListLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinEmptyBaseClassList { get; set; } #endregion #region Method Definition Options /* Method Definitions */ /// <summary> /// Space before the parenthesis in a function declaration. [CodeFormattingExample("def X (): pass", "def X(): pass")] [CodeFormattingCategory(CodeFormattingCategory.Functions)] [CodeFormattingDescription("SpaceBeforeFunctionDeclarationParenShort", "SpaceBeforeFunctionDeclarationParenLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceBeforeFunctionDeclarationParen { get; set; } /// <summary> /// Space after the opening paren and before the closing paren in a function definition. /// </summary> [CodeFormattingExample("def X( a, b ): pass", "def X(a, b): pass")] [CodeFormattingCategory(CodeFormattingCategory.Functions)] [CodeFormattingDescription("SpaceWithinFunctionDeclarationParensShort", "SpaceWithinFunctionDeclarationParensLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinFunctionDeclarationParens { get; set; } /// <summary> /// Space within empty parameter list for a function definition. /// </summary> [CodeFormattingExample("def X( ): pass", "def X(): pass")] [CodeFormattingCategory(CodeFormattingCategory.Functions)] [CodeFormattingDescription("SpaceWithinEmptyParameterListShort", "SpaceWithinEmptyParameterListLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinEmptyParameterList { get; set; } /// <summary> /// Spaces around the equals for a default value in a parameter list. /// </summary> [CodeFormattingExample("def X(a = 42): pass", "def X(a=42): pass")] [CodeFormattingCategory(CodeFormattingCategory.Functions)] [CodeFormattingDescription("SpaceAroundDefaultValueEqualsShort", "SpaceAroundDefaultValueEqualsLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceAroundDefaultValueEquals { get; set; } /// <summary> /// Spaces around the arrow annotation in a function definition. /// </summary> [CodeFormattingExample("def X() -> 42: pass", "def X()->42: pass")] [CodeFormattingCategory(CodeFormattingCategory.Functions)] [CodeFormattingDescription("SpaceAroundAnnotationArrowShort", "SpaceAroundAnnotationArrowLong")] [CodeFormattingDefaultValue(true)] public bool? SpaceAroundAnnotationArrow { get; set; } #endregion #region Function Call Options /// <summary> /// Space before the parenthesis in a call expression. /// </summary> [CodeFormattingExample("X ()", "X()")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceBeforeCallParenShort", "SpaceBeforeCallParenLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceBeforeCallParen { get; set; } /// <summary> /// Spaces within the parenthesis in a call expression with no arguments. /// </summary> [CodeFormattingExample("X( )", "X()")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceWithinEmptyCallArgumentListShort", "SpaceWithinEmptyCallArgumentListLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinEmptyCallArgumentList { get; set; } /// <summary> /// Space within the parenthesis in a call expression. /// </summary> [CodeFormattingExample("X( a, b )", "X(a, b)")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceWithinCallParensShort", "SpaceWithinCallParensLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinCallParens { get; set; } #endregion #region Other Spacing [CodeFormattingExample("( a )", "(a)")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpacesWithinParenthesisExpressionShort", "SpacesWithinParenthesisExpressionLong")] [CodeFormattingDefaultValue(false)] public bool? SpacesWithinParenthesisExpression { get; set; } [CodeFormattingExample("( )", "()")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceWithinEmptyTupleExpressionShort", "SpaceWithinEmptyTupleExpressionLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinEmptyTupleExpression { get; set; } [CodeFormattingExample("( a, b )", "(a, b)")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpacesWithinParenthesisedTupleExpressionShort", "SpacesWithinParenthesisedTupleExpressionLong")] [CodeFormattingDefaultValue(false)] public bool? SpacesWithinParenthesisedTupleExpression { get; set; } [CodeFormattingExample("[ ]", "[]")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpacesWithinEmptyListExpressionShort", "SpacesWithinEmptyListExpressionLong")] [CodeFormattingDefaultValue(false)] public bool? SpacesWithinEmptyListExpression { get; set; } [CodeFormattingExample("[ a, b ]", "[a, b]")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpacesWithinListExpressionShort", "SpacesWithinListExpressionLong")] [CodeFormattingDefaultValue(false)] public bool? SpacesWithinListExpression { get; set; } /* Index Expressions */ [CodeFormattingExample("x [i]", "x[i]")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceBeforeIndexBracketShort", "SpaceBeforeIndexBracketLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceBeforeIndexBracket { get; set; } [CodeFormattingExample("x[ i ]", "x[i]")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceWithinIndexBracketsShort", "SpaceWithinIndexBracketsLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinIndexBrackets { get; set; } #endregion #region Operators [CodeFormattingExample("a + b", "a+b")] [CodeFormattingCategory(CodeFormattingCategory.Operators)] [CodeFormattingDescription("SpacesAroundBinaryOperatorsShort", "SpacesAroundBinaryOperatorsLong")] [CodeFormattingDefaultValue(true)] public bool? SpacesAroundBinaryOperators { get; set; } [CodeFormattingExample("a = b", "a=b")] [CodeFormattingCategory(CodeFormattingCategory.Operators)] [CodeFormattingDescription("SpacesAroundAssignmentOperatorShort", "SpacesAroundAssignmentOperatorLong")] [CodeFormattingDefaultValue(true)] public bool? SpacesAroundAssignmentOperator { get; set; } #endregion #region Statements [CodeFormattingExample("import sys\r\nimport pickle", "import sys, pickle")] [CodeFormattingCategory(CodeFormattingCategory.Statements)] [CodeFormattingDescription("ReplaceMultipleImportsWithMultipleStatementsShort", "ReplaceMultipleImportsWithMultipleStatementsLong")] [CodeFormattingDefaultValue(true)] public bool ReplaceMultipleImportsWithMultipleStatements { get; set; } [CodeFormattingExample("x = 42", "x = 42;")] [CodeFormattingCategory(CodeFormattingCategory.Statements)] [CodeFormattingDescription("RemoveTrailingSemicolonsShort", "RemoveTrailingSemicolonsLong")] [CodeFormattingDefaultValue(true)] public bool RemoveTrailingSemicolons { get; set; } [CodeFormattingExample("x = 42\r\ny = 100", "x = 42; y = 100")] [CodeFormattingCategory(CodeFormattingCategory.Statements)] [CodeFormattingDescription("BreakMultipleStatementsPerLineShort", "BreakMultipleStatementsPerLineLong")] [CodeFormattingDefaultValue(true)] public bool BreakMultipleStatementsPerLine { get; set; } #endregion /* #region New Lines [CodeFormattingExample("# Specifies the number of lines which whould appear between top-level classes and functions")] [CodeFormattingCategory(CodeFormattingCategory.NewLines)] [CodeFormattingDescription("LinesBetweenLevelDeclarationsShort", "LinesBetweenLevelDeclarationsLong")] [CodeFormattingDefaultValue(2)] public int LinesBetweenLevelDeclarations { get; set; } [CodeFormattingExample("# Specifies the number of lines between methods in classes")] [CodeFormattingCategory(CodeFormattingCategory.NewLines)] [CodeFormattingDescription("LinesBetweenMethodsInClassShort", "LinesBetweenMethodsInClassLong")] [CodeFormattingDefaultValue(1)] public int LinesBetweenMethodsInClass { get; set; } [CodeFormattingExample("class C:\r\n def f(): pass\r\n\r\n def g(): pass", "class C:\r\n def f(): pass\r\n\r\n\r\n def g(): pass")] [CodeFormattingCategory(CodeFormattingCategory.NewLines)] [CodeFormattingDescription("RemoveExtraLinesBetweenMethodsShort", "RemoveExtraLinesBetweenMethodsLong")] [CodeFormattingDefaultValue(false)] public bool RemoveExtraLinesBetweenMethods { get; set; } #endregion*/ #region Wrapping [CodeFormattingExample("# Wrapped to 40 columns:\r\n# There should be one-- and preferably\r\n# only one --obvious way to do it.", "# Not wapped:\r\n# There should be one-- and preferably only one --obvious way to do it.")] [CodeFormattingCategory(CodeFormattingCategory.Wrapping)] [CodeFormattingDescription("WrapCommentsShort", "WrapCommentsLong")] [CodeFormattingDefaultValue(true)] public bool WrapComments { get; set; } [CodeFormattingExample("Sets the width for wrapping comments and doc strings.")] [CodeFormattingCategory(CodeFormattingCategory.Wrapping)] [CodeFormattingDescription("WrappingWidthShort", "WrappingWidthLong")] [CodeFormattingDefaultValue(80)] public int WrappingWidth { get; set; } #endregion internal bool UseVerbatimImage { get; set; } = true; /// <summary> /// Appends one of 3 strings depending upon a code formatting setting. The 3 settings are the on and off /// settings as well as the original formatting if the setting is not set. /// </summary> internal void Append(StringBuilder res, bool? setting, string ifOn, string ifOff, string originalFormatting) { if (!String.IsNullOrWhiteSpace(originalFormatting) || setting == null) { // there's a comment in the formatting, so we need to preserve it. ReflowComment(res, originalFormatting); } else { res.Append(setting.Value ? ifOn : ifOff); } } /// <summary> /// Given the whitespace from the proceeding line gets the whitespace that should come for following lines. /// /// This strips extra new lines and takes into account the code formatting new lines options. /// </summary> internal string GetNextLineProceedingText(string proceeding) { int newLine; var additionalProceeding = proceeding; if ((newLine = additionalProceeding.LastIndexOfAny(new[] { '\r', '\n' })) == -1) { additionalProceeding = (NewLineFormat ?? Environment.NewLine) + proceeding; } else { // we just want to capture the indentation, not multiple newlines. additionalProceeding = (NewLineFormat ?? Environment.NewLine) + proceeding.Substring(newLine + 1); } return additionalProceeding; } internal void ReflowComment(StringBuilder res, string text) { if (!WrapComments || String.IsNullOrWhiteSpace(text) || text.IndexOf('#') == -1) { res.Append(text); return; } // figure out how many characters we have on the line not related to the comment, // we'll try and align with this. For example: // (1, # This is a comment which will be wrapped // 2, ... // Should wrap to: // (1, # This is a comment // # which will be wrapped // 2, // int charsOnCurrentLine = GetCharsOnLastLine(res); var lines = text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); int lineCount = lines.Length; if (text.EndsWith("\r") || text.EndsWith("\n")) { // split will give us an extra entry, but there's not really an extra line lineCount = lines.Length - 1; } int reflowStartingLine = 0, curLine = 0; do { string commentPrefix = GetCommentPrefix(lines[curLine]); if (commentPrefix == null) { // non-commented line (empty?), just append it and continue // to the next comment prefix if we have one res.Append(lines[curLine] + (curLine == lineCount - 1 ? "" : (NewLineFormat ?? Environment.NewLine))); charsOnCurrentLine = GetCharsOnLastLine(res); reflowStartingLine = curLine + 1; } else if (curLine == lineCount - 1 || GetCommentPrefix(lines[curLine + 1]) != commentPrefix) { // last line, or next line mismatches with our comment prefix. So reflow the text now res.Append( ReflowText( commentPrefix, new string(' ', charsOnCurrentLine) + commentPrefix, // TODO: Tabs instead of spaces NewLineFormat ?? Environment.NewLine, WrappingWidth, lines.Skip(reflowStartingLine).Take(curLine - reflowStartingLine + 1).ToArray() ) ); reflowStartingLine = curLine + 1; } } while (++curLine < lineCount); } private static int GetCharsOnLastLine(StringBuilder res) { for (int i = res.Length - 1; i >= 0; i--) { if (res[i] == '\n' || res[i] == '\r') { return res.Length - i - 1; } } return res.Length; } internal static string GetCommentPrefix(string text) { var match = _commentRegex.Match(text); if (match.Success) { return text.Substring(0, match.Length); } return null; } internal static string ReflowText(string prefix, string additionalLinePrefix, string newLine, int maxLength, string[] lines) { int curLine = 0, curOffset = prefix.Length, linesWritten = 0; int columnCutoff = maxLength - prefix.Length; int defaultColumnCutoff = columnCutoff; StringBuilder newText = new StringBuilder(); while (curLine < lines.Length) { string curLineText = lines[curLine]; int lastSpace = curLineText.Length; // skip leading white space while (curOffset < curLineText.Length && Char.IsWhiteSpace(curLineText[curOffset])) { curOffset++; } // find next word for (int i = curOffset; i < curLineText.Length; i++) { if (Char.IsWhiteSpace(curLineText[i])) { lastSpace = i; break; } } bool startNewLine = lastSpace - curOffset >= columnCutoff && // word won't fit in remaining space columnCutoff != defaultColumnCutoff; // we're not already at the start of a new line if (!startNewLine) { // we found a like break in the region and it's a reasonable size or // we have a really long word that we need to append unbroken if (columnCutoff == defaultColumnCutoff) { // first time we're appending to this line newText.Append(linesWritten == 0 ? prefix : additionalLinePrefix); } newText.Append(curLineText, curOffset, lastSpace - curOffset); // append appropriate spacing if (_sentenceTerminators.IndexOf(curLineText[lastSpace - 1]) != -1 || // we end in punctuation ((lastSpace - curOffset) > 1 && // we close a paren that ends in punctuation curLineText[lastSpace - curOffset] == ')' && _sentenceTerminators.IndexOf(curLineText[lastSpace - 2]) != -1)) { newText.Append(" "); columnCutoff -= lastSpace - curOffset + 2; } else { newText.Append(' '); columnCutoff -= lastSpace - curOffset + 1; } curOffset = lastSpace + 1; // if we reached the end of the line preserve the existing line break. startNewLine = curOffset >= lines[curLine].Length; } if (startNewLine) { // remove any trailing white space while (newText.Length > 0 && newText[newText.Length - 1] == ' ') { newText.Length = newText.Length - 1; } linesWritten++; newText.Append(newLine); columnCutoff = defaultColumnCutoff; } if (curOffset >= lines[curLine].Length) { // we're now reading from the next line curLine++; curOffset = prefix.Length; } } return newText.ToString(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ChangeSignature { [ExportLanguageService(typeof(AbstractChangeSignatureService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeSignatureService : AbstractChangeSignatureService { public override async Task<ISymbol> GetInvocationSymbolAsync( Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.GetRoot(cancellationToken).FindToken(position != tree.Length ? position : Math.Max(0, position - 1)); var ancestorDeclarationKinds = restrictToDeclarations ? _invokableAncestorKinds.Add(SyntaxKind.Block) : _invokableAncestorKinds; SyntaxNode matchingNode = token.Parent.AncestorsAndSelf().FirstOrDefault(n => ancestorDeclarationKinds.Contains(n.Kind())); if (matchingNode == null || matchingNode.IsKind(SyntaxKind.Block)) { return null; } ISymbol symbol; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); symbol = semanticModel.GetDeclaredSymbol(matchingNode, cancellationToken); if (symbol != null) { return symbol; } if (matchingNode.IsKind(SyntaxKind.ObjectCreationExpression)) { var objectCreation = matchingNode as ObjectCreationExpressionSyntax; if (token.Parent.AncestorsAndSelf().Any(a => a == objectCreation.Type)) { var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol; if (typeSymbol != null && typeSymbol.IsKind(SymbolKind.NamedType) && (typeSymbol as ITypeSymbol).TypeKind == TypeKind.Delegate) { return typeSymbol; } } } var symbolInfo = semanticModel.GetSymbolInfo(matchingNode, cancellationToken); return symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault(); } private ImmutableArray<SyntaxKind> _invokableAncestorKinds = new[] { SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.NameMemberCref, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.DelegateDeclaration }.ToImmutableArray(); private ImmutableArray<SyntaxKind> _updatableAncestorKinds = new[] { SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.DelegateDeclaration, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.NameMemberCref }.ToImmutableArray(); private ImmutableArray<SyntaxKind> _updatableNodeKinds = new[] { SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.DelegateDeclaration, SyntaxKind.NameMemberCref, SyntaxKind.AnonymousMethodExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.SimpleLambdaExpression }.ToImmutableArray(); public override SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node) { if (_updatableNodeKinds.Contains(node.Kind())) { return node; } // TODO: file bug about this: var invocation = csnode.Ancestors().FirstOrDefault(a => a.Kind == SyntaxKind.InvocationExpression); var matchingNode = node.AncestorsAndSelf().FirstOrDefault(n => _updatableAncestorKinds.Contains(n.Kind())); if (matchingNode == null) { return null; } var nodeContainingOriginal = GetNodeContainingTargetNode(matchingNode); if (nodeContainingOriginal == null) { return null; } return node.AncestorsAndSelf().Any(n => n == nodeContainingOriginal) ? matchingNode : null; } private SyntaxNode GetNodeContainingTargetNode(SyntaxNode matchingNode) { switch (matchingNode.Kind()) { case SyntaxKind.InvocationExpression: return (matchingNode as InvocationExpressionSyntax).Expression; case SyntaxKind.ElementAccessExpression: return (matchingNode as ElementAccessExpressionSyntax).ArgumentList; case SyntaxKind.ObjectCreationExpression: return (matchingNode as ObjectCreationExpressionSyntax).Type; case SyntaxKind.ConstructorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.Attribute: case SyntaxKind.DelegateDeclaration: case SyntaxKind.NameMemberCref: return matchingNode; default: return null; } } public override SyntaxNode ChangeSignature( Document document, ISymbol declarationSymbol, SyntaxNode potentiallyUpdatedNode, SyntaxNode originalNode, SignatureChange signaturePermutation, CancellationToken cancellationToken) { var updatedNode = potentiallyUpdatedNode as CSharpSyntaxNode; // Update <param> tags. if (updatedNode.IsKind(SyntaxKind.MethodDeclaration) || updatedNode.IsKind(SyntaxKind.ConstructorDeclaration) || updatedNode.IsKind(SyntaxKind.IndexerDeclaration) || updatedNode.IsKind(SyntaxKind.DelegateDeclaration)) { var updatedLeadingTrivia = UpdateParamTagsInLeadingTrivia(updatedNode, declarationSymbol, signaturePermutation); if (updatedLeadingTrivia != null) { updatedNode = updatedNode.WithLeadingTrivia(updatedLeadingTrivia); } } // Update declarations parameter lists if (updatedNode.IsKind(SyntaxKind.MethodDeclaration)) { var method = updatedNode as MethodDeclarationSyntax; var updatedParameters = PermuteDeclaration(method.ParameterList.Parameters, signaturePermutation); return method.WithParameterList(method.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructor = updatedNode as ConstructorDeclarationSyntax; var updatedParameters = PermuteDeclaration(constructor.ParameterList.Parameters, signaturePermutation); return constructor.WithParameterList(constructor.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.IndexerDeclaration)) { var indexer = updatedNode as IndexerDeclarationSyntax; var updatedParameters = PermuteDeclaration(indexer.ParameterList.Parameters, signaturePermutation); return indexer.WithParameterList(indexer.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.DelegateDeclaration)) { var delegateDeclaration = updatedNode as DelegateDeclarationSyntax; var updatedParameters = PermuteDeclaration(delegateDeclaration.ParameterList.Parameters, signaturePermutation); return delegateDeclaration.WithParameterList(delegateDeclaration.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.AnonymousMethodExpression)) { var anonymousMethod = updatedNode as AnonymousMethodExpressionSyntax; // Delegates may omit parameters in C# if (anonymousMethod.ParameterList == null) { return anonymousMethod; } var updatedParameters = PermuteDeclaration(anonymousMethod.ParameterList.Parameters, signaturePermutation); return anonymousMethod.WithParameterList(anonymousMethod.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.SimpleLambdaExpression)) { var lambda = updatedNode as SimpleLambdaExpressionSyntax; if (signaturePermutation.UpdatedConfiguration.ToListOfParameters().Any()) { Debug.Assert(false, "Updating a simple lambda expression without removing its parameter"); } else { // No parameters. Change to a parenthesized lambda expression var emptyParameterList = SyntaxFactory.ParameterList() .WithLeadingTrivia(lambda.Parameter.GetLeadingTrivia()) .WithTrailingTrivia(lambda.Parameter.GetTrailingTrivia()); return SyntaxFactory.ParenthesizedLambdaExpression(lambda.AsyncKeyword, emptyParameterList, lambda.ArrowToken, lambda.RefKeyword, lambda.Body); } } if (updatedNode.IsKind(SyntaxKind.ParenthesizedLambdaExpression)) { var lambda = updatedNode as ParenthesizedLambdaExpressionSyntax; var updatedParameters = PermuteDeclaration(lambda.ParameterList.Parameters, signaturePermutation); return lambda.WithParameterList(lambda.ParameterList.WithParameters(updatedParameters)); } // Update reference site argument lists if (updatedNode.IsKind(SyntaxKind.InvocationExpression)) { var invocation = updatedNode as InvocationExpressionSyntax; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); var symbolInfo = semanticModel.GetSymbolInfo(originalNode as InvocationExpressionSyntax, cancellationToken); var methodSymbol = symbolInfo.Symbol as IMethodSymbol; var isReducedExtensionMethod = false; if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.ReducedExtension) { isReducedExtensionMethod = true; } var newArguments = PermuteArgumentList(document, declarationSymbol, invocation.ArgumentList.Arguments, signaturePermutation, isReducedExtensionMethod); return invocation.WithArgumentList(invocation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ObjectCreationExpression)) { var objCreation = updatedNode as ObjectCreationExpressionSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation); return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ThisConstructorInitializer) || updatedNode.IsKind(SyntaxKind.BaseConstructorInitializer)) { var objCreation = updatedNode as ConstructorInitializerSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation); return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ElementAccessExpression)) { var elementAccess = updatedNode as ElementAccessExpressionSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, elementAccess.ArgumentList.Arguments, signaturePermutation); return elementAccess.WithArgumentList(elementAccess.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.Attribute)) { var attribute = updatedNode as AttributeSyntax; var newArguments = PermuteAttributeArgumentList(document, declarationSymbol, attribute.ArgumentList.Arguments, signaturePermutation); return attribute.WithArgumentList(attribute.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } // Handle references in crefs if (updatedNode.IsKind(SyntaxKind.NameMemberCref)) { var nameMemberCref = updatedNode as NameMemberCrefSyntax; if (nameMemberCref.Parameters == null || !nameMemberCref.Parameters.Parameters.Any()) { return nameMemberCref; } var newParameters = PermuteDeclaration(nameMemberCref.Parameters.Parameters, signaturePermutation); var newCrefParameterList = nameMemberCref.Parameters.WithParameters(newParameters); return nameMemberCref.WithParameters(newCrefParameterList); } Debug.Assert(false, "Unknown reference location"); return null; } private SeparatedSyntaxList<T> PermuteDeclaration<T>(SeparatedSyntaxList<T> list, SignatureChange updatedSignature) where T : SyntaxNode { var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var newParameters = new List<T>(); foreach (var newParam in reorderedParameters) { var pos = originalParameters.IndexOf(newParam); var param = list[pos]; newParameters.Add(param); } var numSeparatorsToSkip = originalParameters.Count - reorderedParameters.Count; return SyntaxFactory.SeparatedList(newParameters, GetSeparators(list, numSeparatorsToSkip)); } private static SeparatedSyntaxList<AttributeArgumentSyntax> PermuteAttributeArgumentList( Document document, ISymbol declarationSymbol, SeparatedSyntaxList<AttributeArgumentSyntax> arguments, SignatureChange updatedSignature) { var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature); var numSeparatorsToSkip = arguments.Count - newArguments.Count; return SyntaxFactory.SeparatedList(newArguments.Select(a => (AttributeArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip)); } private static SeparatedSyntaxList<ArgumentSyntax> PermuteArgumentList( Document document, ISymbol declarationSymbol, SeparatedSyntaxList<ArgumentSyntax> arguments, SignatureChange updatedSignature, bool isReducedExtensionMethod = false) { var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature, isReducedExtensionMethod); var numSeparatorsToSkip = arguments.Count - newArguments.Count; return SyntaxFactory.SeparatedList(newArguments.Select(a => (ArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip)); } private List<SyntaxTrivia> UpdateParamTagsInLeadingTrivia(CSharpSyntaxNode node, ISymbol declarationSymbol, SignatureChange updatedSignature) { if (!node.HasLeadingTrivia) { return null; } var paramNodes = node .DescendantNodes(descendIntoTrivia: true) .OfType<XmlElementSyntax>() .Where(e => e.StartTag.Name.ToString() == DocumentationCommentXmlNames.ParameterElementName); var permutedParamNodes = VerifyAndPermuteParamNodes(paramNodes, declarationSymbol, updatedSignature); if (permutedParamNodes == null) { return null; } return GetPermutedTrivia(node, permutedParamNodes); } private List<XmlElementSyntax> VerifyAndPermuteParamNodes(IEnumerable<XmlElementSyntax> paramNodes, ISymbol declarationSymbol, SignatureChange updatedSignature) { // Only reorder if count and order match originally. var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var declaredParameters = declarationSymbol.GetParameters(); if (paramNodes.Count() != declaredParameters.Count()) { return null; } var dictionary = new Dictionary<string, XmlElementSyntax>(); int i = 0; foreach (var paramNode in paramNodes) { var nameAttribute = paramNode.StartTag.Attributes.FirstOrDefault(a => a.Name.ToString().Equals("name", StringComparison.OrdinalIgnoreCase)); if (nameAttribute == null) { return null; } var identifier = nameAttribute.DescendantNodes(descendIntoTrivia: true).OfType<IdentifierNameSyntax>().FirstOrDefault(); if (identifier == null || identifier.ToString() != declaredParameters.ElementAt(i).Name) { return null; } dictionary.Add(originalParameters[i].Name.ToString(), paramNode); i++; } // Everything lines up, so permute them. var permutedParams = new List<XmlElementSyntax>(); foreach (var parameter in reorderedParameters) { permutedParams.Add(dictionary[parameter.Name]); } return permutedParams; } private List<SyntaxTrivia> GetPermutedTrivia(CSharpSyntaxNode node, List<XmlElementSyntax> permutedParamNodes) { var updatedLeadingTrivia = new List<SyntaxTrivia>(); var index = 0; foreach (var trivia in node.GetLeadingTrivia()) { if (!trivia.HasStructure) { updatedLeadingTrivia.Add(trivia); continue; } var structuredTrivia = trivia.GetStructure() as DocumentationCommentTriviaSyntax; if (structuredTrivia == null) { updatedLeadingTrivia.Add(trivia); continue; } var updatedNodeList = new List<XmlNodeSyntax>(); var structuredContent = structuredTrivia.Content.ToList(); for (int i = 0; i < structuredContent.Count; i++) { var content = structuredContent[i]; if (!content.IsKind(SyntaxKind.XmlElement)) { updatedNodeList.Add(content); continue; } var xmlElement = content as XmlElementSyntax; if (xmlElement.StartTag.Name.ToString() != DocumentationCommentXmlNames.ParameterElementName) { updatedNodeList.Add(content); continue; } // Found a param tag, so insert the next one from the reordered list if (index < permutedParamNodes.Count) { updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia())); index++; } else { // Inspecting a param element that we are deleting but not replacing. } } var newDocComments = SyntaxFactory.DocumentationCommentTrivia(structuredTrivia.Kind(), SyntaxFactory.List(updatedNodeList.AsEnumerable())); newDocComments = newDocComments.WithEndOfComment(structuredTrivia.EndOfComment); newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia()); var newTrivia = SyntaxFactory.Trivia(newDocComments); updatedLeadingTrivia.Add(newTrivia); } return updatedLeadingTrivia; } private static List<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip = 0) where T : SyntaxNode { var separators = new List<SyntaxToken>(); for (int i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++) { separators.Add(arguments.GetSeparator(i)); } return separators; } public override async Task<IEnumerable<ISymbol>> DetermineCascadedSymbolsFromDelegateInvoke(IMethodSymbol symbol, Document document, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var nodes = root.DescendantNodes(); var convertedMethodGroups = nodes .Where( n => { if (!n.IsKind(SyntaxKind.IdentifierName) || !semanticModel.GetMemberGroup(n, cancellationToken).Any()) { return false; } ISymbol convertedType = semanticModel.GetTypeInfo(n, cancellationToken).ConvertedType; if (convertedType != null) { convertedType = convertedType.OriginalDefinition; } if (convertedType != null) { convertedType = SymbolFinder.FindSourceDefinitionAsync(convertedType, document.Project.Solution, cancellationToken).WaitAndGetResult(cancellationToken) ?? convertedType; } return convertedType == symbol.ContainingType; }) .Select(n => semanticModel.GetSymbolInfo(n, cancellationToken).Symbol); return convertedMethodGroups; } protected override IEnumerable<IFormattingRule> GetFormattingRules(Document document) { return new[] { new ChangeSignatureFormattingRule() }.Concat(Formatter.GetDefaultFormattingRules(document)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace O4ZI.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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); } } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion // With this define each iref object gets a unique number (uid) to make them distinguishable in the debugger #define UNIQUE_IREF_ using System; using System.Collections.Generic; using System.Diagnostics; using PdfSharp.Pdf.IO; namespace PdfSharp.Pdf.Advanced { /// <summary> /// Represents an indirect reference to a PdfObject. /// </summary> [DebuggerDisplay("iref({ObjectNumber}, {GenerationNumber})")] public sealed class PdfReference : PdfItem { // About PdfReference // // * A PdfReference holds either the ObjectID or the PdfObject or both. // // * Each PdfObject has a PdfReference if and only if it is an indirect object. Direct objects have // no PdfReference, because they are embedded in a parent objects. // // * PdfReference objects are used to reference PdfObject instances. A value in a PDF dictionary // or array that is a PdfReference represents an indirect reference. A value in a PDF dictionary or // or array that is a PdfObject represents a direct (or embeddded) object. // // * When a PDF file is imported, the PdfXRefTable is filled with PdfReference objects keeping the // ObjectsIDs and file positions (offsets) of all indirect objects. // // * Indirect objects can easily be renumbered because they do not rely on their ObjectsIDs. // // * During modification of a document the ObjectID of an indirect object has no meaning, // except that they must be different in pairs. /// <summary> /// Initializes a new PdfReference instance for the specified indirect object. /// </summary> public PdfReference(PdfObject pdfObject) { if (pdfObject.Reference != null) throw new InvalidOperationException("Must not create iref for an object that already has one."); _value = pdfObject; pdfObject.Reference = this; #if UNIQUE_IREF && DEBUG _uid = ++s_counter; #endif } /// <summary> /// Initializes a new PdfReference instance from the specified object identifier and file position. /// </summary> public PdfReference(PdfObjectID objectID, int position) { _objectID = objectID; _position = position; #if UNIQUE_IREF && DEBUG _uid = ++s_counter; #endif } /// <summary> /// Writes the object in PDF iref table format. /// </summary> internal void WriteXRefEnty(PdfWriter writer) { // PDFsharp does not yet support PDF 1.5 object streams. // Each line must be exactly 20 bytes long, otherwise Acrobat repairs the file. string text = String.Format("{0:0000000000} {1:00000} n\n", _position, _objectID.GenerationNumber); // InUse ? 'n' : 'f'); writer.WriteRaw(text); } /// <summary> /// Writes an indirect reference. /// </summary> internal override void WriteObject(PdfWriter writer) { writer.Write(this); } /// <summary> /// Gets or sets the object identifier. /// </summary> public PdfObjectID ObjectID { get { return _objectID; } set { // Ignore redundant invokations. if (_objectID == value) return; _objectID = value; if (Document != null) { //PdfXRefTable table = Document.xrefTable; //table.Remove(this); //objectID = value; //table.Add(this); } } } PdfObjectID _objectID; /// <summary> /// Gets the object number of the object identifier. /// </summary> public int ObjectNumber { get { return _objectID.ObjectNumber; } } /// <summary> /// Gets the generation number of the object identifier. /// </summary> public int GenerationNumber { get { return _objectID.GenerationNumber; } } /// <summary> /// Gets or sets the file position of the related PdfObject. /// </summary> public int Position { get { return _position; } set { _position = value; } } int _position; // I know it should be long, but I have never seen a 2GB PDF file. //public bool InUse //{ // get {return inUse;} // set {inUse = value;} //} //bool inUse; /// <summary> /// Gets or sets the referenced PdfObject. /// </summary> public PdfObject Value { get { return _value; } set { Debug.Assert(value != null, "The value of a PdfReference must never be null."); Debug.Assert(value.Reference == null || ReferenceEquals(value.Reference, this), "The reference of the value must be null or this."); _value = value; // value must never be null value.Reference = this; } } PdfObject _value; /// <summary> /// Hack for dead objects. /// </summary> internal void SetObject(PdfObject value) { _value = value; } /// <summary> /// Gets or sets the document this object belongs to. /// </summary> public PdfDocument Document { get { return _document; } set { _document = value; } } PdfDocument _document; /// <summary> /// Gets a string representing the object identifier. /// </summary> public override string ToString() { return _objectID + " R"; } internal static PdfReferenceComparer Comparer { get { return new PdfReferenceComparer(); } } /// <summary> /// Implements a comparer that compares PdfReference objects by their PdfObjectID. /// </summary> internal class PdfReferenceComparer : IComparer<PdfReference> { public int Compare(PdfReference x, PdfReference y) { PdfReference l = x; PdfReference r = y; if (l != null) { if (r != null) return l._objectID.CompareTo(r._objectID); return -1; } if (r != null) return 1; return 0; } } #if UNIQUE_IREF && DEBUG static int s_counter = 0; int _uid; #endif } }
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using Mirabeau.DatabaseReleaseTool.Arguments; using Mirabeau.DatabaseReleaseTool.Connection; using Mirabeau.DatabaseReleaseTool.Files; using Mirabeau.DatabaseReleaseTool.Logging; using Mirabeau.DatabaseReleaseTool.Policies; using Mirabeau.DatabaseReleaseTool.Sql; namespace Mirabeau.DatabaseReleaseTool { public class DatabaseReleaseTool { #region Fields private readonly IConnectionStringFactory _connectionStringFactory; private readonly IFileStructurePolicy _createDatabasePolicy; private readonly IDatabaseConnectionFactory _databaseConnectionFactory; private readonly DirectoryInfo _databaseScriptsDirInfo; private readonly IFileStructurePolicy _fileStructurePolicy; private readonly IOutputLogger _outputLogger; #endregion #region Constructors and Destructors public DatabaseReleaseTool( string databaseScriptPath, IFileStructurePolicy createDatabasePolicy, IFileStructurePolicy fileStructurePolicy, IOutputLogger outputLogger, IConnectionStringFactory connectionStringFactory, IDatabaseConnectionFactory databaseConnectionFactory) { if (outputLogger == null) { throw new ArgumentNullException("outputLogger"); } if (string.IsNullOrEmpty(databaseScriptPath)) { throw new ArgumentException(@"Cannot be null or empty.", "databaseScriptPath"); } if (!Directory.Exists(databaseScriptPath)) { throw new DirectoryNotFoundException(string.Format("Path: {0} does not exist.", databaseScriptPath)); } _createDatabasePolicy = createDatabasePolicy; _fileStructurePolicy = fileStructurePolicy; _outputLogger = outputLogger; _connectionStringFactory = connectionStringFactory; _databaseConnectionFactory = databaseConnectionFactory; _databaseScriptsDirInfo = new DirectoryInfo(databaseScriptPath); } #endregion #region Public Methods and Operators public ExcecutionResult Execute( string fromVersion, string toVersion, DatabaseConnectionParameters connectionParameters, Encoding encodingForReadingSqlScripts) { var excecutionResult = new ExcecutionResult { Success = true }; if (connectionParameters.BeforeExecuteScriptsAction == BeforeExecuteScriptsAction.CreateDatabase) { excecutionResult = ExecuteCreateDatabase(connectionParameters, encodingForReadingSqlScripts); } if (excecutionResult.Success) { excecutionResult = ExecuteAllScriptsForDatabase(fromVersion, toVersion, connectionParameters, encodingForReadingSqlScripts); } return excecutionResult; } public virtual ExcecutionResult ExecuteAllScriptsForDatabase( string fromVersion, string toVersion, DatabaseConnectionParameters connectionParameters, Encoding encodingForReadingSqlScripts) { if (string.IsNullOrEmpty(fromVersion)) { throw new ArgumentException(@"Cannot be null or empty.", "fromVersion"); } if (string.IsNullOrEmpty(toVersion)) { throw new ArgumentException(@"Cannot be null or empty.", "toVersion"); } if (encodingForReadingSqlScripts == null) { encodingForReadingSqlScripts = Encoding.Default; } Version fromVersionObject; Version toVersionObject; try { fromVersionObject = VersionNumberHelper.RemoveNegativeNumbersFromVersionObject(new Version(fromVersion)); } catch (Exception ex) { var result = new ExcecutionResult { Success = false }; result.Errors.Add( string.Format("Invalid fromVersion. Could not parse fromVersion to a usable version object. {0}", ex.Message)); return result; } try { toVersionObject = VersionNumberHelper.RemoveNegativeNumbersFromVersionObject(new Version(toVersion)); } catch (Exception ex) { var result = new ExcecutionResult { Success = false }; result.Errors.Add(string.Format("Invalid toVersion. Could not parse toVersion to a usable version object. {0}", ex.Message)); return result; } // Execute optional FileStructurePolicy if (_fileStructurePolicy != null) { PolicyResult policyResult = _fileStructurePolicy.Check(_databaseScriptsDirInfo); if (!policyResult.Success) { // Policy failed Return errors ExcecutionResult result = new ExcecutionResult { Success = false }; result.Errors.AddRange(policyResult.Messages); return result; } } SqlFilesListReader filesReader = new SqlFilesListReader(_databaseScriptsDirInfo); Dictionary<string, FileInfo> filesToExecute = filesReader.GetSpecificVersionedFilesToExecute(fromVersionObject, toVersionObject); return ExecuteSqlScripts(connectionParameters, filesToExecute, encodingForReadingSqlScripts); } public virtual ExcecutionResult ExecuteCreateDatabase( DatabaseConnectionParameters connectionParameters, Encoding encodingForReadingSqlScripts) { // Execute optional FileStructurePolicy if (_createDatabasePolicy != null) { PolicyResult policyResult = _createDatabasePolicy.Check(_databaseScriptsDirInfo); if (!policyResult.Success) { // Policy failed Return errors ExcecutionResult result = new ExcecutionResult { Success = false }; result.Errors.AddRange(policyResult.Messages); return result; } } SqlFilesListReader filesReader = new SqlFilesListReader(_databaseScriptsDirInfo); Dictionary<string, FileInfo> filesToExecute = filesReader.GetCreateDatabaseFileToExecute(); return ExecuteNonTransactionalCreateDatabaseSqlScripts(connectionParameters, filesToExecute, encodingForReadingSqlScripts); } #endregion #region Methods private IDbConnection CreateDbConnection(DatabaseConnectionParameters connectionParameters) { string connectionString = _connectionStringFactory.Create(connectionParameters); return _databaseConnectionFactory.CreateDatabaseConnection(connectionString, connectionParameters.DatabaseType); } private ExcecutionResult ExecuteNonTransactionalCreateDatabaseSqlScripts( DatabaseConnectionParameters connectionParameters, Dictionary<string, FileInfo> filesToExecute, Encoding encodingForReadingSqlScripts) { IDbConnection connection = CreateDbConnection(connectionParameters); TransactionalSqlFileExecutor sqlFileExecutor = new TransactionalSqlFileExecutor(connection, _outputLogger); try { sqlFileExecutor.ExecuteNonTransactional(filesToExecute.Select(item => item.Key).ToList(), encodingForReadingSqlScripts); } catch (TransactionalSqlFileExecutorException exception) { var result = new ExcecutionResult { Success = false }; result.Errors.Add(exception.Message); result.Errors.Add(exception.InnerException.Message); return result; } return new ExcecutionResult { Success = true }; } private ExcecutionResult ExecuteSqlScripts( DatabaseConnectionParameters connectionParameters, Dictionary<string, FileInfo> filesToExecute, Encoding encodingForReadingSqlScripts) { connectionParameters.BeforeExecuteScriptsAction = BeforeExecuteScriptsAction.None; IDbConnection connection = CreateDbConnection(connectionParameters); TransactionalSqlFileExecutor sqlFileExecutor = new TransactionalSqlFileExecutor(connection, _outputLogger); try { sqlFileExecutor.ExecuteTransactional(filesToExecute.Select(item => item.Key).ToList(), encodingForReadingSqlScripts); } catch (TransactionalSqlFileExecutorRollbackException exception) { var result = new ExcecutionResult { Success = false }; result.Errors.Add(exception.Message); result.Errors.Add(exception.MainException.Message); result.Errors.Add(exception.InnerException.Message); return result; } catch (TransactionalSqlFileExecutorException exception) { var result = new ExcecutionResult { Success = false }; result.Errors.Add(exception.Message); result.Errors.Add(exception.InnerException.Message); return result; } return new ExcecutionResult { Success = true }; } #endregion } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace FabricSharePointAppWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
using System; using Csla; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERCLevel; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F09_Region_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="F09_Region_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="F08_Region"/> collection. /// </remarks> [Serializable] public partial class F09_Region_ReChild : BusinessBase<F09_Region_ReChild> { #region State Fields [NotUndoable] [NonSerialized] internal int region_ID2 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name"); /// <summary> /// Gets or sets the Cities Child Name. /// </summary> /// <value>The Cities Child Name.</value> public string Region_Child_Name { get { return GetProperty(Region_Child_NameProperty); } set { SetProperty(Region_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F09_Region_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="F09_Region_ReChild"/> object.</returns> internal static F09_Region_ReChild NewF09_Region_ReChild() { return DataPortal.CreateChild<F09_Region_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="F09_Region_ReChild"/> object from the given F09_Region_ReChildDto. /// </summary> /// <param name="data">The <see cref="F09_Region_ReChildDto"/>.</param> /// <returns>A reference to the fetched <see cref="F09_Region_ReChild"/> object.</returns> internal static F09_Region_ReChild GetF09_Region_ReChild(F09_Region_ReChildDto data) { F09_Region_ReChild obj = new F09_Region_ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); // check all object rules and property rules obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F09_Region_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F09_Region_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="F09_Region_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F09_Region_ReChild"/> object from the given <see cref="F09_Region_ReChildDto"/>. /// </summary> /// <param name="data">The F09_Region_ReChildDto to use.</param> private void Fetch(F09_Region_ReChildDto data) { // Value properties LoadProperty(Region_Child_NameProperty, data.Region_Child_Name); // parent properties region_ID2 = data.Parent_Region_ID; var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="F09_Region_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F08_Region parent) { var dto = new F09_Region_ReChildDto(); dto.Parent_Region_ID = parent.Region_ID; dto.Region_Child_Name = Region_Child_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IF09_Region_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="F09_Region_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(F08_Region parent) { if (!IsDirty) return; var dto = new F09_Region_ReChildDto(); dto.Parent_Region_ID = parent.Region_ID; dto.Region_Child_Name = Region_Child_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IF09_Region_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="F09_Region_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(F08_Region parent) { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IF09_Region_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Region_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void FloorSingle() { var test = new SimpleUnaryOpTest__FloorSingle(); 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 SimpleUnaryOpTest__FloorSingle { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data = new Single[Op1ElementCount]; private static Vector256<Single> _clsVar; private Vector256<Single> _fld; private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable; static SimpleUnaryOpTest__FloorSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__FloorSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } _dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.Floor( Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.Floor( Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.Floor( Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.Floor), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.Floor), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.Floor), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.Floor( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr); var result = Avx.Floor(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)); var result = Avx.Floor(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)); var result = Avx.Floor(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__FloorSingle(); var result = Avx.Floor(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.Floor(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Single> firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[0]))) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[i]))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Floor)}<Single>(Vector256<Single>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Globalization; using System.Runtime.Serialization; namespace System.Drawing.Printing { /// <summary> /// Specifies the margins of a printed page. /// </summary> #if netcoreapp [TypeConverter("System.Drawing.Printing.MarginsConverter, System.Windows.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")] #endif public partial class Margins : ICloneable { private int _left; private int _right; private int _bottom; private int _top; [OptionalField] private double _doubleLeft; [OptionalField] private double _doubleRight; [OptionalField] private double _doubleTop; [OptionalField] private double _doubleBottom; /// <summary> /// Initializes a new instance of a the <see cref='Margins'/> class with one-inch margins. /// </summary> public Margins() : this(100, 100, 100, 100) { } /// <summary> /// Initializes a new instance of a the <see cref='Margins'/> class with the specified left, right, top, and bottom margins. /// </summary> public Margins(int left, int right, int top, int bottom) { CheckMargin(left, nameof(left)); CheckMargin(right, nameof(right)); CheckMargin(top, nameof(top)); CheckMargin(bottom, nameof(bottom)); _left = left; _right = right; _top = top; _bottom = bottom; _doubleLeft = (double)left; _doubleRight = (double)right; _doubleTop = (double)top; _doubleBottom = (double)bottom; } /// <summary> /// Gets or sets the left margin, in hundredths of an inch. /// </summary> public int Left { get { return _left; } set { CheckMargin(value, "Left"); _left = value; _doubleLeft = (double)value; } } /// <summary> /// Gets or sets the right margin, in hundredths of an inch. /// </summary> public int Right { get { return _right; } set { CheckMargin(value, "Right"); _right = value; _doubleRight = (double)value; } } /// <summary> /// Gets or sets the top margin, in hundredths of an inch. /// </summary> public int Top { get { return _top; } set { CheckMargin(value, "Top"); _top = value; _doubleTop = (double)value; } } /// <summary> /// Gets or sets the bottom margin, in hundredths of an inch. /// </summary> public int Bottom { get { return _bottom; } set { CheckMargin(value, "Bottom"); _bottom = value; _doubleBottom = (double)value; } } /// <summary> /// Gets or sets the left margin with double value, in hundredths of an inch. /// When use the setter, the ranger of setting double value should between /// 0 to Int.MaxValue; /// </summary> internal double DoubleLeft { get { return _doubleLeft; } set { Left = (int)Math.Round(value); _doubleLeft = value; } } /// <summary> /// Gets or sets the right margin with double value, in hundredths of an inch. /// When use the setter, the ranger of setting double value should between /// 0 to Int.MaxValue; /// </summary> internal double DoubleRight { get { return _doubleRight; } set { Right = (int)Math.Round(value); _doubleRight = value; } } /// <summary> /// Gets or sets the top margin with double value, in hundredths of an inch. /// When use the setter, the ranger of setting double value should between /// 0 to Int.MaxValue; /// </summary> internal double DoubleTop { get { return _doubleTop; } set { Top = (int)Math.Round(value); _doubleTop = value; } } /// <summary> /// Gets or sets the bottom margin with double value, in hundredths of an inch. /// When use the setter, the ranger of setting double value should between /// 0 to Int.MaxValue; /// </summary> internal double DoubleBottom { get { return _doubleBottom; } set { Bottom = (int)Math.Round(value); _doubleBottom = value; } } private void CheckMargin(int margin, string name) { if (margin < 0) throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx, name, margin, "0")); } /// <summary> /// Retrieves a duplicate of this object, member by member. /// </summary> public object Clone() { return MemberwiseClone(); } /// <summary> /// Compares this <see cref='Margins'/> to a specified <see cref='Margins'/> to see whether they /// are equal. /// </summary> public override bool Equals(object obj) { Margins margins = obj as Margins; if (margins == this) return true; if (margins == null) return false; return margins.Left == Left && margins.Right == Right && margins.Top == Top && margins.Bottom == Bottom; } /// <summary> /// Calculates and retrieves a hash code based on the left, right, top, and bottom margins. /// </summary> public override int GetHashCode() { // return HashCodes.Combine(left, right, top, bottom); uint left = (uint)Left; uint right = (uint)Right; uint top = (uint)Top; uint bottom = (uint)Bottom; uint result = left ^ ((right << 13) | (right >> 19)) ^ ((top << 26) | (top >> 6)) ^ ((bottom << 7) | (bottom >> 25)); return unchecked((int)result); } /// <summary> /// Tests whether two <see cref='Margins'/> objects are identical. /// </summary> public static bool operator ==(Margins m1, Margins m2) { if (object.ReferenceEquals(m1, null) != object.ReferenceEquals(m2, null)) { return false; } if (!object.ReferenceEquals(m1, null)) { return m1.Left == m2.Left && m1.Top == m2.Top && m1.Right == m2.Right && m1.Bottom == m2.Bottom; } return true; } /// <summary> /// Tests whether two <see cref='Margins'/> objects are different. /// </summary> public static bool operator !=(Margins m1, Margins m2) { return !(m1 == m2); } /// <summary> /// Provides some interesting information for the Margins in String form. /// </summary> public override string ToString() { return "[Margins" + " Left=" + Left.ToString(CultureInfo.InvariantCulture) + " Right=" + Right.ToString(CultureInfo.InvariantCulture) + " Top=" + Top.ToString(CultureInfo.InvariantCulture) + " Bottom=" + Bottom.ToString(CultureInfo.InvariantCulture) + "]"; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Threading; using osu.Game.Extensions; using osu.Game.Graphics.Cursor; using osu.Game.Graphics.UserInterface; using osu.Game.Input.Bindings; using osu.Game.Online.Rooms; using osuTK; namespace osu.Game.Screens.OnlinePlay.Lounge.Components { public class RoomsContainer : CompositeDrawable, IKeyBindingHandler<GlobalAction> { public Action<Room> JoinRequested; private readonly IBindableList<Room> rooms = new BindableList<Room>(); private readonly FillFlowContainer<DrawableRoom> roomFlow; public IReadOnlyList<DrawableRoom> Rooms => roomFlow; [Resolved(CanBeNull = true)] private Bindable<FilterCriteria> filter { get; set; } [Resolved] private Bindable<Room> selectedRoom { get; set; } [Resolved] private IRoomManager roomManager { get; set; } [Resolved(CanBeNull = true)] private LoungeSubScreen loungeSubScreen { get; set; } // handle deselection public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true; public RoomsContainer() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = new OsuContextMenuContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Child = roomFlow = new FillFlowContainer<DrawableRoom> { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(2), } }; } protected override void LoadComplete() { rooms.CollectionChanged += roomsChanged; roomManager.RoomsUpdated += updateSorting; rooms.BindTo(roomManager.Rooms); filter?.BindValueChanged(criteria => Filter(criteria.NewValue)); selectedRoom.BindValueChanged(selection => { updateSelection(); }, true); } private void updateSelection() => roomFlow.Children.ForEach(r => r.State = r.Room == selectedRoom.Value ? SelectionState.Selected : SelectionState.NotSelected); public void Filter(FilterCriteria criteria) { roomFlow.Children.ForEach(r => { if (criteria == null) r.MatchingFilter = true; else { bool matchingFilter = true; matchingFilter &= r.Room.Playlist.Count == 0 || criteria.Ruleset == null || r.Room.Playlist.Any(i => i.Ruleset.Value.Equals(criteria.Ruleset)); if (!string.IsNullOrEmpty(criteria.SearchString)) matchingFilter &= r.FilterTerms.Any(term => term.Contains(criteria.SearchString, StringComparison.InvariantCultureIgnoreCase)); r.MatchingFilter = matchingFilter; } }); } private void roomsChanged(object sender, NotifyCollectionChangedEventArgs args) { switch (args.Action) { case NotifyCollectionChangedAction.Add: addRooms(args.NewItems.Cast<Room>()); break; case NotifyCollectionChangedAction.Remove: removeRooms(args.OldItems.Cast<Room>()); break; } } private void addRooms(IEnumerable<Room> rooms) { foreach (var room in rooms) { roomFlow.Add(new DrawableRoom(room) { Action = () => { if (room == selectedRoom.Value) { joinSelected(); return; } selectRoom(room); } }); } Filter(filter?.Value); updateSelection(); } private void removeRooms(IEnumerable<Room> rooms) { foreach (var r in rooms) { var toRemove = roomFlow.Single(d => d.Room == r); toRemove.Action = null; roomFlow.Remove(toRemove); selectRoom(null); } } private void updateSorting() { foreach (var room in roomFlow) roomFlow.SetLayoutPosition(room, room.Room.Position.Value); } private void selectRoom(Room room) => selectedRoom.Value = room; private void joinSelected() { if (selectedRoom.Value == null) return; JoinRequested?.Invoke(selectedRoom.Value); } protected override bool OnClick(ClickEvent e) { selectRoom(null); return base.OnClick(e); } #region Key selection logic (shared with BeatmapCarousel) public bool OnPressed(GlobalAction action) { switch (action) { case GlobalAction.Select: joinSelected(); return true; case GlobalAction.SelectNext: beginRepeatSelection(() => selectNext(1), action); return true; case GlobalAction.SelectPrevious: beginRepeatSelection(() => selectNext(-1), action); return true; } return false; } public void OnReleased(GlobalAction action) { switch (action) { case GlobalAction.SelectNext: case GlobalAction.SelectPrevious: endRepeatSelection(action); break; } } private ScheduledDelegate repeatDelegate; private object lastRepeatSource; /// <summary> /// Begin repeating the specified selection action. /// </summary> /// <param name="action">The action to perform.</param> /// <param name="source">The source of the action. Used in conjunction with <see cref="endRepeatSelection"/> to only cancel the correct action (most recently pressed key).</param> private void beginRepeatSelection(Action action, object source) { endRepeatSelection(); lastRepeatSource = source; repeatDelegate = this.BeginKeyRepeat(Scheduler, action); } private void endRepeatSelection(object source = null) { // only the most recent source should be able to cancel the current action. if (source != null && !EqualityComparer<object>.Default.Equals(lastRepeatSource, source)) return; repeatDelegate?.Cancel(); repeatDelegate = null; lastRepeatSource = null; } private void selectNext(int direction) { var visibleRooms = Rooms.AsEnumerable().Where(r => r.IsPresent); Room room; if (selectedRoom.Value == null) room = visibleRooms.FirstOrDefault()?.Room; else { if (direction < 0) visibleRooms = visibleRooms.Reverse(); room = visibleRooms.SkipWhile(r => r.Room != selectedRoom.Value).Skip(1).FirstOrDefault()?.Room; } // we already have a valid selection only change selection if we still have a room to switch to. if (room != null) selectRoom(room); } #endregion protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (roomManager != null) roomManager.RoomsUpdated -= updateSorting; } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; namespace Scientia.HtmlRenderer.Adapters.Entities { /// <summary> /// Stores an ordered pair of floating-point numbers, typically the width and height of a rectangle. /// </summary> public struct RSize { #region Fields and Consts /// <summary> /// Gets a <see cref="RSize" /> structure that has a /// <see /// cref="RSize.Height" /> /// and /// <see /// cref="RSize.Width" /> /// value of 0. /// </summary> /// <returns> /// A <see cref="RSize" /> structure that has a /// <see /// cref="RSize.Height" /> /// and /// <see /// cref="RSize.Width" /> /// value of 0. /// </returns> /// <filterpriority>1</filterpriority> public static readonly RSize Empty = new RSize(); #endregion /// <summary> /// Initializes a new instance of the <see cref="RSize" /> structure from the specified existing /// <see /// cref="RSize" /> /// structure. /// </summary> /// <param name="size"> /// The <see cref="RSize" /> structure from which to create the new /// <see /// cref="RSize" /> /// structure. /// </param> public RSize(RSize size) { this.Width = size.Width; this.Height = size.Height; } /// <summary> /// Initializes a new instance of the <see cref="RSize" /> structure from the specified <see cref="RPoint" /> structure. /// </summary> /// <param name="pt">The <see cref="RPoint" /> structure from which to initialize this <see cref="RSize" /> structure.</param> public RSize(RPoint pt) { this.Width = pt.X; this.Height = pt.Y; } /// <summary> /// Initializes a new instance of the <see cref="RSize" /> structure from the specified dimensions. /// </summary> /// <param name="width"> /// The width component of the new <see cref="RSize" /> structure. /// </param> /// <param name="height"> /// The height component of the new <see cref="RSize" /> structure. /// </param> public RSize(double width, double height) { this.Width = width; this.Height = height; } /// <summary> /// Gets a value that indicates whether this <see cref="RSize" /> structure has zero width and height. /// </summary> /// <returns> /// This property returns true when this <see cref="RSize" /> structure has both a width and height of zero; otherwise, false. /// </returns> /// <filterpriority>1</filterpriority> public bool IsEmpty { get { if (Math.Abs(this.Width) < 0.0001) return Math.Abs(this.Height) < 0.0001; else return false; } } /// <summary> /// Gets or sets the horizontal component of this <see cref="RSize" /> structure. /// </summary> /// <returns> /// The horizontal component of this <see cref="RSize" /> structure, typically measured in pixels. /// </returns> /// <filterpriority>1</filterpriority> public double Width { get; set; } /// <summary> /// Gets or sets the vertical component of this <see cref="RSize" /> structure. /// </summary> /// <returns> /// The vertical component of this <see cref="RSize" /> structure, typically measured in pixels. /// </returns> /// <filterpriority>1</filterpriority> public double Height { get; set; } /// <summary> /// Converts the specified <see cref="RSize" /> structure to a /// <see cref="RPoint" /> structure. /// </summary> /// <returns>The <see cref="RPoint" /> structure to which this operator converts.</returns> /// <param name="size">The <see cref="RSize" /> structure to be converted /// </param> public static explicit operator RPoint(RSize size) { return new RPoint(size.Width, size.Height); } /// <summary> /// Adds the width and height of one <see cref="RSize" /> structure to the width and height of another /// <see /// cref="RSize" /> /// structure. /// </summary> /// <returns> /// A <see cref="RSize" /> structure that is the result of the addition operation. /// </returns> /// <param name="sz1"> /// The first <see cref="RSize" /> structure to add. /// </param> /// <param name="sz2"> /// The second <see cref="RSize" /> structure to add. /// </param> /// <filterpriority>3</filterpriority> public static RSize operator +(RSize sz1, RSize sz2) { return Add(sz1, sz2); } /// <summary> /// Subtracts the width and height of one <see cref="RSize" /> structure from the width and height of another /// <see /// cref="RSize" /> /// structure. /// </summary> /// <returns> /// A <see cref="RSize" /> that is the result of the subtraction operation. /// </returns> /// <param name="sz1"> /// The <see cref="RSize" /> structure on the left side of the subtraction operator. /// </param> /// <param name="sz2"> /// The <see cref="RSize" /> structure on the right side of the subtraction operator. /// </param> /// <filterpriority>3</filterpriority> public static RSize operator -(RSize sz1, RSize sz2) { return Subtract(sz1, sz2); } /// <summary> /// Tests whether two <see cref="RSize" /> structures are equal. /// </summary> /// <returns> /// This operator returns true if <paramref name="sz1" /> and <paramref name="sz2" /> have equal width and height; otherwise, false. /// </returns> /// <param name="sz1"> /// The <see cref="RSize" /> structure on the left side of the equality operator. /// </param> /// <param name="sz2"> /// The <see cref="RSize" /> structure on the right of the equality operator. /// </param> /// <filterpriority>3</filterpriority> public static bool operator ==(RSize sz1, RSize sz2) { if (Math.Abs(sz1.Width - sz2.Width) < 0.001) return Math.Abs(sz1.Height - sz2.Height) < 0.001; else return false; } /// <summary> /// Tests whether two <see cref="RSize" /> structures are different. /// </summary> /// <returns> /// This operator returns true if <paramref name="sz1" /> and <paramref name="sz2" /> differ either in width or height; false if /// <paramref /// name="sz1" /> /// and <paramref name="sz2" /> are equal. /// </returns> /// <param name="sz1"> /// The <see cref="RSize" /> structure on the left of the inequality operator. /// </param> /// <param name="sz2"> /// The <see cref="RSize" /> structure on the right of the inequality operator. /// </param> /// <filterpriority>3</filterpriority> public static bool operator !=(RSize sz1, RSize sz2) { return !(sz1 == sz2); } /// <summary> /// Adds the width and height of one <see cref="RSize" /> structure to the width and height of another /// <see /// cref="RSize" /> /// structure. /// </summary> /// <returns> /// A <see cref="RSize" /> structure that is the result of the addition operation. /// </returns> /// <param name="sz1"> /// The first <see cref="RSize" /> structure to add. /// </param> /// <param name="sz2"> /// The second <see cref="RSize" /> structure to add. /// </param> public static RSize Add(RSize sz1, RSize sz2) { return new RSize(sz1.Width + sz2.Width, sz1.Height + sz2.Height); } /// <summary> /// Subtracts the width and height of one <see cref="RSize" /> structure from the width and height of another /// <see /// cref="RSize" /> /// structure. /// </summary> /// <returns> /// A <see cref="RSize" /> structure that is a result of the subtraction operation. /// </returns> /// <param name="sz1"> /// The <see cref="RSize" /> structure on the left side of the subtraction operator. /// </param> /// <param name="sz2"> /// The <see cref="RSize" /> structure on the right side of the subtraction operator. /// </param> public static RSize Subtract(RSize sz1, RSize sz2) { return new RSize(sz1.Width - sz2.Width, sz1.Height - sz2.Height); } /// <summary> /// Tests to see whether the specified object is a <see cref="RSize" /> structure with the same dimensions as this /// <see /// cref="RSize" /> /// structure. /// </summary> /// <returns> /// This method returns true if <paramref name="obj" /> is a <see cref="RSize" /> and has the same width and height as this /// <see /// cref="RSize" /> /// ; otherwise, false. /// </returns> /// <param name="obj"> /// The <see cref="T:System.Object" /> to test. /// </param> /// <filterpriority>1</filterpriority> public override bool Equals(object obj) { if (!(obj is RSize)) return false; var sizeF = (RSize)obj; if (Math.Abs(sizeF.Width - this.Width) < 0.001 && Math.Abs(sizeF.Height - this.Height) < 0.001) return sizeF.GetType() == this.GetType(); else return false; } /// <summary> /// Returns a hash code for this <see cref="RSize" /> structure. /// </summary> /// <returns> /// An integer value that specifies a hash value for this <see cref="RSize" /> structure. /// </returns> /// <filterpriority>1</filterpriority> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Converts a <see cref="RSize" /> structure to a <see cref="RPoint" /> structure. /// </summary> /// <returns> /// Returns a <see cref="RPoint" /> structure. /// </returns> public RPoint ToPointF() { return (RPoint)this; } /// <summary> /// Creates a human-readable string that represents this <see cref="RSize" /> structure. /// </summary> /// <returns> /// A string that represents this <see cref="RSize" /> structure. /// </returns> /// <filterpriority>1</filterpriority> /// <PermissionSet> /// <IPermission /// class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /// version="1" Flags="UnmanagedCode" /> /// </PermissionSet> public override string ToString() { return "{Width=" + this.Width + ", Height=" + this.Height + "}"; } } }
using System; using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif namespace Godot { /// <summary> /// 3-element structure that can be used to represent 3D grid coordinates or sets of integers. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector3i : IEquatable<Vector3i> { /// <summary> /// Enumerated index values for the axes. /// Returned by <see cref="MaxAxis"/> and <see cref="MinAxis"/>. /// </summary> public enum Axis { X = 0, Y, Z } /// <summary> /// The vector's X component. Also accessible by using the index position `[0]`. /// </summary> public int x; /// <summary> /// The vector's Y component. Also accessible by using the index position `[1]`. /// </summary> public int y; /// <summary> /// The vector's Z component. Also accessible by using the index position `[2]`. /// </summary> public int z; /// <summary> /// Access vector components using their index. /// </summary> /// <value>`[0]` is equivalent to `.x`, `[1]` is equivalent to `.y`, `[2]` is equivalent to `.z`.</value> public int this[int index] { get { switch (index) { case 0: return x; case 1: return y; case 2: return z; default: throw new IndexOutOfRangeException(); } } set { switch (index) { case 0: x = value; return; case 1: y = value; return; case 2: z = value; return; default: throw new IndexOutOfRangeException(); } } } /// <summary> /// Returns a new vector with all components in absolute values (i.e. positive). /// </summary> /// <returns>A vector with <see cref="Mathf.Abs(int)"/> called on each component.</returns> public Vector3i Abs() { return new Vector3i(Mathf.Abs(x), Mathf.Abs(y), Mathf.Abs(z)); } /// <summary> /// Returns the squared distance between this vector and `b`. /// This method runs faster than <see cref="DistanceTo"/>, so prefer it if /// you need to compare vectors or need the squared distance for some formula. /// </summary> /// <param name="b">The other vector to use.</param> /// <returns>The squared distance between the two vectors.</returns> public int DistanceSquaredTo(Vector3i b) { return (b - this).LengthSquared(); } /// <summary> /// Returns the distance between this vector and `b`. /// </summary> /// <param name="b">The other vector to use.</param> /// <returns>The distance between the two vectors.</returns> public real_t DistanceTo(Vector3i b) { return (b - this).Length(); } /// <summary> /// Returns the dot product of this vector and `b`. /// </summary> /// <param name="b">The other vector to use.</param> /// <returns>The dot product of the two vectors.</returns> public int Dot(Vector3i b) { return x * b.x + y * b.y + z * b.z; } /// <summary> /// Returns the length (magnitude) of this vector. /// </summary> /// <returns>The length of this vector.</returns> public real_t Length() { int x2 = x * x; int y2 = y * y; int z2 = z * z; return Mathf.Sqrt(x2 + y2 + z2); } /// <summary> /// Returns the squared length (squared magnitude) of this vector. /// This method runs faster than <see cref="Length"/>, so prefer it if /// you need to compare vectors or need the squared length for some formula. /// </summary> /// <returns>The squared length of this vector.</returns> public int LengthSquared() { int x2 = x * x; int y2 = y * y; int z2 = z * z; return x2 + y2 + z2; } /// <summary> /// Returns the axis of the vector's largest value. See <see cref="Axis"/>. /// If all components are equal, this method returns <see cref="Axis.X"/>. /// </summary> /// <returns>The index of the largest axis.</returns> public Axis MaxAxis() { return x < y ? (y < z ? Axis.Z : Axis.Y) : (x < z ? Axis.Z : Axis.X); } /// <summary> /// Returns the axis of the vector's smallest value. See <see cref="Axis"/>. /// If all components are equal, this method returns <see cref="Axis.Z"/>. /// </summary> /// <returns>The index of the smallest axis.</returns> public Axis MinAxis() { return x < y ? (x < z ? Axis.X : Axis.Z) : (y < z ? Axis.Y : Axis.Z); } /// <summary> /// Returns a vector composed of the <see cref="Mathf.PosMod(int, int)"/> of this vector's components and `mod`. /// </summary> /// <param name="mod">A value representing the divisor of the operation.</param> /// <returns>A vector with each component <see cref="Mathf.PosMod(int, int)"/> by `mod`.</returns> public Vector3i PosMod(int mod) { Vector3i v = this; v.x = Mathf.PosMod(v.x, mod); v.y = Mathf.PosMod(v.y, mod); v.z = Mathf.PosMod(v.z, mod); return v; } /// <summary> /// Returns a vector composed of the <see cref="Mathf.PosMod(int, int)"/> of this vector's components and `modv`'s components. /// </summary> /// <param name="modv">A vector representing the divisors of the operation.</param> /// <returns>A vector with each component <see cref="Mathf.PosMod(int, int)"/> by `modv`'s components.</returns> public Vector3i PosMod(Vector3i modv) { Vector3i v = this; v.x = Mathf.PosMod(v.x, modv.x); v.y = Mathf.PosMod(v.y, modv.y); v.z = Mathf.PosMod(v.z, modv.z); return v; } /// <summary> /// Returns a vector with each component set to one or negative one, depending /// on the signs of this vector's components, or zero if the component is zero, /// by calling <see cref="Mathf.Sign(int)"/> on each component. /// </summary> /// <returns>A vector with all components as either `1`, `-1`, or `0`.</returns> public Vector3i Sign() { Vector3i v = this; v.x = Mathf.Sign(v.x); v.y = Mathf.Sign(v.y); v.z = Mathf.Sign(v.z); return v; } // Constants private static readonly Vector3i _zero = new Vector3i(0, 0, 0); private static readonly Vector3i _one = new Vector3i(1, 1, 1); private static readonly Vector3i _up = new Vector3i(0, 1, 0); private static readonly Vector3i _down = new Vector3i(0, -1, 0); private static readonly Vector3i _right = new Vector3i(1, 0, 0); private static readonly Vector3i _left = new Vector3i(-1, 0, 0); private static readonly Vector3i _forward = new Vector3i(0, 0, -1); private static readonly Vector3i _back = new Vector3i(0, 0, 1); /// <summary> /// Zero vector, a vector with all components set to `0`. /// </summary> /// <value>Equivalent to `new Vector3i(0, 0, 0)`</value> public static Vector3i Zero { get { return _zero; } } /// <summary> /// One vector, a vector with all components set to `1`. /// </summary> /// <value>Equivalent to `new Vector3i(1, 1, 1)`</value> public static Vector3i One { get { return _one; } } /// <summary> /// Up unit vector. /// </summary> /// <value>Equivalent to `new Vector3i(0, 1, 0)`</value> public static Vector3i Up { get { return _up; } } /// <summary> /// Down unit vector. /// </summary> /// <value>Equivalent to `new Vector3i(0, -1, 0)`</value> public static Vector3i Down { get { return _down; } } /// <summary> /// Right unit vector. Represents the local direction of right, /// and the global direction of east. /// </summary> /// <value>Equivalent to `new Vector3i(1, 0, 0)`</value> public static Vector3i Right { get { return _right; } } /// <summary> /// Left unit vector. Represents the local direction of left, /// and the global direction of west. /// </summary> /// <value>Equivalent to `new Vector3i(-1, 0, 0)`</value> public static Vector3i Left { get { return _left; } } /// <summary> /// Forward unit vector. Represents the local direction of forward, /// and the global direction of north. /// </summary> /// <value>Equivalent to `new Vector3i(0, 0, -1)`</value> public static Vector3i Forward { get { return _forward; } } /// <summary> /// Back unit vector. Represents the local direction of back, /// and the global direction of south. /// </summary> /// <value>Equivalent to `new Vector3i(0, 0, 1)`</value> public static Vector3i Back { get { return _back; } } /// <summary> /// Constructs a new <see cref="Vector3i"/> with the given components. /// </summary> /// <param name="x">The vector's X component.</param> /// <param name="y">The vector's Y component.</param> /// <param name="z">The vector's Z component.</param> public Vector3i(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } /// <summary> /// Constructs a new <see cref="Vector3i"/> from an existing <see cref="Vector3i"/>. /// </summary> /// <param name="vi">The existing <see cref="Vector3i"/>.</param> public Vector3i(Vector3i vi) { this.x = vi.x; this.y = vi.y; this.z = vi.z; } /// <summary> /// Constructs a new <see cref="Vector3i"/> from an existing <see cref="Vector3"/> /// by rounding the components via <see cref="Mathf.RoundToInt(real_t)"/>. /// </summary> /// <param name="v">The <see cref="Vector3"/> to convert.</param> public Vector3i(Vector3 v) { this.x = Mathf.RoundToInt(v.x); this.y = Mathf.RoundToInt(v.y); this.z = Mathf.RoundToInt(v.z); } public static Vector3i operator +(Vector3i left, Vector3i right) { left.x += right.x; left.y += right.y; left.z += right.z; return left; } public static Vector3i operator -(Vector3i left, Vector3i right) { left.x -= right.x; left.y -= right.y; left.z -= right.z; return left; } public static Vector3i operator -(Vector3i vec) { vec.x = -vec.x; vec.y = -vec.y; vec.z = -vec.z; return vec; } public static Vector3i operator *(Vector3i vec, int scale) { vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } public static Vector3i operator *(int scale, Vector3i vec) { vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } public static Vector3i operator *(Vector3i left, Vector3i right) { left.x *= right.x; left.y *= right.y; left.z *= right.z; return left; } public static Vector3i operator /(Vector3i vec, int divisor) { vec.x /= divisor; vec.y /= divisor; vec.z /= divisor; return vec; } public static Vector3i operator /(Vector3i vec, Vector3i divisorv) { vec.x /= divisorv.x; vec.y /= divisorv.y; vec.z /= divisorv.z; return vec; } public static Vector3i operator %(Vector3i vec, int divisor) { vec.x %= divisor; vec.y %= divisor; vec.z %= divisor; return vec; } public static Vector3i operator %(Vector3i vec, Vector3i divisorv) { vec.x %= divisorv.x; vec.y %= divisorv.y; vec.z %= divisorv.z; return vec; } public static Vector3i operator &(Vector3i vec, int and) { vec.x &= and; vec.y &= and; vec.z &= and; return vec; } public static Vector3i operator &(Vector3i vec, Vector3i andv) { vec.x &= andv.x; vec.y &= andv.y; vec.z &= andv.z; return vec; } public static bool operator ==(Vector3i left, Vector3i right) { return left.Equals(right); } public static bool operator !=(Vector3i left, Vector3i right) { return !left.Equals(right); } public static bool operator <(Vector3i left, Vector3i right) { if (left.x == right.x) { if (left.y == right.y) return left.z < right.z; else return left.y < right.y; } return left.x < right.x; } public static bool operator >(Vector3i left, Vector3i right) { if (left.x == right.x) { if (left.y == right.y) return left.z > right.z; else return left.y > right.y; } return left.x > right.x; } public static bool operator <=(Vector3i left, Vector3i right) { if (left.x == right.x) { if (left.y == right.y) return left.z <= right.z; else return left.y < right.y; } return left.x < right.x; } public static bool operator >=(Vector3i left, Vector3i right) { if (left.x == right.x) { if (left.y == right.y) return left.z >= right.z; else return left.y > right.y; } return left.x > right.x; } public static implicit operator Vector3(Vector3i value) { return new Vector3(value.x, value.y, value.z); } public static explicit operator Vector3i(Vector3 value) { return new Vector3i(value); } public override bool Equals(object obj) { if (obj is Vector3i) { return Equals((Vector3i)obj); } return false; } public bool Equals(Vector3i other) { return x == other.x && y == other.y && z == other.z; } public override int GetHashCode() { return y.GetHashCode() ^ x.GetHashCode() ^ z.GetHashCode(); } public override string ToString() { return String.Format("({0}, {1}, {2})", new object[] { this.x.ToString(), this.y.ToString(), this.z.ToString() }); } public string ToString(string format) { return String.Format("({0}, {1}, {2})", new object[] { this.x.ToString(format), this.y.ToString(format), this.z.ToString(format) }); } } }
// -------------------------------------------------------------------------------------------------------------------- /// <copyright file="HelpAttribute.cs"> /// <See cref="https://github.com/johnearnshaw/unity-inspector-help"></See> /// Copyright (c) 2017, John Earnshaw, reblGreen Software Limited /// <See cref="https://github.com/johnearnshaw/"></See> /// <See cref="https://bitbucket.com/juanshaf/"></See> /// <See cref="https://reblgreen.com/"></See> /// All rights reserved. /// Redistribution and use in source and binary forms, with or without modification, are /// permitted provided that the following conditions are met: /// 1. Redistributions of source code must retain the above copyright notice, this list of /// conditions and the following disclaimer. /// 2. 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. /// </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif [AttributeUsage(AttributeTargets.Field, Inherited = true)] public class HelpAttribute : PropertyAttribute { public readonly string text; // MessageType exists in UnityEditor namespace and can throw an exception when used outside the editor. // We spoof MessageType at the bottom of this script to ensure that errors are not thrown when // MessageType is unavailable. public readonly MessageType type; /// <summary> /// Adds a HelpBox to the Unity property inspector above this field. /// </summary> /// <param name="text">The help text to be displayed in the HelpBox.</param> /// <param name="type">The icon to be displayed in the HelpBox.</param> public HelpAttribute(string text, MessageType type = MessageType.Info) { this.text = text; this.type = type; } } #if UNITY_EDITOR [CustomPropertyDrawer(typeof(HelpAttribute))] public class HelpDrawer : PropertyDrawer { // Used for top and bottom padding between the text and the HelpBox border. const int paddingHeight = 8; // Used to add some margin between the the HelpBox and the property. const int marginHeight = 2; // Global field to store the original (base) property height. float baseHeight = 0; // Custom added height for drawing text area which has the MultilineAttribute. float addedHeight = 0; /// <summary> /// A wrapper which returns the PropertyDrawer.attribute field as a HelpAttribute. /// </summary> HelpAttribute helpAttribute { get { return (HelpAttribute)attribute; } } /// <summary> /// A helper property to check for RangeAttribute. /// </summary> RangeAttribute rangeAttribute { get { var attributes = fieldInfo.GetCustomAttributes(typeof(RangeAttribute), true); return attributes != null && attributes.Length > 0 ? (RangeAttribute)attributes[0] : null; } } /// <summary> /// A helper property to check for MultiLineAttribute. /// </summary> MultilineAttribute multilineAttribute { get { var attributes = fieldInfo.GetCustomAttributes(typeof(MultilineAttribute), true); return attributes != null && attributes.Length > 0 ? (MultilineAttribute)attributes[0] : null; } } public override float GetPropertyHeight(SerializedProperty prop, GUIContent label) { // We store the original property height for later use... baseHeight = base.GetPropertyHeight(prop, label); // This stops icon shrinking if text content doesn't fill out the container enough. float minHeight = paddingHeight * 5; // Calculate the height of the HelpBox using the GUIStyle on the current skin and the inspector // window's currentViewWidth. var content = new GUIContent(helpAttribute.text); var style = GUI.skin.GetStyle("helpbox"); var height = style.CalcHeight(content, EditorGUIUtility.currentViewWidth); // We add tiny padding here to make sure the text is not overflowing the HelpBox from the top // and bottom. height += marginHeight * 2; // Since we draw a custom text area with the label above if our property contains the // MultilineAttribute, we need to add some extra height to compensate. This is stored in a // seperate global field so we can use it again later. if (multilineAttribute != null && prop.propertyType == SerializedPropertyType.String) { addedHeight = 48f; } // If the calculated HelpBox is less than our minimum height we use this to calculate the returned // height instead. return height > minHeight ? height + baseHeight + addedHeight : minHeight + baseHeight + addedHeight; } public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label) { // We get a local reference to the MultilineAttribute as we use it twice in this method and it // saves calling the logic twice for minimal optimization, etc... var multiline = multilineAttribute; EditorGUI.BeginProperty(position, label, prop); // Copy the position out so we can calculate the position of our HelpBox without affecting the // original position. var helpPos = position; helpPos.height -= baseHeight + marginHeight; if (multiline != null) { helpPos.height -= addedHeight; } // Renders the HelpBox in the Unity inspector UI. EditorGUI.HelpBox(helpPos, helpAttribute.text, helpAttribute.type); position.y += helpPos.height + marginHeight; position.height = baseHeight; // If we have a RangeAttribute on our field, we need to handle the PropertyDrawer differently to // keep the same style as Unity's default. var range = rangeAttribute; if (range != null) { if (prop.propertyType == SerializedPropertyType.Float) { EditorGUI.Slider(position, prop, range.min, range.max, label); } else if (prop.propertyType == SerializedPropertyType.Integer) { EditorGUI.IntSlider(position, prop, (int)range.min, (int)range.max, label); } else { // Not numeric so draw standard property field as punishment for adding RangeAttribute to // a property which can not have a range :P EditorGUI.PropertyField(position, prop, label); } } else if (multiline != null) { // Here's where we handle the PropertyDrawer differently if we have a MultiLineAttribute, to try // and keep some kind of multiline text area. This is not identical to Unity's default but is // better than nothing... if (prop.propertyType == SerializedPropertyType.String) { var style = GUI.skin.label; var size = style.CalcHeight(label, EditorGUIUtility.currentViewWidth); EditorGUI.LabelField(position, label); position.y += size; position.height += addedHeight - size; // Fixed text dissappearing thanks to: http://answers.unity3d.com/questions/244043/textarea-does-not-work-text-dissapears-solution-is.html prop.stringValue = EditorGUI.TextArea(position, prop.stringValue); } else { // Again with a MultilineAttribute on a non-text field deserves for the standard property field // to be drawn as punishment :P EditorGUI.PropertyField(position, prop, label); } } else { // If we get to here it means we're drawing the default property field below the HelpBox. More custom // and built in PropertyDrawers could be implemented to enable HelpBox but it could easily make for // hefty else/if block which would need refactoring! EditorGUI.PropertyField(position, prop, label); } EditorGUI.EndProperty(); } } #else // Replicate MessageType Enum if we are not in editor as this enum exists in UnityEditor namespace. // This should stop errors being logged the same as Shawn Featherly's commit in the Github repo but I // feel is cleaner than having the conditional directive in the middle of the HelpAttribute constructor. public enum MessageType { None, Info, Warning, Error, } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Collections.ObjectModel.Tests { public class KeyedCollectionTest { [Fact] public void StringComparer() { var collection = new TestKeyedCollectionOfIKeyedItem<string, int>( System.StringComparer.OrdinalIgnoreCase) { new KeyedItem<string, int>("foo", 0), new KeyedItem<string, int>("bar", 1) }; Assert.Throws<ArgumentException>( () => collection.Add(new KeyedItem<string, int>("Foo", 0))); Assert.Throws<ArgumentException>( () => collection.Add(new KeyedItem<string, int>("fOo", 0))); Assert.Throws<ArgumentException>( () => collection.Add(new KeyedItem<string, int>("baR", 0))); } [Fact] public void ThresholdThrows() { Assert.Throws<ArgumentOutOfRangeException>( () => new TestKeyedCollectionOfIKeyedItem<string, int>(-2)); Assert.Throws<ArgumentOutOfRangeException>( () => new TestKeyedCollectionOfIKeyedItem<string, int>( int.MinValue)); } } public class IListTestKeyedCollectionIntInt : IListTestKeyedCollection<int, int> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return "foo"; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override int CreateItem() { return s_item++; } protected override int GetKeyForItem(int item) { return item; } } public class IListTestKeyedCollectionStringString : IListTestKeyedCollection<string, string> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return 5; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override string CreateItem() { return (s_item++).ToString(); } protected override string GetKeyForItem(string item) { return item; } } public class IListTestKeyedCollectionIntString : IListTestKeyedCollection<int, string> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return 5; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override string CreateItem() { return (s_item++).ToString(); } protected override int GetKeyForItem(string item) { return item == null ? 0 : int.Parse(item); } } public class IListTestKeyedCollectionStringInt : IListTestKeyedCollection<string, int> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return "bar"; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override int CreateItem() { return s_item++; } protected override string GetKeyForItem(int item) { return item.ToString(); } } public class IListTestKeyedCollectionIntIntBadKey : IListTestKeyedCollectionBadKey<int, int> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return "foo"; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override int CreateItem() { return s_item++; } protected override int GetKeyForItem(int item) { return item; } } public class IListTestKeyedCollectionStringStringBadKey : IListTestKeyedCollectionBadKey<string, string> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return 5; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override string CreateItem() { return (s_item++).ToString(); } protected override string GetKeyForItem(string item) { return item; } } public class IListTestKeyedCollectionIntStringBadKey : IListTestKeyedCollectionBadKey<int, string> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return 5; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override string CreateItem() { return (s_item++).ToString(); } protected override int GetKeyForItem(string item) { return item == null ? 0 : int.Parse(item); } } public class IListTestKeyedCollectionStringIntBadKey : IListTestKeyedCollectionBadKey<string, int> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return "bar"; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override int CreateItem() { return s_item++; } protected override string GetKeyForItem(int item) { return item.ToString(); } } public class KeyedCollectionTestsIntInt : KeyedCollectionTests<int, int> { private int _curValue = 1; public override int GetKeyForItem(int item) { return item; } public override int GenerateValue() { return _curValue++; } } public class KeyedCollectionTestsStringString : KeyedCollectionTests<string, string> { private int _curValue = 1; public override string GetKeyForItem(string item) { return item; } public override string GenerateValue() { return (_curValue++).ToString(); } } public class KeyedCollectionTestsIntString : KeyedCollectionTests<int, string> { private int _curValue = 1; public override int GetKeyForItem(string item) { return int.Parse(item); } public override string GenerateValue() { return (_curValue++).ToString(); } } public class KeyedCollectionTestsStringInt : KeyedCollectionTests<string, int> { private int _curValue = 1; public override string GetKeyForItem(int item) { return item.ToString(); } public override int GenerateValue() { return _curValue++; } } }
using System; using DarkMultiPlayerCommon; using UnityEngine; namespace DarkMultiPlayer { public class ConnectionWindow { public bool display = false; public bool connectEventHandled = true; public bool disconnectEventHandled = true; public bool addEventHandled = true; public bool editEventHandled = true; public bool removeEventHandled = true; public bool renameEventHandled = true; public bool addingServer = false; public bool addingServerSafe = false; public int selected = -1; private int selectedSafe = -1; private string status = ""; public ServerEntry addEntry = null; public ServerEntry editEntry = null; //private parts private static ConnectionWindow singleton = new ConnectionWindow(); private bool initialized; //Add window private string serverName = "Local"; private string serverAddress = "127.0.0.1"; private string serverPort = "6702"; //GUI Layout private Rect windowRect; private Rect moveRect; private GUILayoutOption[] labelOptions; private GUILayoutOption[] layoutOptions; private GUIStyle windowStyle; private GUIStyle buttonStyle; private GUIStyle textAreaStyle; private GUIStyle statusStyle; private Vector2 scrollPos; //const private const float WINDOW_HEIGHT = 400; private const float WINDOW_WIDTH = 400; //version private string version() { if (Common.PROGRAM_VERSION.Length == 40) { return "build " + Common.PROGRAM_VERSION.Substring(0, 7); } return Common.PROGRAM_VERSION; } public ConnectionWindow() { lock (Client.eventLock) { Client.updateEvent.Add(this.Update); Client.drawEvent.Add(this.Draw); } } public static ConnectionWindow fetch { get { return singleton; } } private void Update() { status = Client.fetch.status; selectedSafe = selected; addingServerSafe = addingServer; display = (HighLogic.LoadedScene == GameScenes.MAINMENU); } private void InitGUI() { //Setup GUI stuff windowRect = new Rect(Screen.width * 0.9f - WINDOW_WIDTH, Screen.height / 2f - WINDOW_HEIGHT / 2f, WINDOW_WIDTH, WINDOW_HEIGHT); moveRect = new Rect(0, 0, 10000, 20); windowStyle = new GUIStyle(GUI.skin.window); textAreaStyle = new GUIStyle(GUI.skin.textArea); buttonStyle = new GUIStyle(GUI.skin.button); //buttonStyle.fontSize = 10; statusStyle = new GUIStyle(GUI.skin.label); //statusStyle.fontSize = 10; statusStyle.normal.textColor = Color.yellow; layoutOptions = new GUILayoutOption[4]; layoutOptions[0] = GUILayout.MinWidth(WINDOW_WIDTH); layoutOptions[1] = GUILayout.MaxWidth(WINDOW_WIDTH); layoutOptions[2] = GUILayout.MinHeight(WINDOW_HEIGHT); layoutOptions[3] = GUILayout.MaxHeight(WINDOW_HEIGHT); labelOptions = new GUILayoutOption[1]; labelOptions[0] = GUILayout.Width(100); } private void Draw() { if (!initialized) { initialized = true; InitGUI(); } if (display) { windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6702 + Client.WINDOW_OFFSET, windowRect, DrawContent, "DarkMultiPlayer " + version(), windowStyle, layoutOptions)); } } private void DrawContent(int windowID) { GUILayout.BeginVertical(); GUI.DragWindow(moveRect); GUILayout.Space(20); GUILayout.BeginHorizontal(); GUILayout.Label("Player name:", labelOptions); string oldPlayerName = Settings.fetch.playerName; Settings.fetch.playerName = GUILayout.TextArea(Settings.fetch.playerName, 32, textAreaStyle); // Max 32 characters if (oldPlayerName != Settings.fetch.playerName) { Settings.fetch.playerName = Settings.fetch.playerName.Replace("\n", ""); renameEventHandled = false; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); //Draw add button string addMode = selectedSafe == -1 ? "Add" : "Edit"; string buttonAddMode = addMode; if (addingServer) { buttonAddMode = "Cancel"; } addingServer = GUILayout.Toggle(addingServer, buttonAddMode, buttonStyle); if (addingServer && !addingServerSafe) { if (selected != -1) { //Load the existing server settings serverName = Settings.fetch.servers[selected].name; serverAddress = Settings.fetch.servers[selected].address; serverPort = Settings.fetch.servers[selected].port.ToString(); } } //Draw connect button if (NetworkWorker.fetch.state == DarkMultiPlayerCommon.ClientState.DISCONNECTED) { GUI.enabled = (selectedSafe != -1); if (GUILayout.Button("Connect", buttonStyle)) { connectEventHandled = false; } } else { if (GUILayout.Button("Disconnect", buttonStyle)) { disconnectEventHandled = false; } } //Draw remove button if (GUILayout.Button("Remove", buttonStyle)) { if (removeEventHandled == true) { removeEventHandled = false; } } GUI.enabled = true; OptionsWindow.fetch.display = GUILayout.Toggle(OptionsWindow.fetch.display, "Options", buttonStyle); GUILayout.EndHorizontal(); if (addingServerSafe) { GUILayout.BeginHorizontal(); GUILayout.Label("Name:", labelOptions); serverName = GUILayout.TextArea(serverName, textAreaStyle); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Address:", labelOptions); serverAddress = GUILayout.TextArea(serverAddress, textAreaStyle).Trim(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Port:", labelOptions); serverPort = GUILayout.TextArea(serverPort, textAreaStyle).Trim(); GUILayout.EndHorizontal(); if (GUILayout.Button(addMode + " server", buttonStyle)) { if (addEventHandled == true) { if (selected == -1) { addEntry = new ServerEntry(); addEntry.name = serverName; addEntry.address = serverAddress; addEntry.port = 6702; Int32.TryParse(serverPort, out addEntry.port); addEventHandled = false; } else { editEntry = new ServerEntry(); editEntry.name = serverName; editEntry.address = serverAddress; editEntry.port = 6702; Int32.TryParse(serverPort, out editEntry.port); editEventHandled = false; } } } } GUILayout.Label("Servers:"); if (Settings.fetch.servers.Count == 0) { GUILayout.Label("(None - Add a server first)"); } scrollPos = GUILayout.BeginScrollView(scrollPos, GUILayout.Width(WINDOW_WIDTH - 5), GUILayout.Height(WINDOW_HEIGHT - 100)); for (int serverPos = 0; serverPos < Settings.fetch.servers.Count; serverPos++) { bool thisSelected = GUILayout.Toggle(serverPos == selectedSafe, Settings.fetch.servers[serverPos].name, buttonStyle); if (selected == selectedSafe) { if (thisSelected) { if (selected != serverPos) { selected = serverPos; addingServer = false; } } else if (selected == serverPos) { selected = -1; addingServer = false; } } } GUILayout.EndScrollView(); //Draw status message GUILayout.Label(status, statusStyle); GUILayout.EndVertical(); } } }
// 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 was generated, please do not edit it directly. // // Please see MilCodeGen.html for more information. // using MS.Internal; using MS.Internal.WindowsBase; using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Windows; using System.Windows.Media; // 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 { [Serializable] [TypeConverter(typeof(MatrixConverter))] [ValueSerializer(typeof(MatrixValueSerializer))] // Used by MarkupWriter partial struct Matrix : IFormattable { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Compares two Matrix 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 Matrix instances are exactly equal, false otherwise /// </returns> /// <param name='matrix1'>The first Matrix to compare</param> /// <param name='matrix2'>The second Matrix to compare</param> public static bool operator == (Matrix matrix1, Matrix matrix2) { if (matrix1.IsDistinguishedIdentity || matrix2.IsDistinguishedIdentity) { return matrix1.IsIdentity == matrix2.IsIdentity; } else { return matrix1.M11 == matrix2.M11 && matrix1.M12 == matrix2.M12 && matrix1.M21 == matrix2.M21 && matrix1.M22 == matrix2.M22 && matrix1.OffsetX == matrix2.OffsetX && matrix1.OffsetY == matrix2.OffsetY; } } /// <summary> /// Compares two Matrix 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 Matrix instances are exactly unequal, false otherwise /// </returns> /// <param name='matrix1'>The first Matrix to compare</param> /// <param name='matrix2'>The second Matrix to compare</param> public static bool operator != (Matrix matrix1, Matrix matrix2) { return !(matrix1 == matrix2); } /// <summary> /// Compares two Matrix 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 Matrix instances are exactly equal, false otherwise /// </returns> /// <param name='matrix1'>The first Matrix to compare</param> /// <param name='matrix2'>The second Matrix to compare</param> public static bool Equals (Matrix matrix1, Matrix matrix2) { if (matrix1.IsDistinguishedIdentity || matrix2.IsDistinguishedIdentity) { return matrix1.IsIdentity == matrix2.IsIdentity; } else { return matrix1.M11.Equals(matrix2.M11) && matrix1.M12.Equals(matrix2.M12) && matrix1.M21.Equals(matrix2.M21) && matrix1.M22.Equals(matrix2.M22) && matrix1.OffsetX.Equals(matrix2.OffsetX) && matrix1.OffsetY.Equals(matrix2.OffsetY); } } /// <summary> /// Equals - compares this Matrix 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 Matrix 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 Matrix)) { return false; } Matrix value = (Matrix)o; return Matrix.Equals(this,value); } /// <summary> /// Equals - compares this Matrix 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 Matrix to compare to "this"</param> public bool Equals(Matrix value) { return Matrix.Equals(this, value); } /// <summary> /// Returns the HashCode for this Matrix /// </summary> /// <returns> /// int - the HashCode for this Matrix /// </returns> public override int GetHashCode() { if (IsDistinguishedIdentity) { return c_identityHashCode; } else { // Perform field-by-field XOR of HashCodes return M11.GetHashCode() ^ M12.GetHashCode() ^ M21.GetHashCode() ^ M22.GetHashCode() ^ OffsetX.GetHashCode() ^ OffsetY.GetHashCode(); } } /// <summary> /// Parse - returns an instance converted from the provided string using /// the culture "en-US" /// <param name="source"> string with Matrix data </param> /// </summary> public static Matrix Parse(string source) { //IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS; //TokenizerHelper th = new TokenizerHelper(source, formatProvider); //Matrix value; //String firstToken = th.NextTokenRequired(); //// The token will already have had whitespace trimmed so we can do a //// simple string compare. //if (firstToken == "Identity") //{ // value = Identity; //} //else //{ // value = new Matrix( // Convert.ToDouble(firstToken, formatProvider), // Convert.ToDouble(th.NextTokenRequired(), formatProvider), // Convert.ToDouble(th.NextTokenRequired(), formatProvider), // Convert.ToDouble(th.NextTokenRequired(), formatProvider), // Convert.ToDouble(th.NextTokenRequired(), formatProvider), // Convert.ToDouble(th.NextTokenRequired(), formatProvider)); //} //// There should be no more tokens in this string. //th.LastTokenRequired(); //return value; return Identity; } #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 (IsIdentity) { return "Identity"; } // 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 + "}{0}{4:" + format + "}{0}{5:" + format + "}{0}{6:" + format + "}", separator, _m11, _m12, _m21, _m22, _offsetX, _offsetY); } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #endregion Constructors } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using MixedRealityToolkit.Common.Extensions; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MixedRealityToolkit.Sharing.SyncModel { /// <summary> /// The SyncArray class provides the functionality of an array in the data model. /// The array holds entire objects, not primitives, since each object is indexed by unique name. /// Note that this array is unordered. /// </summary> /// <typeparam name="T">Type of SyncObject in the array.</typeparam> public class SyncArray<T> : SyncObject, IEnumerable<T> where T : SyncObject, new() { /// <summary> /// Called when a new object has been added to the array. /// </summary> public event Action<T> ObjectAdded; /// <summary> /// Called when an existing object has been removed from the array /// </summary> public event Action<T> ObjectRemoved; /// <summary> /// // Maps the unique id to object /// </summary> private readonly Dictionary<string, T> dataArray; /// <summary> /// Type of objects in the array. /// This is cached so that we don't have to call typeof(T) more than once. /// </summary> protected readonly Type arrayType; public SyncArray(string field) : base(field) { dataArray = new Dictionary<string, T>(); arrayType = typeof(T); } public SyncArray() : this(string.Empty) { } /// <summary> /// Creates the object in the array, based on its underlying object element that came from the sync system. /// </summary> /// <param name="objectElement">Object element on which the data model object is based.</param> /// <returns>The created data model object of the appropriate type.</returns> protected virtual T CreateObject(ObjectElement objectElement) { Type objectType = SyncSettings.Instance.GetDataModelType(objectElement.GetObjectType()).AsType(); if (!objectType.IsSubclassOf(arrayType) && objectType != arrayType) { throw new InvalidCastException(string.Format("Object of incorrect type added to SyncArray: Expected {0}, got {1} ", objectType, objectElement.GetObjectType().GetString())); } object createdObject = Activator.CreateInstance(objectType); T spawnedDataModel = (T)createdObject; spawnedDataModel.Element = objectElement; spawnedDataModel.FieldName = objectElement.GetName(); // TODO: this should not query SharingStage, but instead query the underlying session layer spawnedDataModel.Owner = SharingStage.Instance.SessionUsersTracker.GetUserById(objectElement.GetOwnerID()); return spawnedDataModel; } /// <summary> /// Adds a new entry into the array. /// </summary> /// <param name="newSyncObject">New object to add.</param> /// <param name="owner">Owner the object. Set to null if the object has no owner.</param> /// <returns>Object that was added, with its networking elements setup.</returns> public T AddObject(T newSyncObject, User owner = null) { // Create our object element for our target string id = System.Guid.NewGuid().ToString(); string dataModelName = SyncSettings.Instance.GetDataModelName(newSyncObject.GetType()); ObjectElement existingElement = Element.CreateObjectElement(new XString(id), dataModelName, owner); // Create a new object and assign the element newSyncObject.Element = existingElement; newSyncObject.FieldName = id; newSyncObject.Owner = owner; // Register the child with the object AddChild(newSyncObject); // Update internal map dataArray[id] = newSyncObject; // Initialize it so it can be used immediately. newSyncObject.InitializeLocal(Element); // Notify listeners that an object was added. if (ObjectAdded != null) { ObjectAdded(newSyncObject); } return newSyncObject; } /// <summary> /// Removes an entry from the array /// </summary> /// <param name="existingObject">Object to remove.</param> /// <returns>True if removal succeeded, false if not.</returns> public bool RemoveObject(T existingObject) { bool success = false; if (existingObject != null) { string uniqueName = existingObject.Element.GetName(); if (dataArray.Remove(uniqueName)) { RemoveChild(existingObject); if (ObjectRemoved != null) { ObjectRemoved(existingObject); } success = true; } } return success; } // Returns a full list of the objects public T[] GetDataArray() { var childrenList = new List<T>(dataArray.Count); foreach (KeyValuePair<string, T> pair in dataArray) { childrenList.Add(pair.Value); } return childrenList.ToArray(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return dataArray.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return dataArray.Values.GetEnumerator(); } public void Clear() { // TODO: We need a way of resetting in a consistent way across all object types and hierarchies. T[] array = GetDataArray(); for (int i = 0; i < array.Length; i++) { RemoveObject(array[i]); } } protected override void OnElementAdded(Element element) { if (element.GetElementType() == ElementType.ObjectType) { // Add the new object and listen for when the initialization has fully completed since it can take time. T newObject = AddObject(ObjectElement.Cast(element)); newObject.InitializationComplete += OnInitializationComplete; } else { Debug.LogError("Error: Adding unknown element to SyncArray<T>"); } base.OnElementAdded(element); } protected override void OnElementDeleted(Element element) { base.OnElementDeleted(element); string uniqueName = element.GetName(); if (dataArray.ContainsKey(uniqueName)) { T obj = dataArray[uniqueName]; RemoveObject(obj); } } private void OnInitializationComplete(SyncObject obj) { // Notify listeners know that an object was added if (ObjectAdded != null) { ObjectAdded(obj as T); } } /// <summary> /// Adds a new entry into the array. /// </summary> /// <param name="existingElement">Element from which the object should be created.</param> /// <returns></returns> private T AddObject(ObjectElement existingElement) { string id = existingElement.GetName(); // Create a new object and assign the element T newObject = CreateObject(existingElement); // Register the child with the object AddChild(newObject); // Update internal map dataArray[id] = newObject; return newObject; } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using EnvDTE; using Microsoft.VisualStudio.ExtensionsExplorer.UI; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell.Interop; using NuGet.Dialog.PackageManagerUI; using NuGet.Dialog.Providers; using NuGet.VisualStudio; namespace NuGet.Dialog { [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public partial class PackageManagerWindow : DialogWindow { internal static PackageManagerWindow CurrentInstance; private const string DialogUserAgentClient = "NuGet Add Package Dialog"; private readonly Lazy<string> _dialogUserAgent = new Lazy<string>(() => HttpUtility.CreateUserAgentString(DialogUserAgentClient)); private static readonly string[] Providers = new string[] { "Installed", "Online", "Updates" }; private const string SearchInSwitch = "/searchin:"; private const string F1Keyword = "vs.ExtensionManager"; private readonly IHttpClientEvents _httpClientEvents; private bool _hasOpenedOnlineProvider; private ComboBox _prereleaseComboBox; private readonly SmartOutputConsoleProvider _smartOutputConsoleProvider; private readonly IProviderSettings _providerSettings; private readonly IProductUpdateService _productUpdateService; private readonly IOptionsPageActivator _optionsPageActivator; private readonly IUpdateAllUIService _updateAllUIService; private readonly Project _activeProject; private string _searchText; public PackageManagerWindow(Project project, string dialogParameters = null) : this(project, ServiceLocator.GetInstance<DTE>(), ServiceLocator.GetInstance<IVsPackageManagerFactory>(), ServiceLocator.GetInstance<IPackageRepositoryFactory>(), ServiceLocator.GetInstance<IPackageSourceProvider>(), ServiceLocator.GetInstance<IHttpClientEvents>(), ServiceLocator.GetInstance<IProductUpdateService>(), ServiceLocator.GetInstance<IPackageRestoreManager>(), ServiceLocator.GetInstance<ISolutionManager>(), ServiceLocator.GetInstance<IOptionsPageActivator>(), ServiceLocator.GetInstance<IDeleteOnRestartManager>(), ServiceLocator.GetGlobalService<SVsShell, IVsShell4>(), dialogParameters) { } private PackageManagerWindow(Project project, DTE dte, IVsPackageManagerFactory packageManagerFactory, IPackageRepositoryFactory repositoryFactory, IPackageSourceProvider packageSourceProvider, IHttpClientEvents httpClientEvents, IProductUpdateService productUpdateService, IPackageRestoreManager packageRestoreManager, ISolutionManager solutionManager, IOptionsPageActivator optionPageActivator, IDeleteOnRestartManager deleteOnRestartManager, IVsShell4 vsRestarter, string dialogParameters) : base(F1Keyword) { InitializeComponent(); #if !VS10 // set unique search guid for VS11 explorer.SearchCategory = new Guid("{85566D5F-E585-411F-B299-5BF006E9F11E}"); #endif _httpClientEvents = httpClientEvents; if (_httpClientEvents != null) { _httpClientEvents.SendingRequest += OnSendingRequest; } _productUpdateService = productUpdateService; _optionsPageActivator = optionPageActivator; _activeProject = project; // replace the ConsoleOutputProvider with SmartOutputConsoleProvider so that we can clear // the console the first time an entry is written to it var providerServices = new ProviderServices(); _smartOutputConsoleProvider = new SmartOutputConsoleProvider(providerServices.OutputConsoleProvider); providerServices.OutputConsoleProvider = _smartOutputConsoleProvider; _providerSettings = providerServices.ProviderSettings; _updateAllUIService = providerServices.UpdateAllUIService; providerServices.ProgressWindow.UpgradeNuGetRequested += (_, __) => { Close(); productUpdateService.Update(); }; AddUpdateBar(productUpdateService); AddRestoreBar(packageRestoreManager); var restartRequestBar = AddRestartRequestBar(deleteOnRestartManager, vsRestarter); InsertDisclaimerElement(); AdjustSortComboBoxWidth(); PreparePrereleaseComboBox(); InsertUpdateAllButton(providerServices.UpdateAllUIService); SetupProviders( project, dte, packageManagerFactory, repositoryFactory, packageSourceProvider, providerServices, httpClientEvents, solutionManager, packageRestoreManager, restartRequestBar); ProcessDialogParameters(dialogParameters); } /// <summary> /// Project.ManageNuGetPackages supports 1 optional argument and 1 optional switch /searchin. /searchin Switch has to be provided at the end /// If the provider specified in the optional switch is not valid, then the provider entered is ignored /// </summary> /// <param name="dialogParameters"></param> private void ProcessDialogParameters(string dialogParameters) { bool providerSet = false; if (dialogParameters != null) { dialogParameters = dialogParameters.Trim(); int lastIndexOfSearchInSwitch = dialogParameters.LastIndexOf(SearchInSwitch, StringComparison.OrdinalIgnoreCase); if (lastIndexOfSearchInSwitch == -1) { _searchText = dialogParameters; } else { _searchText = dialogParameters.Substring(0, lastIndexOfSearchInSwitch); // At this point, we know that /searchin: exists in the string. // Check if there is content following the switch if (dialogParameters.Length > (lastIndexOfSearchInSwitch + SearchInSwitch.Length)) { // At this point, we know that there is some content following the /searchin: switch // Check if it represents a valid provider. Otherwise, don't set the provider here // Note that at the end of the method the provider from the settings will be used if no valid provider was determined string provider = dialogParameters.Substring(lastIndexOfSearchInSwitch + SearchInSwitch.Length); for (int i = 0; i < Providers.Length; i++) { // Case insensitive comparisons with the strings if (String.Equals(Providers[i], provider, StringComparison.OrdinalIgnoreCase)) { UpdateSelectedProvider(i); providerSet = true; break; } } } } } if (!providerSet) { // retrieve the selected provider from the settings UpdateSelectedProvider(_providerSettings.SelectedProvider); } if (!String.IsNullOrEmpty(_searchText)) { var selectedProvider = explorer.SelectedProvider as PackagesProviderBase; selectedProvider.SuppressLoad = true; } } private void AddUpdateBar(IProductUpdateService productUpdateService) { var updateBar = new ProductUpdateBar(productUpdateService); updateBar.UpdateStarting += ExecutedClose; LayoutRoot.Children.Add(updateBar); updateBar.SizeChanged += OnHeaderBarSizeChanged; } private void AddRestoreBar(IPackageRestoreManager packageRestoreManager) { var restoreBar = new PackageRestoreBar(packageRestoreManager); LayoutRoot.Children.Add(restoreBar); restoreBar.SizeChanged += OnHeaderBarSizeChanged; } private RestartRequestBar AddRestartRequestBar(IDeleteOnRestartManager deleteOnRestartManager, IVsShell4 vsRestarter) { var restartRequestBar = new RestartRequestBar(deleteOnRestartManager, vsRestarter); Grid.SetColumn(restartRequestBar, 1); BottomBar.Children.Insert(1, restartRequestBar); return restartRequestBar; } private void OnHeaderBarSizeChanged(object sender, SizeChangedEventArgs e) { // when the update bar appears, we adjust the window position // so that it doesn't push the main content area down if (e.HeightChanged) { double heightDifference = e.NewSize.Height - e.PreviousSize.Height; if (heightDifference > 0) { Top = Math.Max(0, Top - heightDifference); } } } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope"), SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] private void SetupProviders(Project activeProject, DTE dte, IVsPackageManagerFactory packageManagerFactory, IPackageRepositoryFactory packageRepositoryFactory, IPackageSourceProvider packageSourceProvider, ProviderServices providerServices, IHttpClientEvents httpClientEvents, ISolutionManager solutionManager, IPackageRestoreManager packageRestoreManager, RestartRequestBar restartRequestBar) { // This package manager is not used for installing from a remote source, and therefore does not need a fallback repository for resolving dependencies IVsPackageManager packageManager = packageManagerFactory.CreatePackageManager(ServiceLocator.GetInstance<IPackageRepository>(), useFallbackForDependencies: false); IPackageRepository localRepository; // we need different sets of providers depending on whether the dialog is open for solution or a project OnlineProvider onlineProvider; InstalledProvider installedProvider; UpdatesProvider updatesProvider; if (activeProject == null) { Title = String.Format( CultureInfo.CurrentUICulture, NuGet.Dialog.Resources.Dialog_Title, dte.Solution.GetName() + ".sln"); localRepository = packageManager.LocalRepository; onlineProvider = new SolutionOnlineProvider( localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); installedProvider = new SolutionInstalledProvider( packageManager, localRepository, Resources, providerServices, httpClientEvents, solutionManager, packageRestoreManager); updatesProvider = new SolutionUpdatesProvider( localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); } else { IProjectManager projectManager = packageManager.GetProjectManager(activeProject); localRepository = projectManager.LocalRepository; Title = String.Format( CultureInfo.CurrentUICulture, NuGet.Dialog.Resources.Dialog_Title, activeProject.GetDisplayName()); onlineProvider = new OnlineProvider( activeProject, localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); installedProvider = new InstalledProvider( packageManager, activeProject, localRepository, Resources, providerServices, httpClientEvents, solutionManager, packageRestoreManager); updatesProvider = new UpdatesProvider( activeProject, localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); } explorer.Providers.Add(installedProvider); explorer.Providers.Add(onlineProvider); explorer.Providers.Add(updatesProvider); installedProvider.IncludePrerelease = onlineProvider.IncludePrerelease = updatesProvider.IncludePrerelease = _providerSettings.IncludePrereleasePackages; installedProvider.ExecuteCompletedCallback = onlineProvider.ExecuteCompletedCallback = updatesProvider.ExecuteCompletedCallback = restartRequestBar.CheckForUnsuccessfulUninstall; Loaded += (o, e) => restartRequestBar.CheckForUnsuccessfulUninstall(); } private void UpdateSelectedProvider(int selectedProvider) { // update the selected provider selectedProvider = Math.Min(explorer.Providers.Count - 1, selectedProvider); selectedProvider = Math.Max(selectedProvider, 0); explorer.SelectedProvider = explorer.Providers[selectedProvider]; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care about exception handling here.")] private void CanExecuteCommandOnPackage(object sender, CanExecuteRoutedEventArgs e) { if (OperationCoordinator.IsBusy) { e.CanExecute = false; return; } VSExtensionsExplorerCtl control = e.Source as VSExtensionsExplorerCtl; if (control == null) { e.CanExecute = false; return; } PackageItem selectedItem = control.SelectedExtension as PackageItem; if (selectedItem == null) { e.CanExecute = false; return; } try { e.CanExecute = selectedItem.IsEnabled; } catch (Exception) { e.CanExecute = false; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care about exception handling here.")] private void ExecutedPackageCommand(object sender, ExecutedRoutedEventArgs e) { if (OperationCoordinator.IsBusy) { return; } VSExtensionsExplorerCtl control = e.Source as VSExtensionsExplorerCtl; if (control == null) { return; } PackageItem selectedItem = control.SelectedExtension as PackageItem; if (selectedItem == null) { return; } PackagesProviderBase provider = control.SelectedProvider as PackagesProviderBase; if (provider != null) { try { provider.Execute(selectedItem); } catch (Exception exception) { MessageHelper.ShowErrorMessage(exception, NuGet.Dialog.Resources.Dialog_MessageBoxTitle); provider.CloseProgressWindow(); ExceptionHelper.WriteToActivityLog(exception); } } } private void ExecutedClose(object sender, EventArgs e) { Close(); } private void ExecutedShowOptionsPage(object sender, ExecutedRoutedEventArgs e) { Close(); _optionsPageActivator.ActivatePage( OptionsPage.PackageSources, () => OnActivated(_activeProject)); } /// <summary> /// Called when coming back from the Options dialog /// </summary> private static void OnActivated(Project project) { var window = new PackageManagerWindow(project); try { window.ShowModal(); } catch (TargetInvocationException exception) { MessageHelper.ShowErrorMessage(exception, NuGet.Dialog.Resources.Dialog_MessageBoxTitle); ExceptionHelper.WriteToActivityLog(exception); } } private void ExecuteOpenLicenseLink(object sender, ExecutedRoutedEventArgs e) { Hyperlink hyperlink = e.OriginalSource as Hyperlink; if (hyperlink != null && hyperlink.NavigateUri != null) { UriHelper.OpenExternalLink(hyperlink.NavigateUri); e.Handled = true; } } private void ExecuteSetFocusOnSearchBox(object sender, ExecutedRoutedEventArgs e) { explorer.SetFocusOnSearchBox(); } private void OnCategorySelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { PackagesTreeNodeBase selectedNode = explorer.SelectedExtensionTreeNode as PackagesTreeNodeBase; if (selectedNode != null) { // notify the selected node that it is opened. selectedNode.OnOpened(); } } private void OnDialogWindowClosing(object sender, System.ComponentModel.CancelEventArgs e) { // don't allow the dialog to be closed if an operation is pending if (OperationCoordinator.IsBusy) { e.Cancel = true; } } private void OnDialogWindowClosed(object sender, EventArgs e) { foreach (PackagesProviderBase provider in explorer.Providers) { // give each provider a chance to clean up itself provider.Dispose(); } explorer.Providers.Clear(); // flush output messages to the Output console at once when the dialog is closed. _smartOutputConsoleProvider.Flush(); _updateAllUIService.DisposeElement(); CurrentInstance = null; } /// <summary> /// HACK HACK: Insert the disclaimer element into the correct place inside the Explorer control. /// We don't want to bring in the whole control template of the extension explorer control. /// </summary> private void InsertDisclaimerElement() { Grid grid = LogicalTreeHelper.FindLogicalNode(explorer, "resGrid") as Grid; if (grid != null) { // m_Providers is the name of the expander provider control (the one on the leftmost column) UIElement providerExpander = FindChildElementByNameOrType(grid, "m_Providers", typeof(ProviderExpander)); if (providerExpander != null) { // remove disclaimer text and provider expander from their current parents grid.Children.Remove(providerExpander); LayoutRoot.Children.Remove(DisclaimerText); // create the inner grid which will host disclaimer text and the provider extender Grid innerGrid = new Grid(); innerGrid.RowDefinitions.Add(new RowDefinition()); innerGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0, GridUnitType.Auto) }); innerGrid.Children.Add(providerExpander); Grid.SetRow(DisclaimerText, 1); innerGrid.Children.Add(DisclaimerText); // add the inner grid to the first column of the original grid grid.Children.Add(innerGrid); } } } private void InsertUpdateAllButton(IUpdateAllUIService updateAllUIService) { Grid grid = LogicalTreeHelper.FindLogicalNode(explorer, "resGrid") as Grid; if (grid != null && grid.Children.Count > 0) { ListView listView = grid.FindDescendant<ListView>(); if (listView != null) { Grid firstGrid = (Grid)listView.Parent; firstGrid.Children.Remove(listView); var newGrid = new Grid { Margin = listView.Margin }; newGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }); newGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); var updateAllContainer = updateAllUIService.CreateUIElement(); updateAllContainer.Margin = new Thickness(5, 2, 0, 5); updateAllContainer.UpdateInvoked += OnUpdateButtonClick; newGrid.Children.Add(updateAllContainer); listView.Margin = new Thickness(); Grid.SetRow(listView, 1); newGrid.Children.Add(listView); firstGrid.Children.Insert(0, newGrid); } } } private void AdjustSortComboBoxWidth() { ComboBox sortCombo = FindComboBox("cmd_SortOrder"); if (sortCombo != null) { // The default style fixes the Sort combo control's width to 160, which is bad for localization. // We fix it by setting Min width as 160, and let the control resize to content. sortCombo.ClearValue(FrameworkElement.WidthProperty); sortCombo.MinWidth = 160; } } private void PreparePrereleaseComboBox() { // This ComboBox is actually used to display framework versions in various VS dialogs. // We "repurpose" it here to show Prerelease option instead. ComboBox fxCombo = FindComboBox("cmb_Fx"); if (fxCombo != null) { fxCombo.Items.Clear(); fxCombo.Items.Add(NuGet.Dialog.Resources.Filter_StablePackages); fxCombo.Items.Add(NuGet.Dialog.Resources.Filter_IncludePrerelease); fxCombo.SelectedIndex = _providerSettings.IncludePrereleasePackages ? 1 : 0; fxCombo.SelectionChanged += OnFxComboBoxSelectionChanged; _prereleaseComboBox = fxCombo; } } private void OnFxComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e) { var combo = (ComboBox)sender; if (combo.SelectedIndex == -1) { return; } bool includePrerelease = combo.SelectedIndex == 1; // persist the option to VS settings store _providerSettings.IncludePrereleasePackages = includePrerelease; // set the flags on all providers foreach (PackagesProviderBase provider in explorer.Providers) { provider.IncludePrerelease = includePrerelease; } var selectedTreeNode = explorer.SelectedExtensionTreeNode as PackagesTreeNodeBase; if (selectedTreeNode != null) { selectedTreeNode.Refresh(resetQueryBeforeRefresh: true); } } private ComboBox FindComboBox(string name) { Grid grid = LogicalTreeHelper.FindLogicalNode(explorer, "resGrid") as Grid; if (grid != null) { return FindChildElementByNameOrType(grid, name, typeof(SortCombo)) as ComboBox; } return null; } private static UIElement FindChildElementByNameOrType(Grid parent, string childName, Type childType) { UIElement element = parent.FindName(childName) as UIElement; if (element != null) { return element; } else { foreach (UIElement child in parent.Children) { if (childType.IsInstanceOfType(child)) { return child; } } return null; } } private void OnProviderSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { var selectedProvider = explorer.SelectedProvider as PackagesProviderBase; if (selectedProvider != null) { explorer.NoItemsMessage = selectedProvider.NoItemsMessage; _prereleaseComboBox.Visibility = selectedProvider.ShowPrereleaseComboBox ? Visibility.Visible : Visibility.Collapsed; // save the selected provider to user settings _providerSettings.SelectedProvider = explorer.Providers.IndexOf(selectedProvider); // if this is the first time online provider is opened, call to check for update if (selectedProvider == explorer.Providers[1] && !_hasOpenedOnlineProvider) { _hasOpenedOnlineProvider = true; _productUpdateService.CheckForAvailableUpdateAsync(); } _updateAllUIService.Hide(); } else { _prereleaseComboBox.Visibility = Visibility.Collapsed; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care about exception handling here.")] private void OnUpdateButtonClick(object sender, RoutedEventArgs e) { var provider = explorer.SelectedProvider as PackagesProviderBase; if (provider != null) { try { provider.Execute(item: null); } catch (Exception exception) { MessageHelper.ShowErrorMessage(exception, NuGet.Dialog.Resources.Dialog_MessageBoxTitle); provider.CloseProgressWindow(); ExceptionHelper.WriteToActivityLog(exception); } } } private void OnSendingRequest(object sender, WebRequestEventArgs e) { HttpUtility.SetUserAgent(e.Request, _dialogUserAgent.Value); } private void CanExecuteClose(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = !OperationCoordinator.IsBusy; e.Handled = true; } private void OnDialogWindowLoaded(object sender, RoutedEventArgs e) { // HACK: Keep track of the currently open instance of this class. CurrentInstance = this; } protected override void OnContentRendered(EventArgs e) { base.OnContentRendered(e); #if !VS10 var searchControlParent = explorer.SearchControlParent as DependencyObject; #else var searchControlParent = explorer; #endif var element = (TextBox)searchControlParent.FindDescendant<TextBox>(); if (element != null && !String.IsNullOrEmpty(_searchText)) { var selectedProvider = explorer.SelectedProvider as PackagesProviderBase; selectedProvider.SuppressLoad = false; element.Text = _searchText; } } } }
namespace Microsoft.Protocols.TestSuites.MS_OXWSFOLD { using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// This scenario is designed to verify all operations for all optional elements. /// </summary> [TestClass] public class S08_OptionalElements : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the test class. /// </summary> /// <param name="testContext">Context to initialize.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clean up the test class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test cases /// <summary> /// This test case verifies requirements related to all operations with all optional elements. /// </summary> [TestCategory("MSOXWSFOLD"), TestMethod()] public void MSOXWSFOLD_S08_TC01_AllOperationsWithAllOptionalElements() { #region Configure SOAP header this.ConfigureSOAPHeader(); #endregion #region Create new folders in the inbox folder. // CreateFolder request. CreateFolderType createFolderRequest = this.GetCreateFolderRequest( DistinguishedFolderIdNameType.inbox.ToString(), new string[] { "Custom Folder1", "Custom Folder2", "Custom Folder3", "Custom Folder4" }, new string[] { "IPF.MyCustomFolderClass", "IPF.Appointment", "IPF.Contact", "IPF.Task" }, null); // Set ExtendedProperty defined in BaseFolderType. PathToExtendedFieldType publishInAddressBook = new PathToExtendedFieldType(); // A hexadecimal tag of the extended property. publishInAddressBook.PropertyTag = "0x671E"; publishInAddressBook.PropertyType = MapiPropertyTypeType.Boolean; ExtendedPropertyType pubAddressbook = new ExtendedPropertyType(); pubAddressbook.ExtendedFieldURI = publishInAddressBook; pubAddressbook.Item = "1"; ExtendedPropertyType[] extendedProperties = new ExtendedPropertyType[1]; extendedProperties[0] = pubAddressbook; createFolderRequest.Folders[0].ExtendedProperty = extendedProperties; createFolderRequest.Folders[1].ExtendedProperty = extendedProperties; createFolderRequest.Folders[2].ExtendedProperty = extendedProperties; createFolderRequest.Folders[3].ExtendedProperty = extendedProperties; // Define a permissionSet with all optional elements PermissionSetType permissionSet = new PermissionSetType(); permissionSet.Permissions = new PermissionType[1]; permissionSet.Permissions[0] = new PermissionType(); permissionSet.Permissions[0].ReadItems = new PermissionReadAccessType(); permissionSet.Permissions[0].ReadItems = PermissionReadAccessType.FullDetails; permissionSet.Permissions[0].ReadItemsSpecified = true; permissionSet.Permissions[0].CanCreateItems = true; permissionSet.Permissions[0].CanCreateItemsSpecified = true; permissionSet.Permissions[0].CanCreateSubFolders = true; permissionSet.Permissions[0].CanCreateSubFoldersSpecified = true; permissionSet.Permissions[0].IsFolderVisible = true; permissionSet.Permissions[0].IsFolderVisibleSpecified = true; permissionSet.Permissions[0].IsFolderContact = true; permissionSet.Permissions[0].IsFolderContactSpecified = true; permissionSet.Permissions[0].IsFolderOwner = true; permissionSet.Permissions[0].IsFolderOwnerSpecified = true; permissionSet.Permissions[0].IsFolderContact = true; permissionSet.Permissions[0].IsFolderContactSpecified = true; permissionSet.Permissions[0].EditItems = new PermissionActionType(); permissionSet.Permissions[0].EditItems = PermissionActionType.All; permissionSet.Permissions[0].EditItemsSpecified = true; permissionSet.Permissions[0].DeleteItems = new PermissionActionType(); permissionSet.Permissions[0].DeleteItems = PermissionActionType.All; permissionSet.Permissions[0].DeleteItemsSpecified = true; permissionSet.Permissions[0].PermissionLevel = new PermissionLevelType(); permissionSet.Permissions[0].PermissionLevel = PermissionLevelType.Custom; permissionSet.Permissions[0].UserId = new UserIdType(); permissionSet.Permissions[0].UserId.PrimarySmtpAddress = Common.GetConfigurationPropertyValue("User2Name", this.Site) + "@" + Common.GetConfigurationPropertyValue("Domain", this.Site); // Set PermissionSet for FolderType folder. ((FolderType)createFolderRequest.Folders[0]).PermissionSet = permissionSet; // Set PermissionSet for ContactsType folder. ((ContactsFolderType)createFolderRequest.Folders[2]).PermissionSet = permissionSet; // Set PermissionSet for TasksFolderType folder. ((TasksFolderType)createFolderRequest.Folders[3]).PermissionSet = permissionSet; // Create a new folder. CreateFolderResponseType createFolderResponse = this.FOLDAdapter.CreateFolder(createFolderRequest); // Check the response. Common.CheckOperationSuccess(createFolderResponse, 4, this.Site); // Folder ids. FolderIdType[] folderIds = new FolderIdType[createFolderResponse.ResponseMessages.Items.Length]; for (int index = 0; index < createFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, createFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder should be created successfully!"); // Save folder ids. folderIds[index] = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[index]).Folders[0].FolderId; // Save the new created folder's folder id. this.NewCreatedFolderIds.Add(folderIds[index]); } #endregion #region Create a managedfolder CreateManagedFolderRequestType createManagedFolderRequest = this.GetCreateManagedFolderRequest(Common.GetConfigurationPropertyValue("ManagedFolderName1", this.Site)); // Add an email address into request. EmailAddressType mailBox = new EmailAddressType() { EmailAddress = Common.GetConfigurationPropertyValue("User1Name", this.Site) + "@" + Common.GetConfigurationPropertyValue("Domain", this.Site) }; createManagedFolderRequest.Mailbox = mailBox; // Create the specified managed folder. CreateManagedFolderResponseType createManagedFolderResponse = this.FOLDAdapter.CreateManagedFolder(createManagedFolderRequest); // Check the response. Common.CheckOperationSuccess(createManagedFolderResponse, 1, this.Site); // Save the new created managed folder's folder id. FolderIdType newFolderId = ((FolderInfoResponseMessageType)createManagedFolderResponse.ResponseMessages.Items[0]).Folders[0].FolderId; this.NewCreatedFolderIds.Add(newFolderId); #endregion #region Get the new created folders // GetFolder request. GetFolderType getCreatedFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folderIds); // Get the new created folder. GetFolderResponseType getCreatedFolderResponse = this.FOLDAdapter.GetFolder(getCreatedFolderRequest); // Check the response. Common.CheckOperationSuccess(getCreatedFolderResponse, 4, this.Site); for (int index = 0; index < getCreatedFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, getCreatedFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder information should be returned!"); } #endregion #region Update the new created folders // UpdateFolder request. UpdateFolderType updateFolderRequest = this.GetUpdateFolderRequest( new string[] { "Folder", "CalendarFolder", "ContactsFolder", "TasksFolder" }, new string[] { "SetFolderField", "SetFolderField", "SetFolderField", "SetFolderField" }, folderIds); // Update the folders' properties. UpdateFolderResponseType updateFolderResponse = this.FOLDAdapter.UpdateFolder(updateFolderRequest); // Check the response. Common.CheckOperationSuccess(updateFolderResponse, 4, this.Site); for (int index = 0; index < updateFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, updateFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder should be updated successfully!"); } #endregion #region Copy the updated folders to "drafts" folder // Copy the folders into "drafts" folder CopyFolderType copyFolderRequest = this.GetCopyFolderRequest(DistinguishedFolderIdNameType.drafts.ToString(), folderIds); // Copy the folders. CopyFolderResponseType copyFolderResponse = this.FOLDAdapter.CopyFolder(copyFolderRequest); // Check the response. Common.CheckOperationSuccess(copyFolderResponse, 4, this.Site); // Copied Folders' id. FolderIdType[] copiedFolderIds = new FolderIdType[copyFolderResponse.ResponseMessages.Items.Length]; for (int index = 0; index < copyFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, copyFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder should be updated successfully!"); // Variable to save the folders. copiedFolderIds[index] = ((FolderInfoResponseMessageType)copyFolderResponse.ResponseMessages.Items[index]).Folders[0].FolderId; // Save the copied folders' folder id. this.NewCreatedFolderIds.Add(copiedFolderIds[index]); } #endregion #region Move the updated folders to "deleteditems" folder // MoveFolder request. MoveFolderType moveFolderRequest = new MoveFolderType(); // Set the request's folderId field. moveFolderRequest.FolderIds = folderIds; // Set the request's destFolderId field. DistinguishedFolderIdType toFolderId = new DistinguishedFolderIdType(); toFolderId.Id = DistinguishedFolderIdNameType.deleteditems; moveFolderRequest.ToFolderId = new TargetFolderIdType(); moveFolderRequest.ToFolderId.Item = toFolderId; // Move the specified folders. MoveFolderResponseType moveFolderResponse = this.FOLDAdapter.MoveFolder(moveFolderRequest); // Check the response. Common.CheckOperationSuccess(moveFolderResponse, 4, this.Site); for (int index = 0; index < moveFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, moveFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder should be updated successfully!"); } #endregion #region Delete all folders // All folder ids. FolderIdType[] allFolderIds = new FolderIdType[folderIds.Length + copiedFolderIds.Length]; for (int index = 0; index < allFolderIds.Length / 2; index++) { allFolderIds[index] = folderIds[index]; allFolderIds[index + folderIds.Length] = copiedFolderIds[index]; } // DeleteFolder request. DeleteFolderType deleteFolderRequest = this.GetDeleteFolderRequest(DisposalType.HardDelete, allFolderIds); // Delete the specified folder. DeleteFolderResponseType deleteFolderResponse = this.FOLDAdapter.DeleteFolder(deleteFolderRequest); // Check the response. Common.CheckOperationSuccess(deleteFolderResponse, 8, this.Site); for (int index = 0; index < deleteFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, deleteFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder should be updated successfully!"); } #endregion } /// <summary> /// This test case verifies requirements related to all operations without all optional elements. /// </summary> [TestCategory("MSOXWSFOLD"), TestMethod()] public void MSOXWSFOLD_S08_TC02_AllOperationsWithoutAllOptionalElements() { #region Create new folders in the inbox folder. // CreateFolder request. CreateFolderType createFolderRequest = this.GetCreateFolderRequest( DistinguishedFolderIdNameType.inbox.ToString(), new string[] { "Custom Folder1", "Custom Folder2", "Custom Folder3", "Custom Folder4" }, new string[] { "IPF.MyCustomFolderClass", "IPF.Appointment", "IPF.Contact", "IPF.Task" }, null); // Remove FolderClass for FolderType folder. createFolderRequest.Folders[0].FolderClass = null; // Create a new folder. CreateFolderResponseType createFolderResponse = this.FOLDAdapter.CreateFolder(createFolderRequest); // Check the response. Common.CheckOperationSuccess(createFolderResponse, 4, this.Site); // Folder ids. FolderIdType[] folderIds = new FolderIdType[createFolderResponse.ResponseMessages.Items.Length]; for (int index = 0; index < createFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, createFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder should be created successfully!"); // Save folder ids. folderIds[index] = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[index]).Folders[0].FolderId; // Save the new created folder's folder id. this.NewCreatedFolderIds.Add(folderIds[index]); } #endregion #region Create a managedfolder CreateManagedFolderRequestType createManagedFolderRequest = this.GetCreateManagedFolderRequest(Common.GetConfigurationPropertyValue("ManagedFolderName1", this.Site)); // Create the specified managed folder. CreateManagedFolderResponseType createManagedFolderResponse = this.FOLDAdapter.CreateManagedFolder(createManagedFolderRequest); // Check the response. Common.CheckOperationSuccess(createManagedFolderResponse, 1, this.Site); // Save the new created managed folder's folder id. FolderIdType newManagedFolderId = ((FolderInfoResponseMessageType)createManagedFolderResponse.ResponseMessages.Items[0]).Folders[0].FolderId; this.NewCreatedFolderIds.Add(newManagedFolderId); #endregion #region Get the new created folders // GetFolder request. GetFolderType getCreatedFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folderIds); // Get the new created folder. GetFolderResponseType getCreatedFolderResponse = this.FOLDAdapter.GetFolder(getCreatedFolderRequest); // Check the response. Common.CheckOperationSuccess(getCreatedFolderResponse, 4, this.Site); for (int index = 0; index < getCreatedFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, getCreatedFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder information should be returned!"); } #endregion #region Update the new created folders // UpdateFolder request. UpdateFolderType updateFolderRequest = this.GetUpdateFolderRequest( new string[] { "Folder", "CalendarFolder", "ContactsFolder", "TasksFolder" }, new string[] { "SetFolderField", "SetFolderField", "SetFolderField", "SetFolderField" }, folderIds); // Update the folders' properties. UpdateFolderResponseType updateFolderResponse = this.FOLDAdapter.UpdateFolder(updateFolderRequest); // Check the response. Common.CheckOperationSuccess(updateFolderResponse, 4, this.Site); for (int index = 0; index < updateFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, updateFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder should be updated successfully!"); } #endregion #region Copy the updated folders to "drafts" folder // Copy the folders into "drafts" folder CopyFolderType copyFolderRequest = this.GetCopyFolderRequest(DistinguishedFolderIdNameType.drafts.ToString(), folderIds); // Copy the folders. CopyFolderResponseType copyFolderResponse = this.FOLDAdapter.CopyFolder(copyFolderRequest); // Check the response. Common.CheckOperationSuccess(copyFolderResponse, 4, this.Site); // Copied folders' id. FolderIdType[] copiedFolderIds = new FolderIdType[copyFolderResponse.ResponseMessages.Items.Length]; for (int index = 0; index < copyFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, copyFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder should be updated successfully!"); // Variable to save the folders. copiedFolderIds[index] = ((FolderInfoResponseMessageType)copyFolderResponse.ResponseMessages.Items[index]).Folders[0].FolderId; // Save the copied folders' folder id. this.NewCreatedFolderIds.Add(copiedFolderIds[index]); } #endregion #region Move the updated folders to "deleteditems" folder // MoveFolder request. MoveFolderType moveFolderRequest = new MoveFolderType(); // Set the request's folderId field. moveFolderRequest.FolderIds = folderIds; // Set the request's destFolderId field. DistinguishedFolderIdType toFolderId = new DistinguishedFolderIdType(); toFolderId.Id = DistinguishedFolderIdNameType.deleteditems; moveFolderRequest.ToFolderId = new TargetFolderIdType(); moveFolderRequest.ToFolderId.Item = toFolderId; // Move the specified folders. MoveFolderResponseType moveFolderResponse = this.FOLDAdapter.MoveFolder(moveFolderRequest); // Check the response. Common.CheckOperationSuccess(moveFolderResponse, 4, this.Site); for (int index = 0; index < moveFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, moveFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder should be updated successfully!"); } #endregion #region Delete all folders // All folder ids. FolderIdType[] allFolderIds = new FolderIdType[folderIds.Length + copiedFolderIds.Length]; for (int index = 0; index < allFolderIds.Length / 2; index++) { allFolderIds[index] = folderIds[index]; allFolderIds[index + folderIds.Length] = copiedFolderIds[index]; } // DeleteFolder request. DeleteFolderType deleteFolderRequest = this.GetDeleteFolderRequest(DisposalType.HardDelete, allFolderIds); // Delete the specified folder. DeleteFolderResponseType deleteFolderResponse = this.FOLDAdapter.DeleteFolder(deleteFolderRequest); // Check the response. Common.CheckOperationSuccess(deleteFolderResponse, 8, this.Site); for (int index = 0; index < deleteFolderResponse.ResponseMessages.Items.Length; index++) { Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, deleteFolderResponse.ResponseMessages.Items[index].ResponseClass, "Folder should be updated successfully!"); } #endregion } #endregion } }
// <copyright file="LfsController.cs" company="Glenn Watson"> // Copyright (c) 2018 Glenn Watson. All rights reserved. // See LICENSE file in the project root for full license information. // </copyright> namespace GitLfs.Server.Caching.Controllers { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading.Tasks; using GitLfs.Client; using GitLfs.Core; using GitLfs.Core.BatchRequest; using GitLfs.Core.BatchResponse; using GitLfs.Core.ErrorHandling; using GitLfs.Core.File; using GitLfs.Server.Caching.Data; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; /// <summary> /// Controller for handling LFS data. /// </summary> [Produces("application/vnd.git-lfs+json")] public class LfsController : Controller { private const int DefaultErrorCode = 404; private readonly ApplicationDbContext context; private readonly IFileManager fileManager; private readonly ILfsClient lfsClient; private readonly IBatchTransferSerialiser transferSerialiser; private readonly ILogger logger; /// <summary> /// Initializes a new instance of the <see cref="LfsController"/> class. /// </summary> /// <param name="context">The main database context.</param> /// <param name="fileManager">A instance to the file manager.</param> /// <param name="lfsClient">The main LFS client.</param> /// <param name="transferSerialiser">A serialiser that will serialise the batch transfer requests.</param> /// <param name="logger">The main logger for this part of the application.</param> public LfsController( ApplicationDbContext context, IFileManager fileManager, ILfsClient lfsClient, IBatchTransferSerialiser transferSerialiser, ILogger<LfsController> logger) { this.context = context; this.fileManager = fileManager; this.lfsClient = lfsClient; this.transferSerialiser = transferSerialiser; this.logger = logger; } /// <summary> /// Downloads a file from the LFS store. /// </summary> /// <param name="hostId">The internal identification of the host.</param> /// <param name="repositoryName">The name of the repository where to download the file from.</param> /// <param name="objectId">The ID of the object to download.</param> /// <param name="size">The size of the object to download.</param> /// <returns>The result of the action.</returns> [HttpGet("/api/{hostId}/{repositoryName}/info/lfs/{objectId}/{size}")] public async Task<IActionResult> DownloadFile(int hostId, string repositoryName, string objectId, long size) { var fileObjectId = new ObjectId(objectId, size); try { GitHost host = await this.context.GitHost.FindAsync(hostId).ConfigureAwait(false); if (host == null) { return this.NotFound(new ErrorResponse { Message = "Not a valid host id." }); } Stream stream = this.fileManager.GetFileStream(repositoryName, fileObjectId, FileLocation.Permanent); if (stream != null) { this.logger.LogInformation($"Found local cache file: {fileObjectId}"); return this.File(stream, "application/octet-stream"); } var actionStream = await this.fileManager.GetFileContentsAsync(repositoryName, fileObjectId, FileLocation.Metadata, "download").ConfigureAwait(false); if (actionStream == null) { this.logger.LogWarning($"No valid batch request for {fileObjectId}"); return this.NotFound(new ErrorResponse { Message = $"No valid batch request for {fileObjectId}" }); } BatchObjectAction action = this.transferSerialiser.ObjectActionFromString(actionStream); if (action == null) { this.logger.LogWarning($"Unable to find file {objectId}"); return this.NotFound(new ErrorResponse { Message = $"Unable to find file {objectId}" }); } if (action.Mode != BatchActionMode.Download) { this.logger.LogWarning($"No download action associated with request: {objectId}"); return this.StatusCode( 422, new ErrorResponse { Message = $"No download action associated with request: {objectId}" }); } this.fileManager.DeleteFile(repositoryName, fileObjectId, FileLocation.Metadata, "download"); return this.File( await this.lfsClient.DownloadFileAsync( host, repositoryName, fileObjectId, action).ConfigureAwait(false), "application/octet-stream"); } catch (ErrorResponseException ex) { this.logger.LogWarning(null, ex, $"Received a error response with message {ex.Message} for {fileObjectId}"); return this.StatusCode(ex.StatusCode ?? DefaultErrorCode, ex.ErrorResponse); } catch (StatusCodeException ex) { this.logger.LogWarning(null, ex, $"Received a status code error with message {ex.Message}"); return this.StatusCode(ex.StatusCode ?? DefaultErrorCode, new ErrorResponse { Message = ex.Message }); } } /// <summary> /// Handles a request for batching a transfer. /// </summary> /// <param name="hostId">The internal identification of the host.</param> /// <param name="repositoryName">The name of the repository where to download the file from.</param> /// <param name="request">The batch request being asked for.</param> /// <returns>The result of the action.</returns> [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Needed by LFS standard.")] [HttpPost("/api/{hostId}/{repositoryName}/info/lfs/objects/batch")] public async Task<IActionResult> HandleBatchRequest( int hostId, string repositoryName, [FromBody] BatchRequest request) { GitHost host = await this.context.GitHost.FindAsync(hostId).ConfigureAwait(false); if (host == null) { return this.NotFound(new ErrorResponse { Message = "Not a valid host id." }); } var serverBatchRequest = new BatchRequest { Objects = new List<ObjectId>(), Operation = request.Operation, Transfers = request.Transfers }; foreach (ObjectId objectId in request.Objects) { if (request.Operation == BatchRequestMode.Download && this.fileManager.IsFileStored(repositoryName, objectId, FileLocation.Permanent)) { continue; } serverBatchRequest.Objects.Add(objectId); } try { IDictionary<ObjectId, IBatchObject> batchObjects = new Dictionary<ObjectId, IBatchObject>(); if (serverBatchRequest.Objects.Count > 0) { BatchTransfer serverResults = await this.lfsClient.RequestBatchAsync(host, repositoryName, serverBatchRequest).ConfigureAwait(false); foreach (IBatchObject serverResult in serverResults.Objects) { batchObjects.Add(serverResult.Id, serverResult); if (serverResult is BatchObject batchObject) { foreach (BatchObjectAction action in batchObject.Actions) { await this.fileManager.SaveFileAsync( repositoryName, serverResult.Id, FileLocation.Metadata, this.transferSerialiser.ToString(action), action.Mode.ToString().ToLowerInvariant()).ConfigureAwait(false); } } } } var returnResult = new BatchTransfer(); returnResult.Mode = TransferMode.Basic; returnResult.Objects = new List<IBatchObject>(); foreach (ObjectId pendingObjectId in request.Objects) { batchObjects.TryGetValue(pendingObjectId, out IBatchObject batchObjectBase); var batchObject = batchObjectBase as BatchObject; if (batchObjectBase is BatchObjectError errorResult) { returnResult.Objects.Add(errorResult); } else { switch (request.Operation) { case BatchRequestMode.Upload: returnResult.Objects.Add(batchObject); break; case BatchRequestMode.Download: { var returnBatchObject = new BatchObject { Id = pendingObjectId, Actions = new List<BatchObjectAction>() }; var action = new BatchObjectAction { Mode = BatchActionMode.Download, HRef = $"{this.Request.Scheme}://{this.Request.Host}/api/{hostId}/{repositoryName}/info/lfs/{pendingObjectId.Hash}/{pendingObjectId.Size}" }; returnBatchObject.Actions.Add(action); returnResult.Objects.Add(returnBatchObject); break; } } } } return this.Ok(returnResult); } catch (ErrorResponseException ex) { this.logger.LogWarning(null, ex, $"Received a error response with message {ex.Message}"); return this.StatusCode(ex.StatusCode ?? DefaultErrorCode, ex.ErrorResponse); } catch (StatusCodeException ex) { this.logger.LogWarning(null, ex, $"Received a status code error with message {ex.Message}"); return this.StatusCode(ex.StatusCode ?? DefaultErrorCode, new ErrorResponse { Message = ex.Message }); } } /// <summary> /// Handles a upload request to the LFS store. /// </summary> /// <param name="hostId">The internal identification of the host.</param> /// <param name="repositoryName">The name of the repository where to upload the file to.</param> /// <param name="objectId">The ID of the object to upload.</param> /// <param name="size">The size of the object to upload.</param> /// <returns>The result of the action.</returns> [HttpPut("/api/{hostId}/{repositoryName}/info/lfs/{objectId}/{size}")] public async Task<IActionResult> UploadFile(int hostId, string repositoryName, string objectId, long size) { var fileObjectId = new ObjectId(objectId, size); try { GitHost host = await this.context.GitHost.FindAsync(hostId).ConfigureAwait(false); if (host == null) { this.logger.LogWarning("Not a valid host id"); return this.NotFound(new ErrorResponse { Message = "Not a valid host id" }); } this.logger.LogInformation($"Saving the file to disk for {fileObjectId}"); this.Response.Headers.Remove("transfer-encoding"); if (!this.fileManager.IsFileStored( repositoryName, fileObjectId, FileLocation.Metadata, false, "upload")) { this.fileManager.DeleteFile(repositoryName, fileObjectId, FileLocation.Metadata, "upload"); return this.Ok(); } BatchObjectAction action = this.transferSerialiser.ObjectActionFromString(await this.fileManager.GetFileContentsAsync(repositoryName, fileObjectId, FileLocation.Metadata, "upload").ConfigureAwait(false)); this.logger.LogInformation($"Starting file upload for {fileObjectId}"); await this.lfsClient.UploadFileAsync(action, this.Request.Body).ConfigureAwait(false); this.logger.LogInformation($"Finished file upload for {fileObjectId}"); this.fileManager.DeleteFile(repositoryName, fileObjectId, FileLocation.Metadata, "upload"); return this.Ok(); } catch (ErrorResponseException ex) { this.logger.LogWarning(null, ex, $"Received a error response with message {ex.Message} for {fileObjectId}"); this.fileManager.DeleteFile(repositoryName, fileObjectId, FileLocation.Temporary); return this.StatusCode(ex.StatusCode ?? DefaultErrorCode, ex.ErrorResponse); } catch (StatusCodeException ex) { this.logger.LogWarning(null, ex, $"Received a status code error with message {ex.Message} for {fileObjectId}"); this.fileManager.DeleteFile(repositoryName, fileObjectId, FileLocation.Temporary); return this.StatusCode(ex.StatusCode ?? DefaultErrorCode, new ErrorResponse { Message = ex.Message }); } } /// <summary> /// Handles a verify request to the LFS service. /// </summary> /// <param name="hostId">The internal identification of the host.</param> /// <param name="repositoryName">The name of the repository where to verify the file from.</param> /// <param name="objectId">The ID of the object to verify.</param> /// <param name="size">The size of the object to verify.</param> /// <returns>The result of the action.</returns> [HttpPost("/api/{hostId}/{repositoryName}/info/lfs/verify/{objectId}/{size}")] public async Task<IActionResult> Verify(int hostId, string repositoryName, string objectId, long size) { var fileObjectId = new ObjectId(objectId, size); try { GitHost host = await this.context.GitHost.FindAsync(hostId).ConfigureAwait(false); if (host == null) { return this.NotFound(new ErrorResponse { Message = "Not a valid host id." }); } this.fileManager.MoveFile(repositoryName, fileObjectId, FileLocation.Temporary, FileLocation.Permanent); if (this.fileManager.IsFileStored(repositoryName, fileObjectId, FileLocation.Metadata, false, "verify")) { this.logger.LogInformation($"Starting verify for {fileObjectId}"); BatchObjectAction action = this.transferSerialiser.ObjectActionFromString(await this.fileManager.GetFileContentsAsync(repositoryName, fileObjectId, FileLocation.Metadata, "verify").ConfigureAwait(false)); await this.lfsClient.VerifyAsync(host, repositoryName, fileObjectId, action).ConfigureAwait(false); this.logger.LogInformation($"Ending verify for {fileObjectId}"); } this.fileManager.DeleteFile(repositoryName, fileObjectId, FileLocation.Metadata, "verify"); return this.Ok(); } catch (ErrorResponseException ex) { this.logger.LogWarning(null, ex, $"Received a error response with message {ex.Message} for {fileObjectId}"); return this.StatusCode(ex.StatusCode ?? DefaultErrorCode, ex.ErrorResponse); } catch (StatusCodeException ex) { this.logger.LogWarning(null, ex, $"Received a status code error with message {ex.Message} for {fileObjectId}"); return this.StatusCode(ex.StatusCode ?? DefaultErrorCode, new ErrorResponse { Message = ex.Message }); } } } }
using System; using System.Collections.ObjectModel; using System.Text.RegularExpressions; using NUnit.Framework; using OpenQA.Selenium.Environment; using System.Text; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { [TestFixture] public class CookieImplementationTest : DriverTestFixture { private Random random = new Random(); private bool isOnAlternativeHostName; private string hostname; [SetUp] public void GoToSimplePageAndDeleteCookies() { GotoValidDomainAndClearCookies("animals"); AssertNoCookiesArePresent(); } [Test] public void ShouldGetCookieByName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key = string.Format("key_{0}", new Random().Next()); ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key); Cookie cookie = driver.Manage().Cookies.GetCookieNamed(key); Assert.AreEqual("set", cookie.Value); } [Test] public void ShouldBeAbleToAddCookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key = GenerateUniqueKey(); string value = "foo"; Cookie cookie = new Cookie(key, value); AssertCookieIsNotPresentWithName(key); driver.Manage().Cookies.AddCookie(cookie); AssertCookieHasValue(key, value); Assert.That(driver.Manage().Cookies.AllCookies.Contains(cookie), "Cookie was not added successfully"); } [Test] public void GetAllCookies() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key1 = GenerateUniqueKey(); string key2 = GenerateUniqueKey(); AssertCookieIsNotPresentWithName(key1); AssertCookieIsNotPresentWithName(key2); ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies; int count = cookies.Count; Cookie one = new Cookie(key1, "value"); Cookie two = new Cookie(key2, "value"); driver.Manage().Cookies.AddCookie(one); driver.Manage().Cookies.AddCookie(two); driver.Url = simpleTestPage; cookies = driver.Manage().Cookies.AllCookies; Assert.AreEqual(count + 2, cookies.Count); Assert.That(cookies, Does.Contain(one)); Assert.That(cookies, Does.Contain(two)); } [Test] public void DeleteAllCookies() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = 'foo=set';"); AssertSomeCookiesArePresent(); driver.Manage().Cookies.DeleteAllCookies(); AssertNoCookiesArePresent(); } [Test] public void DeleteCookieWithName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key1 = GenerateUniqueKey(); string key2 = GenerateUniqueKey(); ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key1); ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key2); AssertCookieIsPresentWithName(key1); AssertCookieIsPresentWithName(key2); driver.Manage().Cookies.DeleteCookieNamed(key1); AssertCookieIsNotPresentWithName(key1); AssertCookieIsPresentWithName(key2); } [Test] public void ShouldNotDeleteCookiesWithASimilarName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieOneName = "fish"; Cookie cookie1 = new Cookie(cookieOneName, "cod"); Cookie cookie2 = new Cookie(cookieOneName + "x", "earth"); IOptions options = driver.Manage(); AssertCookieIsNotPresentWithName(cookie1.Name); options.Cookies.AddCookie(cookie1); options.Cookies.AddCookie(cookie2); AssertCookieIsPresentWithName(cookie1.Name); options.Cookies.DeleteCookieNamed(cookieOneName); Assert.That(driver.Manage().Cookies.AllCookies, Does.Not.Contain(cookie1)); Assert.That(driver.Manage().Cookies.AllCookies, Does.Contain(cookie2)); } [Test] public void AddCookiesWithDifferentPathsThatAreRelatedToOurs() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string basePath = EnvironmentManager.Instance.UrlBuilder.Path; Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals"); Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/"); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); options.Cookies.AddCookie(cookie2); UrlBuilder builder = EnvironmentManager.Instance.UrlBuilder; driver.Url = builder.WhereIs("animals"); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; AssertCookieIsPresentWithName(cookie1.Name); AssertCookieIsPresentWithName(cookie2.Name); driver.Url = builder.WhereIs("simpleTest.html"); AssertCookieIsNotPresentWithName(cookie1.Name); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome does not retrieve cookies when in frame.")] [IgnoreBrowser(Browser.Edge, "Edge does not retrieve cookies when in frame.")] public void GetCookiesInAFrame() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals"); Cookie cookie1 = new Cookie("fish", "cod", "/common/animals"); driver.Manage().Cookies.AddCookie(cookie1); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("frameWithAnimals.html"); AssertCookieIsNotPresentWithName(cookie1.Name); driver.SwitchTo().Frame("iframe1"); AssertCookieIsPresentWithName(cookie1.Name); } [Test] [IgnoreBrowser(Browser.Opera)] public void CannotGetCookiesWithPathDifferingOnlyInCase() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieName = "fish"; driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod", "/Common/animals")); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals"); Assert.That(driver.Manage().Cookies.GetCookieNamed(cookieName), Is.Null); } [Test] public void ShouldNotGetCookieOnDifferentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieName = "fish"; driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod")); AssertCookieIsPresentWithName(cookieName); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html"); AssertCookieIsNotPresentWithName(cookieName); } [Test] public void ShouldBeAbleToAddToADomainWhichIsRelatedToTheCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } AssertCookieIsNotPresentWithName("name"); Regex replaceRegex = new Regex(".*?\\."); string shorter = replaceRegex.Replace(this.hostname, ".", 1); Cookie cookie = new Cookie("name", "value", shorter, "/", GetTimeInTheFuture()); driver.Manage().Cookies.AddCookie(cookie); AssertCookieIsPresentWithName("name"); } [Test] public void ShouldNotGetCookiesRelatedToCurrentDomainWithoutLeadingPeriod() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieName = "name"; AssertCookieIsNotPresentWithName(cookieName); Regex replaceRegex = new Regex(".*?\\."); string subdomain = replaceRegex.Replace(this.hostname, "subdomain.", 1); Cookie cookie = new Cookie(cookieName, "value", subdomain, "/", GetTimeInTheFuture()); string originalUrl = driver.Url; string subdomainUrl = originalUrl.Replace(this.hostname, subdomain); driver.Url = subdomainUrl; driver.Manage().Cookies.AddCookie(cookie); driver.Url = originalUrl; AssertCookieIsNotPresentWithName(cookieName); } [Test] public void ShouldBeAbleToIncludeLeadingPeriodInDomainName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } AssertCookieIsNotPresentWithName("name"); // Replace the first part of the name with a period Regex replaceRegex = new Regex(".*?\\."); string shorter = replaceRegex.Replace(this.hostname, ".", 1); Cookie cookie = new Cookie("name", "value", shorter, "/", DateTime.Now.AddSeconds(100000)); driver.Manage().Cookies.AddCookie(cookie); AssertCookieIsPresentWithName("name"); } [Test] public void ShouldBeAbleToSetDomainToTheCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } Uri url = new Uri(driver.Url); String host = url.Host + ":" + url.Port.ToString(); Cookie cookie1 = new Cookie("fish", "cod", host, "/", null); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); driver.Url = javascriptPage; ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Contain(cookie1)); } [Test] public void ShouldWalkThePathToDeleteACookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string basePath = EnvironmentManager.Instance.UrlBuilder.Path; Cookie cookie1 = new Cookie("fish", "cod"); driver.Manage().Cookies.AddCookie(cookie1); int count = driver.Manage().Cookies.AllCookies.Count; driver.Url = childPage; Cookie cookie2 = new Cookie("rodent", "hamster", "/" + basePath + "/child"); driver.Manage().Cookies.AddCookie(cookie2); count = driver.Manage().Cookies.AllCookies.Count; driver.Url = grandchildPage; Cookie cookie3 = new Cookie("dog", "dalmation", "/" + basePath + "/child/grandchild/"); driver.Manage().Cookies.AddCookie(cookie3); count = driver.Manage().Cookies.AllCookies.Count; driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("child/grandchild")); driver.Manage().Cookies.DeleteCookieNamed("rodent"); count = driver.Manage().Cookies.AllCookies.Count; Assert.That(driver.Manage().Cookies.GetCookieNamed("rodent"), Is.Null); ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies; Assert.That(cookies, Has.Count.EqualTo(2)); Assert.That(cookies, Does.Contain(cookie1)); Assert.That(cookies, Does.Contain(cookie3)); driver.Manage().Cookies.DeleteAllCookies(); driver.Url = grandchildPage; AssertNoCookiesArePresent(); } [Test] public void ShouldIgnoreThePortNumberOfTheHostWhenSettingTheCookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } Uri uri = new Uri(driver.Url); string host = string.Format("{0}:{1}", uri.Host, uri.Port); string cookieName = "name"; AssertCookieIsNotPresentWithName(cookieName); Cookie cookie = new Cookie(cookieName, "value", host, "/", null); driver.Manage().Cookies.AddCookie(cookie); AssertCookieIsPresentWithName(cookieName); } [Test] [IgnoreBrowser(Browser.Opera)] public void CookieEqualityAfterSetAndGet() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); DateTime time = DateTime.Now.AddDays(1); Cookie cookie1 = new Cookie("fish", "cod", null, "/common/animals", time); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Cookie retrievedCookie = null; foreach (Cookie tempCookie in cookies) { if (cookie1.Equals(tempCookie)) { retrievedCookie = tempCookie; break; } } Assert.That(retrievedCookie, Is.Not.Null); //Cookie.equals only compares name, domain and path Assert.AreEqual(cookie1, retrievedCookie); } [Test] [IgnoreBrowser(Browser.Opera)] public void ShouldRetainCookieExpiry() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); // DateTime.Now contains milliseconds; the returned cookie expire date // will not. So we need to truncate the milliseconds. DateTime current = DateTime.Now; DateTime expireDate = new DateTime(current.Year, current.Month, current.Day, current.Hour, current.Minute, current.Second, DateTimeKind.Local).AddDays(1); Cookie addCookie = new Cookie("fish", "cod", "/common/animals", expireDate); IOptions options = driver.Manage(); options.Cookies.AddCookie(addCookie); Cookie retrieved = options.Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Not.Null); Assert.AreEqual(addCookie.Expiry, retrieved.Expiry, "Cookies are not equal"); } [Test] [IgnoreBrowser(Browser.IE, "Browser does not handle untrusted SSL certificates.")] [IgnoreBrowser(Browser.EdgeLegacy, "Browser does not handle untrusted SSL certificates.")] public void CanHandleSecureCookie() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("animals"); Cookie addedCookie = new ReturnedCookie("fish", "cod", null, "/common/animals", null, true, false, null); driver.Manage().Cookies.AddCookie(addedCookie); driver.Navigate().Refresh(); Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Not.Null); } [Test] [IgnoreBrowser(Browser.IE, "Browser does not handle untrusted SSL certificates.")] [IgnoreBrowser(Browser.EdgeLegacy, "Browser does not handle untrusted SSL certificates.")] public void ShouldRetainCookieSecure() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("animals"); ReturnedCookie addedCookie = new ReturnedCookie("fish", "cod", string.Empty, "/common/animals", null, true, false, null); driver.Manage().Cookies.AddCookie(addedCookie); driver.Navigate().Refresh(); Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Not.Null); Assert.That(retrieved.Secure, "Secure attribute not set to true"); } [Test] public void CanHandleHttpOnlyCookie() { StringBuilder url = new StringBuilder(EnvironmentManager.Instance.UrlBuilder.WhereIs("cookie")); url.Append("?action=add"); url.Append("&name=").Append("fish"); url.Append("&value=").Append("cod"); url.Append("&path=").Append("/common/animals"); url.Append("&httpOnly=").Append("true"); driver.Url = url.ToString(); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals"); Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Not.Null); } [Test] public void ShouldRetainHttpOnlyFlag() { StringBuilder url = new StringBuilder(EnvironmentManager.Instance.UrlBuilder.WhereElseIs("cookie")); url.Append("?action=add"); url.Append("&name=").Append("fish"); url.Append("&value=").Append("cod"); url.Append("&path=").Append("/common/animals"); url.Append("&httpOnly=").Append("true"); driver.Url = url.ToString(); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Not.Null); Assert.That(retrieved.IsHttpOnly, "HttpOnly attribute not set to true"); } [Test] public void SettingACookieThatExpiredInThePast() { string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); DateTime expires = DateTime.Now.AddSeconds(-1000); Cookie cookie = new Cookie("expired", "yes", "/common/animals", expires); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie); cookie = options.Cookies.GetCookieNamed("expired"); Assert.That(cookie, Is.Null, "Cookie expired before it was set, so nothing should be returned: " + cookie); } [Test] public void CanSetCookieWithoutOptionalFieldsSet() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key = GenerateUniqueKey(); string value = "foo"; Cookie cookie = new Cookie(key, value); AssertCookieIsNotPresentWithName(key); driver.Manage().Cookies.AddCookie(cookie); AssertCookieHasValue(key, value); } [Test] public void DeleteNotExistedCookie() { String key = GenerateUniqueKey(); AssertCookieIsNotPresentWithName(key); driver.Manage().Cookies.DeleteCookieNamed(key); } [Test] public void DeleteAllCookiesDifferentUrls() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } Cookie cookie1 = new Cookie("fish1", "cod", EnvironmentManager.Instance.UrlBuilder.HostName, null, null); Cookie cookie2 = new Cookie("fish2", "tune", EnvironmentManager.Instance.UrlBuilder.AlternateHostName, null, null); string url1 = EnvironmentManager.Instance.UrlBuilder.WhereIs(""); string url2 = EnvironmentManager.Instance.UrlBuilder.WhereElseIs(""); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); AssertCookieIsPresentWithName(cookie1.Name); driver.Url = url2; options.Cookies.AddCookie(cookie2); AssertCookieIsNotPresentWithName(cookie1.Name); AssertCookieIsPresentWithName(cookie2.Name); driver.Url = url1; AssertCookieIsPresentWithName(cookie1.Name); AssertCookieIsNotPresentWithName(cookie2.Name); options.Cookies.DeleteAllCookies(); AssertCookieIsNotPresentWithName(cookie1.Name); driver.Url = url2; AssertCookieIsPresentWithName(cookie2.Name); } //------------------------------------------------------------------ // Tests below here are not included in the Java test suite //------------------------------------------------------------------ [Test] public void CanSetCookiesOnADifferentPathOfTheSameHost() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string basePath = EnvironmentManager.Instance.UrlBuilder.Path; Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals"); Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/galaxy"); IOptions options = driver.Manage(); ReadOnlyCollection<Cookie> count = options.Cookies.AllCookies; options.Cookies.AddCookie(cookie1); options.Cookies.AddCookie(cookie2); string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals"); driver.Url = url; ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Contain(cookie1)); Assert.That(cookies, Does.Not.Contain(cookie2)); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("galaxy"); cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Not.Contain(cookie1)); Assert.That(cookies, Does.Contain(cookie2)); } [Test] public void ShouldNotBeAbleToSetDomainToSomethingThatIsUnrelatedToTheCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } Cookie cookie1 = new Cookie("fish", "cod"); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html"); driver.Url = url; Assert.That(options.Cookies.GetCookieNamed("fish"), Is.Null); } [Test] public void GetCookieDoesNotRetriveBeyondCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } Cookie cookie1 = new Cookie("fish", "cod"); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); String url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs(""); driver.Url = url; ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Not.Contain(cookie1)); } [Test] public void ShouldAddCookieToCurrentDomainAndPath() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Homer", "Simpson", this.hostname, "/" + EnvironmentManager.Instance.UrlBuilder.Path, null); options.Cookies.AddCookie(cookie); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies.Contains(cookie), "Valid cookie was not returned"); } [Test] public void ShouldNotShowCookieAddedToDifferentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { Assert.Ignore("Not on a standard domain for cookies (localhost doesn't count)."); } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Bart", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName + ".com", EnvironmentManager.Instance.UrlBuilder.Path, null); Assert.That(() => options.Cookies.AddCookie(cookie), Throws.InstanceOf<WebDriverException>().Or.InstanceOf<InvalidOperationException>()); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Not.Contain(cookie), "Invalid cookie was returned"); } [Test] public void ShouldNotShowCookieAddedToDifferentPath() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Lisa", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName, "/" + EnvironmentManager.Instance.UrlBuilder.Path + "IDoNotExist", null); options.Cookies.AddCookie(cookie); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Not.Contain(cookie), "Invalid cookie was returned"); } [Test] public void ShouldThrowExceptionWhenAddingCookieToCookieAverseDocument() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // URLs using a non-network scheme (like "about:" or "data:") are // averse to cookies, and should throw an InvalidCookieDomainException. driver.Url = "about:blank"; IOptions options = driver.Manage(); Cookie cookie = new Cookie("question", "dunno"); Assert.That(() => options.Cookies.AddCookie(cookie), Throws.InstanceOf<InvalidCookieDomainException>().Or.InstanceOf<InvalidOperationException>()); } [Test] public void ShouldReturnNullBecauseCookieRetainsExpiry() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); Cookie addCookie = new Cookie("fish", "cod", "/common/animals", DateTime.Now.AddHours(-1)); IOptions options = driver.Manage(); options.Cookies.AddCookie(addCookie); Cookie retrieved = options.Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Null); } [Test] public void ShouldAddCookieToCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Marge", "Simpson", "/"); options.Cookies.AddCookie(cookie); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies.Contains(cookie), "Valid cookie was not returned"); } [Test] public void ShouldDeleteCookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookieToDelete = new Cookie("answer", "42"); Cookie cookieToKeep = new Cookie("canIHaz", "Cheeseburguer"); options.Cookies.AddCookie(cookieToDelete); options.Cookies.AddCookie(cookieToKeep); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; options.Cookies.DeleteCookie(cookieToDelete); ReadOnlyCollection<Cookie> cookies2 = options.Cookies.AllCookies; Assert.That(cookies2, Does.Not.Contain(cookieToDelete), "Cookie was not deleted successfully"); Assert.That(cookies2.Contains(cookieToKeep), "Valid cookie was not returned"); } ////////////////////////////////////////////// // Support functions ////////////////////////////////////////////// private void GotoValidDomainAndClearCookies(string page) { this.hostname = null; String hostname = EnvironmentManager.Instance.UrlBuilder.HostName; if (IsValidHostNameForCookieTests(hostname)) { this.isOnAlternativeHostName = false; this.hostname = hostname; } hostname = EnvironmentManager.Instance.UrlBuilder.AlternateHostName; if (this.hostname == null && IsValidHostNameForCookieTests(hostname)) { this.isOnAlternativeHostName = true; this.hostname = hostname; } GoToPage(page); driver.Manage().Cookies.DeleteAllCookies(); if (driver.Manage().Cookies.AllCookies.Count != 0) { // If cookies are still present, restart the driver and try again. // This may mask some errors, where DeleteAllCookies doesn't fully // delete all it should, but that's a tradeoff we need to be willing // to make. driver = EnvironmentManager.Instance.CreateFreshDriver(); GoToPage(page); } } private bool CheckIsOnValidHostNameForCookieTests() { bool correct = this.hostname != null && IsValidHostNameForCookieTests(this.hostname); if (!correct) { System.Console.WriteLine("Skipping test: unable to find domain name to use"); } return correct; } private void GoToPage(String pageName) { driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName); } private void GoToOtherPage(String pageName) { driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName); } private bool IsValidHostNameForCookieTests(string hostname) { // TODO(JimEvan): Some coverage is better than none, so we // need to ignore the fact that localhost cookies are problematic. // Reenable this when we have a better solution per DanielWagnerHall. // ChromeDriver2 has trouble with localhost. IE and Firefox don't. // return !IsIpv4Address(hostname) && "localhost" != hostname; bool isLocalHostOkay = true; if ("localhost" == hostname && TestUtilities.IsChrome(driver)) { isLocalHostOkay = false; } return !IsIpv4Address(hostname) && isLocalHostOkay; } private static bool IsIpv4Address(string addrString) { return Regex.IsMatch(addrString, "\\d{1,3}(?:\\.\\d{1,3}){3}"); } private string GenerateUniqueKey() { return string.Format("key_{0}", random.Next()); } private string GetDocumentCookieOrNull() { IJavaScriptExecutor jsDriver = driver as IJavaScriptExecutor; if (jsDriver == null) { return null; } try { return (string)jsDriver.ExecuteScript("return document.cookie"); } catch (InvalidOperationException) { return null; } } private void AssertNoCookiesArePresent() { Assert.That(driver.Manage().Cookies.AllCookies.Count, Is.EqualTo(0), "Cookies were not empty"); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.AreEqual(string.Empty, documentCookie, "Cookies were not empty"); } } private void AssertSomeCookiesArePresent() { Assert.That(driver.Manage().Cookies.AllCookies.Count, Is.Not.EqualTo(0), "Cookies were empty"); String documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.AreNotEqual(string.Empty, documentCookie, "Cookies were empty"); } } private void AssertCookieIsNotPresentWithName(string key) { Assert.That(driver.Manage().Cookies.GetCookieNamed(key), Is.Null, "Cookie was present with name " + key); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.That(documentCookie, Does.Not.Contain(key + "=")); } } private void AssertCookieIsPresentWithName(string key) { Assert.That(driver.Manage().Cookies.GetCookieNamed(key), Is.Not.Null, "Cookie was present with name " + key); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.That(documentCookie, Does.Contain(key + "=")); } } private void AssertCookieHasValue(string key, string value) { Assert.AreEqual(value, driver.Manage().Cookies.GetCookieNamed(key).Value, "Cookie had wrong value"); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.That(documentCookie, Does.Contain(key + "=" + value)); } } private DateTime GetTimeInTheFuture() { return DateTime.Now.Add(TimeSpan.FromMilliseconds(100000)); } } }
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Text; using System.Xml; using ICSharpCode.SharpZipLib.Zip; using MarkdownSharp; using NuGet; using Splat; using ICSharpCode.SharpZipLib.Core; namespace Squirrel { internal static class FrameworkTargetVersion { public static FrameworkName Net40 = new FrameworkName(".NETFramework,Version=v4.0"); public static FrameworkName Net45 = new FrameworkName(".NETFramework,Version=v4.5"); } public interface IReleasePackage { string InputPackageFile { get; } string ReleasePackageFile { get; } string SuggestedReleaseFileName { get; } string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null, Action<string> contentsPostProcessHook = null); } public static class VersionComparer { public static bool Matches(IVersionSpec versionSpec, SemanticVersion version) { if (versionSpec == null) return true; // I CAN'T DEAL WITH THIS bool minVersion; if (versionSpec.MinVersion == null) { minVersion = true; // no preconditon? LET'S DO IT } else if (versionSpec.IsMinInclusive) { minVersion = version >= versionSpec.MinVersion; } else { minVersion = version > versionSpec.MinVersion; } bool maxVersion; if (versionSpec.MaxVersion == null) { maxVersion = true; // no preconditon? LET'S DO IT } else if (versionSpec.IsMaxInclusive) { maxVersion = version <= versionSpec.MaxVersion; } else { maxVersion = version < versionSpec.MaxVersion; } return maxVersion && minVersion; } } public class ReleasePackage : IEnableLogger, IReleasePackage { public ReleasePackage(string inputPackageFile, bool isReleasePackage = false) { InputPackageFile = inputPackageFile; if (isReleasePackage) { ReleasePackageFile = inputPackageFile; } } public string InputPackageFile { get; protected set; } public string ReleasePackageFile { get; protected set; } public string SuggestedReleaseFileName { get { var zp = new ZipPackage(InputPackageFile); return String.Format("{0}-{1}-full.nupkg", zp.Id, zp.Version); } } public SemanticVersion Version { get { return InputPackageFile.ToSemanticVersion(); } } public string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null, Action<string> contentsPostProcessHook = null) { Contract.Requires(!String.IsNullOrEmpty(outputFile)); releaseNotesProcessor = releaseNotesProcessor ?? (x => (new Markdown()).Transform(x)); if (ReleasePackageFile != null) { return ReleasePackageFile; } var package = new ZipPackage(InputPackageFile); // we can tell from here what platform(s) the package targets // but given this is a simple package we only // ever expect one entry here (crash hard otherwise) var frameworks = package.GetSupportedFrameworks(); if (frameworks.Count() > 1) { var platforms = frameworks .Aggregate(new StringBuilder(), (sb, f) => sb.Append(f.ToString() + "; ")); throw new InvalidOperationException(String.Format( "The input package file {0} targets multiple platforms - {1} - and cannot be transformed into a release package.", InputPackageFile, platforms)); } else if (!frameworks.Any()) { throw new InvalidOperationException(String.Format( "The input package file {0} targets no platform and cannot be transformed into a release package.", InputPackageFile)); } var targetFramework = frameworks.Single(); // Recursively walk the dependency tree and extract all of the // dependent packages into the a temporary directory this.Log().Info("Creating release package: {0} => {1}", InputPackageFile, outputFile); var dependencies = findAllDependentPackages( package, new LocalPackageRepository(packagesRootDir), frameworkName: targetFramework); string tempPath = null; using (Utility.WithTempDirectory(out tempPath, null)) { var tempDir = new DirectoryInfo(tempPath); extractZipDecoded(InputPackageFile, tempPath); this.Log().Info("Extracting dependent packages: [{0}]", String.Join(",", dependencies.Select(x => x.Id))); extractDependentPackages(dependencies, tempDir, targetFramework); var specPath = tempDir.GetFiles("*.nuspec").First().FullName; this.Log().Info("Removing unnecessary data"); removeDependenciesFromPackageSpec(specPath); removeDeveloperDocumentation(tempDir); if (releaseNotesProcessor != null) { renderReleaseNotesMarkdown(specPath, releaseNotesProcessor); } addDeltaFilesToContentTypes(tempDir.FullName); if (contentsPostProcessHook != null) { contentsPostProcessHook(tempPath); } createZipEncoded(outputFile, tempPath); ReleasePackageFile = outputFile; return ReleasePackageFile; } } // nupkg file %-encodes zip entry names. This method decodes entry names before writing to disk. // We must do this, or PathTooLongException may be thrown for some unicode entry names. void extractZipDecoded(string zipFilePath, string outFolder) { var zf = new ZipFile(zipFilePath); foreach (ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) continue; var entryFileName = Uri.UnescapeDataString(zipEntry.Name); var buffer = new byte[4096]; var zipStream = zf.GetInputStream(zipEntry); var fullZipToPath = Path.Combine(outFolder, entryFileName); var directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } zf.Close(); } // Create zip file with entry names %-encoded, as nupkg file does. void createZipEncoded(string zipFilePath, string folder) { folder = Path.GetFullPath(folder); var offset = folder.Length + (folder.EndsWith("\\", StringComparison.OrdinalIgnoreCase) ? 1 : 0); var fsOut = File.Create(zipFilePath); var zipStream = new ZipOutputStream(fsOut); zipStream.SetLevel(5); compressFolderEncoded(folder, zipStream, offset); zipStream.IsStreamOwner = true; zipStream.Close(); } void compressFolderEncoded(string path, ZipOutputStream zipStream, int folderOffset) { string[] files = Directory.GetFiles(path); foreach (string filename in files) { FileInfo fi = new FileInfo(filename); string entryName = filename.Substring(folderOffset); entryName = ZipEntry.CleanName(entryName); entryName = Uri.EscapeUriString(entryName); var newEntry = new ZipEntry(entryName); newEntry.DateTime = fi.LastWriteTime; newEntry.Size = fi.Length; zipStream.PutNextEntry(newEntry); var buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } string[] folders = Directory.GetDirectories(path); foreach (string folder in folders) { compressFolderEncoded(folder, zipStream, folderOffset); } } void extractDependentPackages(IEnumerable<IPackage> dependencies, DirectoryInfo tempPath, FrameworkName framework) { dependencies.ForEach(pkg => { this.Log().Info("Scanning {0}", pkg.Id); pkg.GetLibFiles().ForEach(file => { var outPath = new FileInfo(Path.Combine(tempPath.FullName, file.Path)); if (!VersionUtility.IsCompatible(framework , new[] { file.TargetFramework })) { this.Log().Info("Ignoring {0} as the target framework is not compatible", outPath); return; } Directory.CreateDirectory(outPath.Directory.FullName); using (var of = File.Create(outPath.FullName)) { this.Log().Info("Writing {0} to {1}", file.Path, outPath); file.GetStream().CopyTo(of); } }); }); } void removeDeveloperDocumentation(DirectoryInfo expandedRepoPath) { expandedRepoPath.GetAllFilesRecursively() .Where(x => x.Name.EndsWith(".dll", true, CultureInfo.InvariantCulture)) .Select(x => new FileInfo(x.FullName.ToLowerInvariant().Replace(".dll", ".xml"))) .Where(x => x.Exists) .ForEach(x => x.Delete()); } void renderReleaseNotesMarkdown(string specPath, Func<string, string> releaseNotesProcessor) { var doc = new XmlDocument(); doc.Load(specPath); // XXX: This code looks full tart var metadata = doc.DocumentElement.ChildNodes .OfType<XmlElement>() .First(x => x.Name.ToLowerInvariant() == "metadata"); var releaseNotes = metadata.ChildNodes .OfType<XmlElement>() .FirstOrDefault(x => x.Name.ToLowerInvariant() == "releasenotes"); if (releaseNotes == null) { this.Log().Info("No release notes found in {0}", specPath); return; } releaseNotes.InnerText = String.Format("<![CDATA[\n" + "{0}\n" + "]]>", releaseNotesProcessor(releaseNotes.InnerText)); doc.Save(specPath); } void removeDependenciesFromPackageSpec(string specPath) { var xdoc = new XmlDocument(); xdoc.Load(specPath); var metadata = xdoc.DocumentElement.FirstChild; var dependenciesNode = metadata.ChildNodes.OfType<XmlElement>().FirstOrDefault(x => x.Name.ToLowerInvariant() == "dependencies"); if (dependenciesNode != null) { metadata.RemoveChild(dependenciesNode); } xdoc.Save(specPath); } internal IEnumerable<IPackage> findAllDependentPackages( IPackage package = null, IPackageRepository packageRepository = null, HashSet<string> packageCache = null, FrameworkName frameworkName = null) { package = package ?? new ZipPackage(InputPackageFile); packageCache = packageCache ?? new HashSet<string>(); var deps = package.DependencySets .Where(x => x.TargetFramework == null || x.TargetFramework == frameworkName) .SelectMany(x => x.Dependencies); return deps.SelectMany(dependency => { var ret = matchPackage(packageRepository, dependency.Id, dependency.VersionSpec); if (ret == null) { var message = String.Format("Couldn't find file for package in {1}: {0}", dependency.Id, packageRepository.Source); this.Log().Error(message); throw new Exception(message); } if (packageCache.Contains(ret.GetFullName())) { return Enumerable.Empty<IPackage>(); } packageCache.Add(ret.GetFullName()); return findAllDependentPackages(ret, packageRepository, packageCache, frameworkName).StartWith(ret).Distinct(y => y.GetFullName()); }).ToArray(); } IPackage matchPackage(IPackageRepository packageRepository, string id, IVersionSpec version) { return packageRepository.FindPackagesById(id).FirstOrDefault(x => VersionComparer.Matches(version, x.Version)); } static internal void addDeltaFilesToContentTypes(string rootDirectory) { var doc = new XmlDocument(); var path = Path.Combine(rootDirectory, "[Content_Types].xml"); doc.Load(path); ContentType.Merge(doc); using (var sw = new StreamWriter(path, false, Encoding.UTF8)) { doc.Save(sw); } } } public class ChecksumFailedException : Exception { public string Filename { get; set; } } }
using UnityEngine; using UnityEditor; using System.IO; using System.Collections; public class FlatColorUI : EditorWindow { #region showColor Bools public bool showReds = false; public bool showPinks = false; public bool showPurple = false; public bool showBlue = false; public bool showGreen = false; public bool showYellow = false; public bool showOrange = false; public bool showGray = false; public bool showOptions = false; #endregion //the scroll position stored in a Vector2 private Vector2 scrollPos; //Colors #region Reds private Color ChestNutRose = new Color(0.823f, 0.301f, 0.341f); private Color Pomegranate = new Color(0.95f, 0.14f, 0.074f); private Color Red = new Color(1, 0, 0); private Color ThunderBird = new Color(0.85f, 0.117f, 0.09f); private Color OldBrick = new Color(0.588f, 0.156f, 0.10f); private Color Flamingo = new Color(0.937f, 0.282f, 0.211f); //TODO: Check if Tall Poppy is correct. private Color TallPoppy = new Color(0.752f, 0.22f, 0.168f); private Color Monza = new Color(0.811f, 0, 0.058f); private Color Cinnabar = new Color(0.905f, 0.298f, 0.235f); #endregion #region Pinks private Color Razzmatazz = new Color(0.858f, 0.0392f, 0.356f); private Color Derby = new Color(1, 0.925f, 0.858f); private Color SunsetOrange = new Color(0.964f, 0.278f, 0.278f); private Color WaxFlower = new Color(0.945f, 0.662f, 0.627f); private Color Cabaret = new Color(0.823f, 0.321f, 0.498f); private Color NewYorkPink = new Color(0.878f, 0.509f, 0.513f); private Color RadicalRed = new Color(0.964f, 0.141f, 0.349f); private Color Sunglo = new Color(0.886f, 0.415f, 0.415f); #endregion #region Purple private Color Snuff = new Color(0.862f, 0.776f, 0.878f); private Color RebeccaPurple = new Color(0.4f, 0.2f, 0.6f); private Color HoneyFlower = new Color(0.403f, 0.254f, 0.447f); private Color Wistful = new Color(0.682f, 0.658f, 0.827f); private Color Plum = new Color(0.568f, 0.239f, 0.533f); private Color Seance = new Color(0.603f, 0.070f, 0.701f); private Color MediumPurple = new Color(0.749f, 0.333f, 0.925f); private Color LightWisteria = new Color(0.745f, 0.564f, 0.831f); private Color Studio = new Color(0.556f, 0.266f, 0.678f); private Color Wisteria = new Color(0.607f, 0.349f, 0.713f); #endregion #region Blue private Color SanMarino = new Color(0.266f, 0.423f, 0.701f); private Color AliceBlue = new Color(0.894f, 0.945f, 0.996f); private Color RoyalBlue = new Color(0.254f, 0.513f, 0.843f); private Color PictonBlue = new Color(0.349f, 0.670f, 0.890f); private Color Spray = new Color(0.505f, 0.811f, 0.878f); private Color Shakespeare = new Color(0.321f, 0.701f, 0.850f); private Color HummingBird = new Color(0.772f, 0.937f, 0.968f); private Color PictonBlueTwo = new Color(0.203f, 0.596f, 0.858f); private Color Madison = new Color(0.172f, 0.243f, 0.313f); private Color DodgerBlue = new Color(0.098f, 0.709f, 0.996f); private Color Ming = new Color(0.2f, 0.431f, 0.482f); private Color EbonyClay = new Color(0.133f, 0.192f, 0.247f); private Color Malibu = new Color(0.419f, 0.725f, 0.941f); private Color CuriousBlue = new Color(0.117f, 0.545f, 0.764f); private Color Chambray = new Color(0.227f, 0.325f, 0.607f); private Color PickledBlueWood = new Color(0.203f, 0.286f, 0.368f); private Color Hoki = new Color(0.403f, 0.501f, 0.623f); private Color JellyBean = new Color(0.145f, 0.454f, 0.662f); private Color JacksonsPurple = new Color(0.121f, 0.227f, 0.576f); private Color JordyBlue = new Color(0.537f, 0.768f, 0.956f); private Color SteelBlue = new Color(0.294f, 0.466f, 0.745f); private Color FoundtainBlue = new Color(0.360f, 0.592f, 0.749f); #endregion #region Green private Color MediumTurquoise = new Color(0.305f, 0.803f, 0.768f); private Color AquaIsland = new Color(0.635f, 0.870f, 0.815f); private Color Gossip = new Color(0.529f, 0.827f, 0.486f); private Color DarkSeaGreen = new Color(0.564f, 0.776f, 0.584f); private Color Eucalyptus = new Color(0.149f, 0.650f, 0.356f); private Color CaribbeanGreen = new Color(0.011f, 0.650f, 0.356f); private Color SilverTree = new Color(0.407f, 0.764f, 0.639f); private Color Downy = new Color(0.396f, 0.776f, 0.733f); private Color MountainMeadow = new Color(0.105f, 0.737f, 0.607f); private Color LightSeaGreen = new Color(0.105f, 0.639f, 0.611f); private Color MediumAquaMarine = new Color(0.4f, 0.8f, 0.6f); private Color Turquoise = new Color(0.211f, 0.843f, 0.717f); private Color Madang = new Color(0.784f, 0.968f, 0.772f); private Color Riptide = new Color(0.525f, 0.886f, 0.835f); private Color Shamrock = new Color(0.180f, 0.8f, 0.443f); private Color MountainMeadowTwo = new Color(0.086f, 0.627f, 0.521f); private Color Emerald = new Color(0.247f, 0.764f, 0.501f); private Color GreenHaze = new Color(0.003f, 0.596f, 0.458f); private Color FreeSpeechAquaMarine = new Color(0.011f, 0.650f, 0.470f); private Color OceanGreen = new Color(0.301f, 0.686f, 0.486f); private Color Niagara = new Color(0.164f, 0.733f, 0.607f); private Color Jade = new Color(0, 0.694f, 0.415f); private Color Salem = new Color(0.117f, 0.509f, 0.298f); private Color Observatory = new Color(0.015f, 0.576f, 0.447f); private Color JungleGreen = new Color(0.149f, 0.760f, 0.505f); #endregion #region Yellow private Color CreamCan = new Color(0.960f, 0.843f, 0.431f); private Color RipeLemon = new Color(0.968f, 0.792f, 0.094f); private Color Saffron = new Color(0.956f, 0.815f, 0.247f); #endregion [MenuItem("Window/FlatColorUI")] public static void ShowWindow() { //Show existing window instance. If one doesn't exist, make one. EditorWindow.GetWindow(typeof(FlatColorUI)); } // Use this for initialization void Start() { } /// Create Material /// <summary> /// Create a material in the Assets Folder /// </summary> /// <param name="newColor"></param> /// <param name="materialName"></param> void CreateMaterial(Color newColor, string materialName) { var newMaterial = new Material(Shader.Find("Diffuse")); newMaterial.color = newColor; AssetDatabase.CreateAsset(newMaterial, "Assets/" + materialName + ".mat"); Debug.Log("Created FlatUI Material: " + AssetDatabase.GetAssetPath(newMaterial)); } void OnGUI() { //Title GUILayout.Space(10); GUILayout.Label("Flat Color UI: Created by @kinifi"); scrollPos = EditorGUILayout.BeginScrollView(scrollPos); #region Red Colors showReds = EditorGUILayout.Foldout(showReds, "Reds"); if (showReds) { GUILayout.Space(5); #region ChestNut Red EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); ChestNutRose = EditorGUILayout.ColorField("ChestNut Rose:", ChestNutRose); if (GUILayout.Button("Create ChestNut Rose")) { CreateMaterial(ChestNutRose, "ChestNut_Rose"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Pomegranate EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Pomegranate = EditorGUILayout.ColorField("Pomegranate:", Pomegranate); if (GUILayout.Button("Create Pomegranate")) { CreateMaterial(Pomegranate, "Pomegranate"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Red EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Red = EditorGUILayout.ColorField("Red:", Red); if (GUILayout.Button("Create Red")) { CreateMaterial(Red, "Red"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region ThunderBird EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); ThunderBird = EditorGUILayout.ColorField("ThunderBird:", ThunderBird); if (GUILayout.Button("Create ThunderBird")) { CreateMaterial(ThunderBird, "ThunderBird"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region OldBrick EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); OldBrick = EditorGUILayout.ColorField("OldBrick:", OldBrick); if (GUILayout.Button("Create OldBrick")) { CreateMaterial(OldBrick, "OldBrick"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Flamingo EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Flamingo = EditorGUILayout.ColorField("Flamingo:", Flamingo); if (GUILayout.Button("Create Flamingo")) { CreateMaterial(Flamingo, "Flamingo"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region TallPoppy EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); TallPoppy = EditorGUILayout.ColorField("TallPoppy:", TallPoppy); if (GUILayout.Button("Create TallPoppy")) { CreateMaterial(TallPoppy, "TallPoppy"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Monza EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Monza = EditorGUILayout.ColorField("Monza:", Monza); if (GUILayout.Button("Create Monza")) { CreateMaterial(Monza, "Monza"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Cinnabar EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Cinnabar = EditorGUILayout.ColorField("Cinnabar:", Cinnabar); if (GUILayout.Button("Create Cinnabar")) { CreateMaterial(Cinnabar, "Cinnabar"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion } #endregion #region Pinks Colors EditorGUI.indentLevel = 0; showPinks = EditorGUILayout.Foldout(showPinks, "Pinks"); if (showPinks) { #region Razzmatazz EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Razzmatazz = EditorGUILayout.ColorField("Razzmatazz:", Razzmatazz); if (GUILayout.Button("Create Razzmatazz")) { CreateMaterial(Razzmatazz, "Razzmatazz"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Derby EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Derby = EditorGUILayout.ColorField("Derby:", Derby); if (GUILayout.Button("Create Derby")) { CreateMaterial(Derby, "Derby"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region SunsetOrange EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); SunsetOrange = EditorGUILayout.ColorField("SunsetOrange:", SunsetOrange); if (GUILayout.Button("Create SunsetOrange")) { CreateMaterial(SunsetOrange, "SunsetOrange"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region WaxFlower EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); WaxFlower = EditorGUILayout.ColorField("WaxFlower:", WaxFlower); if (GUILayout.Button("Create WaxFlower")) { CreateMaterial(WaxFlower, "WaxFlower"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Cabaret EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Cabaret = EditorGUILayout.ColorField("Cabaret:", Cabaret); if (GUILayout.Button("Create Cabaret")) { CreateMaterial(Cabaret, "Cabaret"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region NewYorkPink EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); NewYorkPink = EditorGUILayout.ColorField("NewYorkPink:", NewYorkPink); if (GUILayout.Button("Create NewYorkPink")) { CreateMaterial(NewYorkPink, "NewYorkPink"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region RadicalRed EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); RadicalRed = EditorGUILayout.ColorField("RadicalRed:", RadicalRed); if (GUILayout.Button("Create RadicalRed")) { CreateMaterial(RadicalRed, "RadicalRed"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Sunglo EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Sunglo = EditorGUILayout.ColorField("Sunglo:", Sunglo); if (GUILayout.Button("Create Sunglo")) { CreateMaterial(Sunglo, "Sunglo"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion } #endregion #region Purple Colors EditorGUI.indentLevel = 0; showPurple = EditorGUILayout.Foldout(showPurple, "Purples"); if (showPurple) { #region Snuff EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Snuff = EditorGUILayout.ColorField("Snuff:", Snuff); if (GUILayout.Button("Create Snuff")) { CreateMaterial(Snuff, "Snuff"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region RebeccaPurple EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); RebeccaPurple = EditorGUILayout.ColorField("RebeccaPurple:", RebeccaPurple); if (GUILayout.Button("Create RebeccaPurple")) { CreateMaterial(RebeccaPurple, "RebeccaPurple"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region HoneyFlower EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); HoneyFlower = EditorGUILayout.ColorField("HoneyFlower:", HoneyFlower); if (GUILayout.Button("Create HoneyFlower")) { CreateMaterial(HoneyFlower, "HoneyFlower"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Wistful EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Wistful = EditorGUILayout.ColorField("Wistful:", Wistful); if (GUILayout.Button("Create Wistful")) { CreateMaterial(Wistful, "Wistful"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Plum EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Plum = EditorGUILayout.ColorField("Plum:", Plum); if (GUILayout.Button("Create Plum")) { CreateMaterial(Plum, "Plum"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Seance EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Seance = EditorGUILayout.ColorField("Seance:", Seance); if (GUILayout.Button("Create Seance")) { CreateMaterial(Seance, "Seance"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region MediumPurple EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); MediumPurple = EditorGUILayout.ColorField("MediumPurple:", MediumPurple); if (GUILayout.Button("Create MediumPurple")) { CreateMaterial(MediumPurple, "MediumPurple"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region LightWisteria EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); LightWisteria = EditorGUILayout.ColorField("LightWisteria:", LightWisteria); if (GUILayout.Button("Create LightWisteria")) { CreateMaterial(LightWisteria, "LightWisteria"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Studio EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Studio = EditorGUILayout.ColorField("Studio:", Studio); if (GUILayout.Button("Create Studio")) { CreateMaterial(Studio, "Studio"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Wisteria EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Wisteria = EditorGUILayout.ColorField("Wisteria:", Wisteria); if (GUILayout.Button("Create Wisteria")) { CreateMaterial(Wisteria, "Wisteria"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion } #endregion #region Blue Colors EditorGUI.indentLevel = 0; showBlue = EditorGUILayout.Foldout(showBlue, "Blue"); if (showBlue) { #region SanMarino EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); SanMarino = EditorGUILayout.ColorField("SanMarino:", SanMarino); if (GUILayout.Button("Create SanMarino")) { CreateMaterial(SanMarino, "SanMarino"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region AliceBlue EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); AliceBlue = EditorGUILayout.ColorField("AliceBlue:", AliceBlue); if (GUILayout.Button("Create AliceBlue")) { CreateMaterial(AliceBlue, "AliceBlue"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region RoyalBlue EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); RoyalBlue = EditorGUILayout.ColorField("RoyalBlue:", RoyalBlue); if (GUILayout.Button("Create RoyalBlue")) { CreateMaterial(RoyalBlue, "RoyalBlue"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region PictonBlue EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); PictonBlue = EditorGUILayout.ColorField("PictonBlue:", PictonBlue); if (GUILayout.Button("Create PictonBlue")) { CreateMaterial(PictonBlue, "PictonBlue"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Spray EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Spray = EditorGUILayout.ColorField("Spray:", Spray); if (GUILayout.Button("Create Spray")) { CreateMaterial(Spray, "Spray"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Shakespeare EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Shakespeare = EditorGUILayout.ColorField("Shakespeare:", Shakespeare); if (GUILayout.Button("Create Shakespeare")) { CreateMaterial(Shakespeare, "Shakespeare"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region HummingBird EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); HummingBird = EditorGUILayout.ColorField("HummingBird:", HummingBird); if (GUILayout.Button("Create HummingBird")) { CreateMaterial(HummingBird, "HummingBird"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region PictonBlueTwo EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); PictonBlueTwo = EditorGUILayout.ColorField("PictonBlueTwo:", PictonBlueTwo); if (GUILayout.Button("Create PictonBlueTwo")) { CreateMaterial(PictonBlueTwo, "PictonBlueTwo"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Madison EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Madison = EditorGUILayout.ColorField("Madison:", Madison); if (GUILayout.Button("Create Madison")) { CreateMaterial(Madison, "Madison"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region DodgerBlue EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); DodgerBlue = EditorGUILayout.ColorField("DodgerBlue:", DodgerBlue); if (GUILayout.Button("Create DodgerBlue")) { CreateMaterial(DodgerBlue, "DodgerBlue"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Ming EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Ming = EditorGUILayout.ColorField("Ming:", Ming); if (GUILayout.Button("Create Ming")) { CreateMaterial(Ming, "Ming"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region EbonyClay EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); EbonyClay = EditorGUILayout.ColorField("EbonyClay:", EbonyClay); if (GUILayout.Button("Create EbonyClay")) { CreateMaterial(EbonyClay, "EbonyClay"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Malibu EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Malibu = EditorGUILayout.ColorField("Malibu:", Malibu); if (GUILayout.Button("Create Malibu")) { CreateMaterial(Malibu, "Malibu"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region CuriousBlue EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); CuriousBlue = EditorGUILayout.ColorField("CuriousBlue:", CuriousBlue); if (GUILayout.Button("Create CuriousBlue")) { CreateMaterial(CuriousBlue, "CuriousBlue"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Chambray EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Chambray = EditorGUILayout.ColorField("Chambray:", Chambray); if (GUILayout.Button("Create Chambray")) { CreateMaterial(Chambray, "Chambray"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region PickledBlueWood EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); PickledBlueWood = EditorGUILayout.ColorField("PickledBlueWood:", PickledBlueWood); if (GUILayout.Button("Create PickledBlueWood")) { CreateMaterial(PickledBlueWood, "PickledBlueWood"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Hoki EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Hoki = EditorGUILayout.ColorField("Hoki:", Hoki); if (GUILayout.Button("Create Hoki")) { CreateMaterial(Hoki, "Hoki"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region JellyBean EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); JellyBean = EditorGUILayout.ColorField("JellyBean:", JellyBean); if (GUILayout.Button("Create JellyBean")) { CreateMaterial(JellyBean, "JellyBean"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region JacksonsPurple EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); JacksonsPurple = EditorGUILayout.ColorField("JacksonsPurple:", JacksonsPurple); if (GUILayout.Button("Create JacksonsPurple")) { CreateMaterial(JacksonsPurple, "JacksonsPurple"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region JordyBlue EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); JordyBlue = EditorGUILayout.ColorField("JordyBlue:", JordyBlue); if (GUILayout.Button("Create JordyBlue")) { CreateMaterial(JordyBlue, "JordyBlue"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region SteelBlue EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); SteelBlue = EditorGUILayout.ColorField("SteelBlue:", SteelBlue); if (GUILayout.Button("Create SteelBlue")) { CreateMaterial(SteelBlue, "SteelBlue"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region FoundtainBlue EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); FoundtainBlue = EditorGUILayout.ColorField("FoundtainBlue:", FoundtainBlue); if (GUILayout.Button("Create FoundtainBlue")) { CreateMaterial(FoundtainBlue, "FoundtainBlue"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion } #endregion #region Green Colors EditorGUI.indentLevel = 0; showGreen = EditorGUILayout.Foldout(showGreen, "Green"); if (showGreen) { #region MediumTurquoise EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); MediumTurquoise = EditorGUILayout.ColorField("MediumTurquoise:", MediumTurquoise); if (GUILayout.Button("Create MediumTurquoise")) { CreateMaterial(MediumTurquoise, "MediumTurquoise"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region AquaIsland EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); AquaIsland = EditorGUILayout.ColorField("AquaIsland:", AquaIsland); if (GUILayout.Button("Create AquaIsland")) { CreateMaterial(AquaIsland, "AquaIsland"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Gossip EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Gossip = EditorGUILayout.ColorField("Gossip:", Gossip); if (GUILayout.Button("Create Gossip")) { CreateMaterial(Gossip, "Gossip"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region DarkSeaGreen EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); DarkSeaGreen = EditorGUILayout.ColorField("DarkSeaGreen:", DarkSeaGreen); if (GUILayout.Button("Create DarkSeaGreen")) { CreateMaterial(DarkSeaGreen, "DarkSeaGreen"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Eucalyptus EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Eucalyptus = EditorGUILayout.ColorField("Eucalyptus:", Eucalyptus); if (GUILayout.Button("Create Eucalyptus")) { CreateMaterial(Eucalyptus, "Eucalyptus"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region CaribbeanGreen EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); CaribbeanGreen = EditorGUILayout.ColorField("CaribbeanGreen:", CaribbeanGreen); if (GUILayout.Button("Create CaribbeanGreen")) { CreateMaterial(CaribbeanGreen, "CaribbeanGreen"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region SilverTree EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); SilverTree = EditorGUILayout.ColorField("SilverTree:", SilverTree); if (GUILayout.Button("Create SilverTree")) { CreateMaterial(SilverTree, "SilverTree"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Downy EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Downy = EditorGUILayout.ColorField("Downy:", Downy); if (GUILayout.Button("Create Downy")) { CreateMaterial(Downy, "Downy"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region MountainMeadow EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); MountainMeadow = EditorGUILayout.ColorField("MountainMeadow:", MountainMeadow); if (GUILayout.Button("Create MountainMeadow")) { CreateMaterial(MountainMeadow, "MountainMeadow"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region LightSeaGreen EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); LightSeaGreen = EditorGUILayout.ColorField("LightSeaGreen:", LightSeaGreen); if (GUILayout.Button("Create LightSeaGreen")) { CreateMaterial(LightSeaGreen, "LightSeaGreen"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region MediumAquaMarine EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); MediumAquaMarine = EditorGUILayout.ColorField("MediumAquaMarine:", MediumAquaMarine); if (GUILayout.Button("Create MediumAquaMarine")) { CreateMaterial(MediumAquaMarine, "MediumAquaMarine"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Turquoise EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Turquoise = EditorGUILayout.ColorField("Turquoise:", Turquoise); if (GUILayout.Button("Create Turquoise")) { CreateMaterial(Turquoise, "Turquoise"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Madang EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Madang = EditorGUILayout.ColorField("Madang:", Madang); if (GUILayout.Button("Create Madang")) { CreateMaterial(Madang, "Madang"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Riptide EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Riptide = EditorGUILayout.ColorField("Riptide:", Riptide); if (GUILayout.Button("Create Riptide")) { CreateMaterial(Riptide, "Riptide"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Shamrock EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Shamrock = EditorGUILayout.ColorField("Shamrock:", Shamrock); if (GUILayout.Button("Create Shamrock")) { CreateMaterial(Shamrock, "Shamrock"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region MountainMeadowTwo EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); MountainMeadowTwo = EditorGUILayout.ColorField("MountainMeadowTwo:", MountainMeadowTwo); if (GUILayout.Button("Create MountainMeadowTwo")) { CreateMaterial(MountainMeadowTwo, "MountainMeadowTwo"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Emerald EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Emerald = EditorGUILayout.ColorField("Emerald:", Emerald); if (GUILayout.Button("Create Emerald")) { CreateMaterial(Emerald, "Emerald"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region GreenHaze EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); GreenHaze = EditorGUILayout.ColorField("GreenHaze:", GreenHaze); if (GUILayout.Button("Create GreenHaze")) { CreateMaterial(GreenHaze, "GreenHaze"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region FreeSpeechAquaMarine EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); FreeSpeechAquaMarine = EditorGUILayout.ColorField("FreeSpeechAquaMarine:", FreeSpeechAquaMarine); if (GUILayout.Button("Create FreeSpeechAquaMarine")) { CreateMaterial(FreeSpeechAquaMarine, "FreeSpeechAquaMarine"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region OceanGreen EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); OceanGreen = EditorGUILayout.ColorField("OceanGreen:", OceanGreen); if (GUILayout.Button("Create OceanGreen")) { CreateMaterial(OceanGreen, "OceanGreen"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Niagara EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Niagara = EditorGUILayout.ColorField("Niagara:", Niagara); if (GUILayout.Button("Create Niagara")) { CreateMaterial(Niagara, "Niagara"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Jade EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Jade = EditorGUILayout.ColorField("Jade:", Jade); if (GUILayout.Button("Create Jade")) { CreateMaterial(Jade, "Jade"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Salem EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Salem = EditorGUILayout.ColorField("Salem:", Salem); if (GUILayout.Button("Create Salem")) { CreateMaterial(Salem, "Salem"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Observatory EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Observatory = EditorGUILayout.ColorField("Observatory:", Observatory); if (GUILayout.Button("Create Observatory")) { CreateMaterial(Observatory, "Observatory"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region JungleGreen EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); JungleGreen = EditorGUILayout.ColorField("JungleGreen:", JungleGreen); if (GUILayout.Button("Create JungleGreen")) { CreateMaterial(JungleGreen, "JungleGreen"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion } #endregion #region Yellow Colors EditorGUI.indentLevel = 0; showYellow = EditorGUILayout.Foldout(showYellow, "Yellows"); if (showYellow) { #region CreamCan EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); CreamCan = EditorGUILayout.ColorField("CreamCan:", CreamCan); if (GUILayout.Button("Create CreamCan")) { CreateMaterial(CreamCan, "CreamCan"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region RipeLemon EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); RipeLemon = EditorGUILayout.ColorField("RipeLemon:", RipeLemon); if (GUILayout.Button("Create RipeLemon")) { CreateMaterial(RipeLemon, "RipeLemon"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion #region Saffron EditorGUI.indentLevel = 1; GUILayout.BeginHorizontal(); Saffron = EditorGUILayout.ColorField("Saffron:", Saffron); if (GUILayout.Button("Create Saffron")) { CreateMaterial(CreamCan, "Saffron"); } GUILayout.EndHorizontal(); GUILayout.Space(5); #endregion } #endregion #region Orange Colors EditorGUI.indentLevel = 0; showOrange = EditorGUILayout.Foldout(showOrange, "Orange"); if (showOrange) { } #endregion #region Gray Colors EditorGUI.indentLevel = 0; showGray = EditorGUILayout.Foldout(showGray, "Grays"); if (showGray) { } #endregion EditorGUILayout.EndScrollView(); } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Swashbuckle.SwaggerGen.Annotations; using SchoolBusAPI.Models; using SchoolBusAPI.ViewModels; using SchoolBusAPI.Services; namespace SchoolBusAPI.Controllers { /// <summary> /// /// </summary> public partial class SchoolBusApiController : Controller { private readonly ISchoolBusApiService _service; /// <summary> /// Create a controller and set the service /// </summary> public SchoolBusApiController(ISchoolBusApiService service) { _service = service; } /// <summary> /// Creates a new school bus /// </summary> /// <remarks>The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource. For 201 (Created) responses, the Location is that of the new resource which was created by the request. The field value consists of a single absolute URI. </remarks> /// <param name="item"></param> /// <response code="201">SchoolBus created</response> [HttpPost] [Route("/api/schoolbuses")] [SwaggerOperation("AddBus")] [SwaggerResponse(200, type: typeof(SchoolBus))] public virtual IActionResult AddBus([FromBody]SchoolBus item) { return this._service.AddBusAsync(item); } /// <summary> /// Creates several school buses /// </summary> /// <remarks>Used for bulk creation of schoolbus records.</remarks> /// <param name="items"></param> /// <response code="201">SchoolBus items created</response> [HttpPost] [Route("/api/schoolbuses/bulk")] [SwaggerOperation("AddSchoolBusBulk")] public virtual IActionResult AddSchoolBusBulk([FromBody]SchoolBus[] items) { return this._service.AddSchoolBusBulkAsync(items); } /// <summary> /// Returns a single school bus object /// </summary> /// <remarks></remarks> /// <param name="id">Id of SchoolBus to fetch</param> /// <response code="200">OK</response> /// <response code="404">Not Found</response> [HttpGet] [Route("/api/schoolbuses/{id}")] [SwaggerOperation("FindBusById")] [SwaggerResponse(200, type: typeof(SchoolBus))] public virtual IActionResult FindBusById([FromRoute]int id) { return this._service.FindBusByIdAsync(id); } /// <summary> /// Returns a collection of school buses /// </summary> /// <remarks></remarks> /// <response code="200">OK</response> [HttpGet] [Route("/api/schoolbuses")] [SwaggerOperation("GetAllBuses")] [SwaggerResponse(200, type: typeof(List<SchoolBus>))] public virtual IActionResult GetAllBuses() { return this._service.GetAllBusesAsync(); } /// <summary> /// /// </summary> /// <remarks>Returns attachments for a particular SchoolBus</remarks> /// <param name="id">id of SchoolBus to fetch attachments for</param> /// <response code="200">OK</response> /// <response code="404">SchoolBus not found</response> [HttpGet] [Route("/api/schoolbuses/{id}/attachments")] [SwaggerOperation("SchoolbusesIdAttachmentsGet")] [SwaggerResponse(200, type: typeof(List<SchoolBusAttachment>))] public virtual IActionResult SchoolbusesIdAttachmentsGet([FromRoute]int id) { return this._service.SchoolbusesIdAttachmentsGetAsync(id); } /// <summary> /// /// </summary> /// <remarks>Returns CCWData for a particular Schoolbus</remarks> /// <param name="id">id of SchoolBus to fetch CCWData for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/schoolbuses/{id}/ccwdata")] [SwaggerOperation("SchoolbusesIdCcwdataGet")] [SwaggerResponse(200, type: typeof(CCWData))] public virtual IActionResult SchoolbusesIdCcwdataGet([FromRoute]int id) { return this._service.SchoolbusesIdCcwdataGetAsync(id); } /// <summary> /// /// </summary> /// <param name="id">id of SchoolBus to delete</param> /// <response code="200">OK</response> /// <response code="404">SchoolBus not found</response> [HttpPost] [Route("/api/schoolbuses/{id}/delete")] [SwaggerOperation("SchoolbusesIdDeletePost")] public virtual IActionResult SchoolbusesIdDeletePost([FromRoute]int id) { return this._service.SchoolbusesIdDeletePostAsync(id); } /// <summary> /// /// </summary> /// <remarks>Returns History for a particular SchoolBus</remarks> /// <param name="id">id of SchoolBus to fetch SchoolBusHistory for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/schoolbuses/{id}/history")] [SwaggerOperation("SchoolbusesIdHistoryGet")] [SwaggerResponse(200, type: typeof(List<SchoolBusHistory>))] public virtual IActionResult SchoolbusesIdHistoryGet([FromRoute]int id) { return this._service.SchoolbusesIdHistoryGetAsync(id); } /// <summary> /// /// </summary> /// <param name="id">id of SchoolBus to fetch Inspections for</param> /// <response code="200">OK</response> /// <response code="404">SchoolBus not found</response> [HttpGet] [Route("/api/schoolbuses/{id}/inspections")] [SwaggerOperation("SchoolbusesIdInspectionsGet")] [SwaggerResponse(200, type: typeof(List<Inspection>))] public virtual IActionResult SchoolbusesIdInspectionsGet([FromRoute]int id) { return this._service.SchoolbusesIdInspectionsGetAsync(id); } /// <summary> /// /// </summary> /// <remarks>Returns notes for a particular SchoolBus.</remarks> /// <param name="id">id of SchoolBus to fetch notes for</param> /// <response code="200">OK</response> /// <response code="404">SchoolBus not found</response> [HttpGet] [Route("/api/schoolbuses/{id}/notes")] [SwaggerOperation("SchoolbusesIdNotesGet")] [SwaggerResponse(200, type: typeof(List<SchoolBusNote>))] public virtual IActionResult SchoolbusesIdNotesGet([FromRoute]int id) { return this._service.SchoolbusesIdNotesGetAsync(id); } /// <summary> /// Updates a single school bus object /// </summary> /// <remarks></remarks> /// <param name="id">Id of SchoolBus to fetch</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">Not Found</response> [HttpPut] [Route("/api/schoolbuses/{id}")] [SwaggerOperation("SchoolbusesIdPut")] [SwaggerResponse(200, type: typeof(SchoolBus))] public virtual IActionResult SchoolbusesIdPut([FromRoute]int id, [FromBody]SchoolBus item) { return this._service.SchoolbusesIdPutAsync(id, item); } /// <summary> /// Searches school buses /// </summary> /// <remarks>Used for the search schoolbus page.</remarks> /// <param name="serviceareas">Service areas (array of id numbers)</param> /// <param name="inspectors">Assigned School Bus Inspectors (array of id numbers)</param> /// <param name="cities">Cities (array of id numbers)</param> /// <param name="schooldistricts">School Districts (array of id numbers)</param> /// <param name="owner"></param> /// <param name="regi">ICBC Regi Number</param> /// <param name="vin">VIN</param> /// <param name="plate">License Plate String</param> /// <param name="includeInactive">True if Inactive schoolbuses will be returned</param> /// <param name="onlyReInspections">If true, only buses that need a re-inspection will be returned</param> /// <param name="startDate">Inspection start date</param> /// <param name="endDate">Inspection end date</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/schoolbuses/search")] [SwaggerOperation("SchoolbusesSearchGet")] [SwaggerResponse(200, type: typeof(List<SchoolBus>))] public virtual IActionResult SchoolbusesSearchGet([FromQuery]int?[] serviceareas, [FromQuery]int?[] inspectors, [FromQuery]int?[] cities, [FromQuery]int?[] schooldistricts, [FromQuery]int? owner, [FromQuery]string regi, [FromQuery]string vin, [FromQuery]string plate, [FromQuery]bool? includeInactive, [FromQuery]bool? onlyReInspections, [FromQuery]DateTime? startDate, [FromQuery]DateTime? endDate) { return this._service.SchoolbusesSearchGetAsync(serviceareas, inspectors, cities, schooldistricts, owner, regi, vin, plate, includeInactive, onlyReInspections, startDate, endDate); } } }
// // Copyright (c) 2004-2017 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. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD namespace NLog.Targets { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using NLog.Common; using NLog.Config; using NLog.Internal; using Layouts; /// <summary> /// Increments specified performance counter on each write. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/PerformanceCounter-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/PerfCounter/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/PerfCounter/Simple/Example.cs" /> /// </example> /// <remarks> /// TODO: /// 1. Unable to create a category allowing multiple counter instances (.Net 2.0 API only, probably) /// 2. Is there any way of adding new counters without deleting the whole category? /// 3. There should be some mechanism of resetting the counter (e.g every day starts from 0), or auto-switching to /// another counter instance (with dynamic creation of new instance). This could be done with layouts. /// </remarks> [Target("PerfCounter")] public class PerformanceCounterTarget : Target, IInstallable { private PerformanceCounter perfCounter; private bool initialized; private bool created; /// <summary> /// Initializes a new instance of the <see cref="PerformanceCounterTarget" /> class. /// </summary> public PerformanceCounterTarget() { this.CounterType = PerformanceCounterType.NumberOfItems32; this.IncrementValue = new SimpleLayout("1"); this.InstanceName = string.Empty; this.CounterHelp = string.Empty; } /// <summary> /// Initializes a new instance of the <see cref="PerformanceCounterTarget" /> class. /// </summary> /// <param name="name">Name of the target.</param> public PerformanceCounterTarget(string name) : this() { this.Name = name; } /// <summary> /// Gets or sets a value indicating whether performance counter should be automatically created. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> public bool AutoCreate { get; set; } /// <summary> /// Gets or sets the name of the performance counter category. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> [RequiredParameter] public string CategoryName { get; set; } /// <summary> /// Gets or sets the name of the performance counter. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> [RequiredParameter] public string CounterName { get; set; } /// <summary> /// Gets or sets the performance counter instance name. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> public string InstanceName { get; set; } /// <summary> /// Gets or sets the counter help text. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> public string CounterHelp { get; set; } /// <summary> /// Gets or sets the performance counter type. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> [DefaultValue(PerformanceCounterType.NumberOfItems32)] public PerformanceCounterType CounterType { get; set; } /// <summary> /// The value by which to increment the counter. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> [DefaultValue(1)] public Layout IncrementValue { get; set; } /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { // categories must be installed together, so we must find all PerfCounter targets in the configuration file var countersByCategory = this.LoggingConfiguration.AllTargets.OfType<PerformanceCounterTarget>().BucketSort(c => c.CategoryName); string categoryName = this.CategoryName; if (countersByCategory[categoryName].Any(c => c.created)) { installationContext.Trace("Category '{0}' has already been installed.", categoryName); return; } try { PerformanceCounterCategoryType categoryType; CounterCreationDataCollection ccds = GetCounterCreationDataCollection(countersByCategory[this.CategoryName], out categoryType); if (PerformanceCounterCategory.Exists(categoryName)) { installationContext.Debug("Deleting category '{0}'", categoryName); PerformanceCounterCategory.Delete(categoryName); } installationContext.Debug("Creating category '{0}' with {1} counter(s) (Type: {2})", categoryName, ccds.Count, categoryType); foreach (CounterCreationData c in ccds) { installationContext.Trace(" Counter: '{0}' Type: ({1}) Help: {2}", c.CounterName, c.CounterType, c.CounterHelp); } PerformanceCounterCategory.Create(categoryName, "Category created by NLog", categoryType, ccds); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } if (installationContext.IgnoreFailures) { installationContext.Warning("Error creating category '{0}': {1}", categoryName, exception.Message); } else { installationContext.Error("Error creating category '{0}': {1}", categoryName, exception.Message); throw; } if (exception.MustBeRethrown()) { throw; } } finally { foreach (var t in countersByCategory[categoryName]) { t.created = true; } } } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { string categoryName = this.CategoryName; if (PerformanceCounterCategory.Exists(categoryName)) { installationContext.Debug("Deleting category '{0}'", categoryName); PerformanceCounterCategory.Delete(categoryName); } else { installationContext.Debug("Category '{0}' does not exist.", categoryName); } } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { if (!PerformanceCounterCategory.Exists(this.CategoryName)) { return false; } return PerformanceCounterCategory.CounterExists(this.CounterName, this.CategoryName); } /// <summary> /// Increments the configured performance counter. /// </summary> /// <param name="logEvent">Log event.</param> protected override void Write(LogEventInfo logEvent) { if (this.EnsureInitialized()) { string incrementValueString = IncrementValue.Render(logEvent); long incrementValue; if (Int64.TryParse(incrementValueString, out incrementValue)) this.perfCounter.IncrementBy(incrementValue); else InternalLogger.Error("Error incrementing PerfCounter {0}. IncrementValue must be an integer but was <{1}>", CounterName, incrementValueString); } } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected override void CloseTarget() { base.CloseTarget(); if (this.perfCounter != null) { this.perfCounter.Close(); this.perfCounter = null; } this.initialized = false; } private static CounterCreationDataCollection GetCounterCreationDataCollection(IEnumerable<PerformanceCounterTarget> countersInCategory, out PerformanceCounterCategoryType categoryType) { categoryType = PerformanceCounterCategoryType.SingleInstance; var ccds = new CounterCreationDataCollection(); foreach (var counter in countersInCategory) { if (!string.IsNullOrEmpty(counter.InstanceName)) { categoryType = PerformanceCounterCategoryType.MultiInstance; } ccds.Add(new CounterCreationData(counter.CounterName, counter.CounterHelp, counter.CounterType)); } return ccds; } /// <summary> /// Ensures that the performance counter has been initialized. /// </summary> /// <returns>True if the performance counter is operational, false otherwise.</returns> private bool EnsureInitialized() { if (!this.initialized) { this.initialized = true; if (this.AutoCreate) { using (var context = new InstallationContext()) { this.Install(context); } } try { this.perfCounter = new PerformanceCounter(this.CategoryName, this.CounterName, this.InstanceName, false); } catch (Exception exception) { InternalLogger.Error(exception, "Cannot open performance counter {0}/{1}/{2}.", this.CategoryName, this.CounterName, this.InstanceName); if (exception.MustBeRethrown()) { throw; } } } return this.perfCounter != null; } } } #endif
#region Copyright notice and license // Copyright 2019 The 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.Net; using System.Net.Http.Headers; using Any; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Greet; using Grpc.AspNetCore.FunctionalTests.Infrastructure; using Grpc.Core; using Grpc.Tests.Shared; using Microsoft.Extensions.Logging; using NUnit.Framework; using AnyMessage = Google.Protobuf.WellKnownTypes.Any; namespace Grpc.AspNetCore.FunctionalTests.Server { [TestFixture] public class UnaryMethodTests : FunctionalTestBase { [Test] public async Task SendValidRequest_SuccessResponse() { // Arrange var requestMessage = new HelloRequest { Name = "World" }; var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); // Act var response = await Fixture.Client.PostAsync( "Greet.Greeter/SayHello", new GrpcStreamContent(ms)).DefaultTimeout(); // Assert var responseMessage = await response.GetSuccessfulGrpcMessageAsync<HelloReply>().DefaultTimeout(); Assert.AreEqual("Hello World", responseMessage.Message); response.AssertTrailerStatus(); } [Test] public async Task StreamedMessage_SuccessResponseAfterMessageReceived() { // Arrange var requestMessage = new HelloRequest { Name = "World" }; var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); var streamingContent = new StreamingContent(); var httpRequest = GrpcHttpHelper.Create("Greet.Greeter/SayHello"); httpRequest.Content = streamingContent; // Act var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead); // Assert Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming"); var requestStream = await streamingContent.GetRequestStreamAsync().DefaultTimeout(); await requestStream.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout(); streamingContent.Complete(); var response = await responseTask.DefaultTimeout(); var responseMessage = await response.GetSuccessfulGrpcMessageAsync<HelloReply>().DefaultTimeout(); Assert.AreEqual("Hello World", responseMessage.Message); } [Test] public async Task AdditionalDataAfterStreamedMessage_ErrorResponse() { // Arrange SetExpectedErrorsFilter(writeContext => { if (writeContext.LoggerName == TestConstants.ServerCallHandlerTestName && writeContext.EventId.Name == "ErrorReadingMessage" && writeContext.State.ToString() == "Error reading message.") { return true; } return false; }); var requestMessage = new HelloRequest { Name = "World" }; var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); var streamingContent = new StreamingContent(); var httpRequest = GrpcHttpHelper.Create("Greet.Greeter/SayHello"); httpRequest.Content = streamingContent; // Act var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead); // Assert Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming"); var requestStream = await streamingContent.GetRequestStreamAsync().DefaultTimeout(); await requestStream.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout(); await requestStream.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout(); streamingContent.Complete(); var response = await responseTask.DefaultTimeout(); // Read to end of response so headers are available await response.Content.CopyToAsync(new MemoryStream()).DefaultTimeout(); response.AssertTrailerStatus(StatusCode.Internal, "Additional data after the message received."); AssertHasLogRpcConnectionError(StatusCode.Internal, "Additional data after the message received."); } [Test] public async Task SendHeadersTwice_ThrowsException() { static async Task<HelloReply> ReturnHeadersTwice(HelloRequest request, ServerCallContext context) { await context.WriteResponseHeadersAsync(Metadata.Empty).DefaultTimeout(); await context.WriteResponseHeadersAsync(Metadata.Empty).DefaultTimeout(); return new HelloReply { Message = "Should never reach here" }; } // Arrange SetExpectedErrorsFilter(writeContext => { return writeContext.LoggerName == TestConstants.ServerCallHandlerTestName && writeContext.EventId.Name == "ErrorExecutingServiceMethod" && writeContext.State.ToString() == "Error when executing service method 'ReturnHeadersTwice'." && writeContext.Exception!.Message == "Response headers can only be sent once per call."; }); var requestMessage = new HelloRequest { Name = "World" }; var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); var method = Fixture.DynamicGrpc.AddUnaryMethod<HelloRequest, HelloReply>(ReturnHeadersTwice, nameof(ReturnHeadersTwice)); // Act var response = await Fixture.Client.PostAsync( method.FullName, new GrpcStreamContent(ms)).DefaultTimeout(); // Assert response.AssertIsSuccessfulGrpcRequest(); response.AssertTrailerStatus(StatusCode.Unknown, "Exception was thrown by handler. InvalidOperationException: Response headers can only be sent once per call."); } [Test] public async Task ServerMethodReturnsNull_FailureResponse() { // Arrange var method = Fixture.DynamicGrpc.AddUnaryMethod<HelloRequest, HelloReply>( (requestStream, context) => Task.FromResult<HelloReply>(null!)); var requestMessage = new HelloRequest { Name = "World" }; var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); // Act var response = await Fixture.Client.PostAsync( method.FullName, new GrpcStreamContent(ms)).DefaultTimeout(); // Assert response.AssertIsSuccessfulGrpcRequest(); response.AssertTrailerStatus(StatusCode.Cancelled, "No message returned from method."); AssertHasLogRpcConnectionError(StatusCode.Cancelled, "No message returned from method."); } [Test] public async Task ServerMethodThrowsExceptionWithTrailers_FailureResponse() { // Arrange var method = Fixture.DynamicGrpc.AddUnaryMethod<HelloRequest, HelloReply>((request, context) => { var trailers = new Metadata { new Metadata.Entry("test-trailer", "A value!") }; return Task.FromException<HelloReply>(new RpcException(new Status(StatusCode.Unknown, "User error"), trailers)); }); var requestMessage = new HelloRequest { Name = "World" }; var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); // Act var response = await Fixture.Client.PostAsync( method.FullName, new GrpcStreamContent(ms)).DefaultTimeout(); // Assert response.AssertIsSuccessfulGrpcRequest(); response.AssertTrailerStatus(StatusCode.Unknown, "User error"); // Trailer is written to the header because this is a Trailers-Only response Assert.AreEqual("A value!", response.Headers.GetValues("test-trailer").Single()); AssertHasLogRpcConnectionError(StatusCode.Unknown, "User error"); } [Test] public async Task ServerMethodThrowsNonRpcException_FailureResponse() { // Arrange SetExpectedErrorsFilter(writeContext => { return writeContext.LoggerName == TestConstants.ServerCallHandlerTestName && writeContext.EventId.Name == "ErrorExecutingServiceMethod" && writeContext.State.ToString() == "Error when executing service method 'GrpcErrorMethod'." && writeContext.Exception!.Message == "Non RPC exception."; }); var ex = new InvalidOperationException("Non RPC exception."); var method = Fixture.DynamicGrpc.AddUnaryMethod<HelloRequest, HelloReply>((request, context) => { return Task.FromException<HelloReply>(ex); }, "GrpcErrorMethod"); var requestMessage = new HelloRequest { Name = "World" }; var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); // Act var response = await Fixture.Client.PostAsync( method.FullName, new GrpcStreamContent(ms)).DefaultTimeout(); // Assert response.AssertIsSuccessfulGrpcRequest(); response.AssertTrailerStatus(StatusCode.Unknown, "Exception was thrown by handler. InvalidOperationException: Non RPC exception."); AssertHasLog(LogLevel.Error, "ErrorExecutingServiceMethod", "Error when executing service method 'GrpcErrorMethod'.", e => e == ex); } [Test] public async Task ValidRequest_ReturnContextInfoInTrailers() { static Task<Empty> ReturnContextInfoInTrailers(Empty request, ServerCallContext context) { context.ResponseTrailers.Add("Test-Method", context.Method); context.ResponseTrailers.Add("Test-Peer", context.Peer); context.ResponseTrailers.Add("Test-Host", context.Host); return Task.FromResult(new Empty()); } // Arrange var requestMessage = new Empty(); var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); var method = Fixture.DynamicGrpc.AddUnaryMethod<Empty, Empty>(ReturnContextInfoInTrailers); // Act var response = await Fixture.Client.PostAsync( method.FullName, new GrpcStreamContent(ms)).DefaultTimeout(); // Assert var responseMessage = await response.GetSuccessfulGrpcMessageAsync<Empty>().DefaultTimeout(); Assert.IsNotNull(responseMessage); var methodParts = response.TrailingHeaders.GetValues("Test-Method").Single().Split('/', StringSplitOptions.RemoveEmptyEntries); var serviceName = methodParts[0]; var methodName = methodParts[1]; Assert.AreEqual("DynamicService", serviceName); Assert.IsTrue(Guid.TryParse(methodName, out var _)); Assert.IsTrue(response.TrailingHeaders.TryGetValues("Test-Peer", out _)); Assert.AreEqual(Fixture.Client.BaseAddress!.Authority, response.TrailingHeaders.GetValues("Test-Host").Single()); } [Test] public async Task ThrowErrorInNonAsyncMethod_StatusMessageReturned() { static Task<Empty> ReturnContextInfoInTrailers(Empty request, ServerCallContext context) { throw new Exception("Test!"); } SetExpectedErrorsFilter(writeContext => { return writeContext.LoggerName == TestConstants.ServerCallHandlerTestName && writeContext.EventId.Name == "ErrorExecutingServiceMethod"; }); // Arrange var requestMessage = new Empty(); var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); var method = Fixture.DynamicGrpc.AddUnaryMethod<Empty, Empty>(ReturnContextInfoInTrailers); // Act var response = await Fixture.Client.PostAsync( method.FullName, new GrpcStreamContent(ms)).DefaultTimeout(); // Assert response.AssertTrailerStatus(StatusCode.Unknown, "Exception was thrown by handler. Exception: Test!"); } [Test] public async Task SingletonService_PrivateFieldsPreservedBetweenCalls() { // Arrange 1 var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, new Empty()); // Act 1 var response = await Fixture.Client.PostAsync( "singleton_count.Counter/IncrementCount", new GrpcStreamContent(ms)).DefaultTimeout(); // Assert 1 var total = await response.GetSuccessfulGrpcMessageAsync<SingletonCount.CounterReply>().DefaultTimeout(); Assert.AreEqual(1, total.Count); response.AssertTrailerStatus(); // Arrange 2 ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, new Empty()); // Act 2 response = await Fixture.Client.PostAsync( "singleton_count.Counter/IncrementCount", new GrpcStreamContent(ms)).DefaultTimeout(); // Assert 2 total = await response.GetSuccessfulGrpcMessageAsync<SingletonCount.CounterReply>().DefaultTimeout(); Assert.AreEqual(2, total.Count); response.AssertTrailerStatus(); } [TestCase(null, "Content-Type is missing from the request.")] [TestCase("application/json", "Content-Type 'application/json' is not supported.")] [TestCase("application/binary", "Content-Type 'application/binary' is not supported.")] public async Task InvalidContentType_Return415Response(string contentType, string responseMessage) { // Arrange var requestMessage = new HelloRequest { Name = "World" }; var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); var streamContent = new StreamContent(ms); streamContent.Headers.ContentType = contentType != null ? new MediaTypeHeaderValue(contentType) : null; // Act var response = await Fixture.Client.PostAsync( "Greet.Greeter/SayHello", streamContent).DefaultTimeout(); // Assert Assert.AreEqual(HttpStatusCode.UnsupportedMediaType, response.StatusCode); response.AssertTrailerStatus(StatusCode.Internal, responseMessage); } [Test] public async Task InvalidProtocol_Return426Response() { // Arrange var requestMessage = new HelloRequest { Name = "World" }; var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); var streamContent = new StreamContent(ms); streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/grpc"); var client = Fixture.CreateClient(TestServerEndpointName.Http1); // Act var response = await client.PostAsync( "Greet.Greeter/SayHello", streamContent).DefaultTimeout(); // Assert Assert.AreEqual(HttpStatusCode.UpgradeRequired, response.StatusCode); var upgradeValue = response.Headers.Upgrade.Single(); Assert.AreEqual("HTTP", upgradeValue.Name); Assert.AreEqual("2", upgradeValue.Version); response.AssertTrailerStatus(StatusCode.Internal, "Request protocol 'HTTP/1.1' is not supported."); } [TestCase("application/grpc")] [TestCase("APPLICATION/GRPC")] [TestCase("application/grpc+proto")] [TestCase("APPLICATION/GRPC+PROTO")] [TestCase("application/grpc+json")] // Accept any message format. A Method+marshaller may have been set that reads and writes JSON [TestCase("application/grpc; param=one")] public async Task ValidContentType_ReturnValidResponse(string contentType) { // Arrange var requestMessage = new HelloRequest { Name = "World" }; var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); var streamContent = new StreamContent(ms); streamContent.Headers.ContentType = contentType != null ? MediaTypeHeaderValue.Parse(contentType) : null; // Act var response = await Fixture.Client.PostAsync( "Greet.Greeter/SayHello", streamContent).DefaultTimeout(); // Assert var responseMessage = await response.GetSuccessfulGrpcMessageAsync<HelloReply>().DefaultTimeout(); Assert.AreEqual("Hello World", responseMessage.Message); response.AssertTrailerStatus(); } [Test] public async Task AnyRequest_SuccessResponse() { // Arrange 1 IMessage requestMessage = AnyMessage.Pack(new AnyProductRequest { Name = "Headlight fluid", Quantity = 2 }); var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); // Act 1 var response = await Fixture.Client.PostAsync( "any.AnyService/DoAny", new GrpcStreamContent(ms)).DefaultTimeout(); // Assert 1 var responseMessage = await response.GetSuccessfulGrpcMessageAsync<AnyMessageResponse>().DefaultTimeout(); Assert.AreEqual("2 x Headlight fluid", responseMessage.Message); response.AssertTrailerStatus(); // Arrange 2 requestMessage = AnyMessage.Pack(new AnyUserRequest { Name = "Arnie Admin", Enabled = true }); ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, requestMessage); // Act 2 response = await Fixture.Client.PostAsync( "any.AnyService/DoAny", new GrpcStreamContent(ms)).DefaultTimeout(); // Assert 2 responseMessage = await response.GetSuccessfulGrpcMessageAsync<AnyMessageResponse>().DefaultTimeout(); Assert.AreEqual("Arnie Admin - Enabled", responseMessage.Message); response.AssertTrailerStatus(); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ /*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ namespace Microsoft.Samples.VisualStudio.IronPythonProject { using System; using System.Reflection; using System.Globalization; using System.Resources; using System.Text; using System.Threading; using System.ComponentModel; using System.Security.Permissions; [AttributeUsage(AttributeTargets.All)] internal sealed class SRDescriptionAttribute : DescriptionAttribute { private bool replaced = false; public SRDescriptionAttribute(string description) : base(description) { } public override string Description { get { if (!replaced) { replaced = true; DescriptionValue = SR.GetString(base.Description); } return base.Description; } } } [AttributeUsage(AttributeTargets.All)] internal sealed class SRCategoryAttribute : CategoryAttribute { public SRCategoryAttribute(string category) : base(category) { } protected override string GetLocalizedString(string value) { return SR.GetString(value); } } internal sealed class SR { internal const string ProjectReferenceError = "ProjectReferenceError"; internal const string ProjectReferenceError2 = "ProjectReferenceError2"; internal const string Application = "Application"; internal const string ApplicationIcon = "ApplicationIcon"; internal const string ApplicationIconDescription = "ApplicationIconDescription"; internal const string AssemblyName = "AssemblyName"; internal const string AssemblyNameDescription = "AssemblyNameDescription"; internal const string DefaultNamespace = "DefaultNamespace"; internal const string DefaultNamespaceDescription = "DefaultNamespaceDescription"; internal const string GeneralCaption = "GeneralCaption"; internal const string OutputFile = "OutputFile"; internal const string OutputFileDescription = "OutputFileDescription"; internal const string OutputType = "OutputType"; internal const string OutputTypeDescription = "OutputTypeDescription"; internal const string Project = "Project"; internal const string ProjectFile = "ProjectFile"; internal const string ProjectFileDescription = "ProjectFileDescription"; internal const string ProjectFileExtensionFilter = "ProjectFileExtensionFilter"; internal const string ProjectFolder = "ProjectFolder"; internal const string ProjectFolderDescription = "ProjectFolderDescription"; internal const string StartupObject = "StartupObject"; internal const string StartupObjectDescription = "StartupObjectDescription"; internal const string TargetPlatform = "TargetPlatform"; internal const string TargetPlatformDescription = "TargetPlatformDescription"; internal const string TargetPlatformLocation = "TargetPlatformLocation"; internal const string TargetPlatformLocationDescription = "TargetPlatformLocationDescription"; static SR loader = null; ResourceManager resources; private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } internal SR() { resources = new System.Resources.ResourceManager("Microsoft.Samples.VisualStudio.IronPythonProject.Resources", this.GetType().Assembly); } private static SR GetLoader() { if (loader == null) { lock (InternalSyncObject) { if (loader == null) { loader = new SR(); } } } return loader; } private static CultureInfo Culture { get { return null/*use ResourceManager default, CultureInfo.CurrentUICulture*/; } } public static ResourceManager Resources { get { return GetLoader().resources; } } public static string GetString(string name, params object[] args) { SR sys = GetLoader(); if (sys == null) return null; string res = sys.resources.GetString(name, SR.Culture); if (args != null && args.Length > 0) { return String.Format(CultureInfo.CurrentCulture, res, args); } else { return res; } } public static string GetString(string name) { SR sys = GetLoader(); if (sys == null) return null; return sys.resources.GetString(name, SR.Culture); } public static object GetObject(string name) { SR sys = GetLoader(); if (sys == null) return null; return sys.resources.GetObject(name, SR.Culture); } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// SignHashDocument /// </summary> [DataContract] public partial class SignHashDocument : IEquatable<SignHashDocument>, IValidatableObject { public SignHashDocument() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="SignHashDocument" /> class. /// </summary> /// <param name="Data">.</param> /// <param name="DocumentId">Specifies the document ID number that the tab is placed on. This must refer to an existing Document&#39;s ID attribute..</param> /// <param name="Format">.</param> /// <param name="Name">.</param> /// <param name="RemainingSignatures">.</param> /// <param name="Revisions">.</param> /// <param name="SignatureType">.</param> public SignHashDocument(string Data = default(string), string DocumentId = default(string), string Format = default(string), string Name = default(string), string RemainingSignatures = default(string), List<Revision> Revisions = default(List<Revision>), string SignatureType = default(string)) { this.Data = Data; this.DocumentId = DocumentId; this.Format = Format; this.Name = Name; this.RemainingSignatures = RemainingSignatures; this.Revisions = Revisions; this.SignatureType = SignatureType; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="data", EmitDefaultValue=false)] public string Data { get; set; } /// <summary> /// Specifies the document ID number that the tab is placed on. This must refer to an existing Document&#39;s ID attribute. /// </summary> /// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document&#39;s ID attribute.</value> [DataMember(Name="documentId", EmitDefaultValue=false)] public string DocumentId { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="format", EmitDefaultValue=false)] public string Format { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="remainingSignatures", EmitDefaultValue=false)] public string RemainingSignatures { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="revisions", EmitDefaultValue=false)] public List<Revision> Revisions { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="signatureType", EmitDefaultValue=false)] public string SignatureType { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class SignHashDocument {\n"); sb.Append(" Data: ").Append(Data).Append("\n"); sb.Append(" DocumentId: ").Append(DocumentId).Append("\n"); sb.Append(" Format: ").Append(Format).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" RemainingSignatures: ").Append(RemainingSignatures).Append("\n"); sb.Append(" Revisions: ").Append(Revisions).Append("\n"); sb.Append(" SignatureType: ").Append(SignatureType).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as SignHashDocument); } /// <summary> /// Returns true if SignHashDocument instances are equal /// </summary> /// <param name="other">Instance of SignHashDocument to be compared</param> /// <returns>Boolean</returns> public bool Equals(SignHashDocument other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Data == other.Data || this.Data != null && this.Data.Equals(other.Data) ) && ( this.DocumentId == other.DocumentId || this.DocumentId != null && this.DocumentId.Equals(other.DocumentId) ) && ( this.Format == other.Format || this.Format != null && this.Format.Equals(other.Format) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.RemainingSignatures == other.RemainingSignatures || this.RemainingSignatures != null && this.RemainingSignatures.Equals(other.RemainingSignatures) ) && ( this.Revisions == other.Revisions || this.Revisions != null && this.Revisions.SequenceEqual(other.Revisions) ) && ( this.SignatureType == other.SignatureType || this.SignatureType != null && this.SignatureType.Equals(other.SignatureType) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Data != null) hash = hash * 59 + this.Data.GetHashCode(); if (this.DocumentId != null) hash = hash * 59 + this.DocumentId.GetHashCode(); if (this.Format != null) hash = hash * 59 + this.Format.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.RemainingSignatures != null) hash = hash * 59 + this.RemainingSignatures.GetHashCode(); if (this.Revisions != null) hash = hash * 59 + this.Revisions.GetHashCode(); if (this.SignatureType != null) hash = hash * 59 + this.SignatureType.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.StreamAnalytics; using Microsoft.Azure.Management.StreamAnalytics.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.StreamAnalytics { public partial class StreamAnalyticsManagementClient : ServiceClient<StreamAnalyticsManagementClient>, IStreamAnalyticsManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// The URI used as the base for all Service Management requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } set { this._baseUri = value; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// When you create a Windows Azure subscription, it is uniquely /// identified by a subscription ID. The subscription ID forms part of /// the URI for every call that you make to the Service Management /// API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } set { this._credentials = value; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IInputOperations _inputs; /// <summary> /// Operations for managing the input of the stream analytics job. /// </summary> public virtual IInputOperations Inputs { get { return this._inputs; } } private IJobOperations _streamingJobs; /// <summary> /// Operations for managing the stream analytics job. /// </summary> public virtual IJobOperations StreamingJobs { get { return this._streamingJobs; } } private IOutputOperations _outputs; /// <summary> /// Operations for managing the output of the stream analytics job. /// </summary> public virtual IOutputOperations Outputs { get { return this._outputs; } } private ISubscriptionOperations _subscriptions; /// <summary> /// Operations for Azure Stream Analytics subscription information. /// </summary> public virtual ISubscriptionOperations Subscriptions { get { return this._subscriptions; } } private ITransformationOperations _transformations; /// <summary> /// Operations for managing the transformation definition of the stream /// analytics job. /// </summary> public virtual ITransformationOperations Transformations { get { return this._transformations; } } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> public StreamAnalyticsManagementClient() : base() { this._inputs = new InputOperations(this); this._streamingJobs = new JobOperations(this); this._outputs = new OutputOperations(this); this._subscriptions = new SubscriptionOperations(this); this._transformations = new TransformationOperations(this); this._apiVersion = "2015-09-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(60); } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='baseUri'> /// Optional. The URI used as the base for all Service Management /// requests. /// </param> public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public StreamAnalyticsManagementClient(HttpClient httpClient) : base(httpClient) { this._inputs = new InputOperations(this); this._streamingJobs = new JobOperations(this); this._outputs = new OutputOperations(this); this._subscriptions = new SubscriptionOperations(this); this._transformations = new TransformationOperations(this); this._apiVersion = "2015-09-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(60); } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='baseUri'> /// Optional. The URI used as the base for all Service Management /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// StreamAnalyticsManagementClient instance /// </summary> /// <param name='client'> /// Instance of StreamAnalyticsManagementClient to clone to /// </param> protected override void Clone(ServiceClient<StreamAnalyticsManagementClient> client) { base.Clone(client); if (client is StreamAnalyticsManagementClient) { StreamAnalyticsManagementClient clonedClient = ((StreamAnalyticsManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-09-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.NotFound && statusCode != HttpStatusCode.Conflict && statusCode != HttpStatusCode.PreconditionFailed) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; // Deserialize Response result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Conflict) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.PreconditionFailed) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.NotFound) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The test result of the input or output data source. /// </returns> public async Task<DataSourceTestConnectionResponse> GetTestConnectionStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetTestConnectionStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); httpRequest.Headers.Add("x-ms-version", "2015-09-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.BadRequest) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataSourceTestConnectionResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent || statusCode == HttpStatusCode.BadRequest) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataSourceTestConnectionResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); result.DataSourceTestStatus = statusInstance; } JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken detailsValue = errorValue["details"]; if (detailsValue != null && detailsValue.Type != JTokenType.Null) { ErrorDetailsResponse detailsInstance = new ErrorDetailsResponse(); errorInstance.Details = detailsInstance; JToken codeValue2 = detailsValue["code"]; if (codeValue2 != null && codeValue2.Type != JTokenType.Null) { string codeInstance2 = ((string)codeValue2); detailsInstance.Code = codeInstance2; } JToken messageValue2 = detailsValue["message"]; if (messageValue2 != null && messageValue2.Type != JTokenType.Null) { string messageInstance2 = ((string)messageValue2); detailsInstance.Message = messageInstance2; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.BadRequest) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.NotFound) { result.Status = OperationStatus.Failed; } if (result.DataSourceTestStatus == DataSourceTestStatus.TestFailed) { result.Status = OperationStatus.Failed; } if (result.DataSourceTestStatus == DataSourceTestStatus.TestSucceeded) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
namespace Microsoft.WindowsAzure.Management.HDInsight.TestUtilities { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using System.IO; using System.Runtime.Serialization; using System.Xml; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.Data.Rdfe; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.Data; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.PocoClient.PaasClusters; using Microsoft.WindowsAzure.Management.HDInsight.Contracts; using Microsoft.WindowsAzure.Management.HDInsight.Contracts.May2014; using Microsoft.WindowsAzure.Management.HDInsight.Contracts.May2014.Components; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning; public class RootHandlerSimulatorController : ApiController { //Mapping between subscription id and Cluster internal static readonly IDictionary<string, List<Cluster>> _clustersAvailable = new Dictionary<string, List<Cluster>>(); [System.Web.Http.Route("~/{subscriptionId}/cloudservices")] [HttpGet] public HttpResponseMessage ListCloudServicesAsync(string subscriptionId) { var requestMessage = this.Request; var detailLevel = requestMessage.RequestUri.ParseQueryString()["detailLevel"]; List<Cluster> clusters; bool subExists = _clustersAvailable.TryGetValue(subscriptionId, out clusters); if (!subExists) { return this.Request.CreateResponse(HttpStatusCode.Accepted, new CloudServiceList()); } var clustersByLocation = clusters.GroupBy(c => c.Location); var cloudServiceList = new CloudServiceList(); foreach (var locationcluster in clustersByLocation) { var cloudService = new CloudService(); cloudService.Description = "test description"; cloudService.GeoRegion = locationcluster.Key; cloudService.Label = "test label"; cloudService.Resources = new ResourceList(); foreach (Cluster cluster in locationcluster) { var resource = new Resource(); resource.Name = cluster.DnsName; resource.Type = PaasClustersPocoClient.ClustersResourceType; resource.State = cluster.State.ToString(); resource.OutputItems = this.GetOutputItems(cluster); cloudService.Resources.Add(resource); } cloudServiceList.Add(cloudService); } return this.Request.CreateResponse(HttpStatusCode.Accepted, cloudServiceList); } [System.Web.Http.Route("~/{subscriptionId}/cloudservices/{cloudServiceName}/resources/{resourceNamespace}/clusters/{dnsName}")] [HttpDelete] public HttpResponseMessage DeleteCluster(string subscriptionId, string cloudServiceName, string resourceNamespace, string dnsName) { var requestMessage = this.Request; List<Cluster> clusters; bool subExists = _clustersAvailable.TryGetValue(subscriptionId, out clusters); if (!subExists) { return null; } var cluster = clusters.SingleOrDefault(c => c.DnsName.Equals(dnsName) && cloudServiceName.Contains(c.Location.Replace(" ", "-"))); if (cluster != null) { clusters.Remove(cluster); _clustersAvailable[subscriptionId] = clusters; } return this.Request.CreateResponse(HttpStatusCode.OK); } [Route("~/{subscriptionId}/cloudservices/{cloudServiceName}/resources/{resourceNamespace}/~/clusters/{dnsName}")] [HttpGet] public PassthroughResponse GetCluster(string subscriptionId, string cloudServiceName, string resourceNamespace, string dnsName) { return new PassthroughResponse { Data = this.GetCluster(dnsName, cloudServiceName, subscriptionId) }; } [Route("~/{subscriptionId}/services")] [HttpPut] public HttpResponseMessage RegisterSubscriptionIfNotExists(string subscriptionId) { return this.Request.CreateResponse(HttpStatusCode.OK); } [Route("~/{subscriptionId}/cloudservices/{cloudServiceName}")] [HttpPut] public async Task<HttpResponseMessage> PutCloudServiceAsync(string subscriptionId, string cloudServiceName) { var cloudServiceFromRequest = await this.Request.Content.ReadAsAsync<CloudService>(); return this.Request.CreateResponse(HttpStatusCode.Created); } [Route("~/{subscriptionId}/cloudservices/{cloudServiceName}/resources/{resourceNamespace}/clusters/{dnsName}")] [HttpPut] public async Task<HttpResponseMessage> CreateCluster(string subscriptionId, string cloudServiceName, string resourceNamespace, string dnsName) { var requestMessage = this.Request; var rdfeResource = await requestMessage.Content.ReadAsAsync<RDFEResource>(); XmlNode node = rdfeResource.IntrinsicSettings[0]; MemoryStream stm = new MemoryStream(); StreamWriter stw = new StreamWriter(stm); stw.Write(node.OuterXml); stw.Flush(); stm.Position = 0; DataContractSerializer ser = new DataContractSerializer(typeof(ClusterCreateParameters)); ClusterCreateParameters clusterCreateParams = (ClusterCreateParameters)ser.ReadObject(stm); // Spark cluster creation in introduced after schema version 3.0 if (clusterCreateParams.Components.Any(c => c.GetType() == typeof(SparkComponent))) { if (!requestMessage.Headers.GetValues("SchemaVersion").Any(v => v.Equals("3.0"))) { throw new NotSupportedException(ClustersTestConstants.NotSupportedBySubscriptionException); } } var testCluster = new Cluster { ClusterRoleCollection = clusterCreateParams.ClusterRoleCollection, CreatedTime = DateTime.UtcNow, Error = null, FullyQualifiedDnsName = clusterCreateParams.DnsName, State = ClusterState.Running, UpdatedTime = DateTime.UtcNow, DnsName = clusterCreateParams.DnsName, Components = clusterCreateParams.Components, ExtensionData = clusterCreateParams.ExtensionData, Location = clusterCreateParams.Location, Version = ClusterVersionUtils.TryGetVersionNumber(clusterCreateParams.Version), VirtualNetworkConfiguration = clusterCreateParams.VirtualNetworkConfiguration }; List<Cluster> clusters; bool subExists = _clustersAvailable.TryGetValue(subscriptionId, out clusters); if (subExists) { clusters.Add(testCluster); _clustersAvailable[subscriptionId] = clusters; } else { _clustersAvailable.Add( new KeyValuePair<string, List<Cluster>>(subscriptionId, new List<Cluster> { testCluster })); } return this.Request.CreateResponse(HttpStatusCode.Created); } [Route("~/{subscriptionId}/cloudservices/{cloudServiceName}/resources/{resourceNamespace}/~/clusters/{dnsName}/roles")] [HttpPost] public async Task<PassthroughResponse> UpdateRole(string subscriptionId, string cloudServiceName, string resourceNamespace, string dnsName) { var requestMessage = this.Request; if (requestMessage.Headers.GetValues("SchemaVersion").Any(v => v.Equals("1.0"))) { throw new NotSupportedException(ClustersTestConstants.NotSupportedBySubscriptionException); } ClusterRoleCollection roleCollection = await requestMessage.Content.ReadAsAsync<ClusterRoleCollection>(); var actionValue = requestMessage.RequestUri.ParseQueryString()["action"]; PassthroughResponse response; //If no action is specified then RP defaults to Enable Rdp action. if (string.IsNullOrEmpty(actionValue)) { this.EnableRdp(roleCollection, subscriptionId, cloudServiceName, dnsName); } switch (actionValue.ToLowerInvariant()) { case "resize": response = this.ResizeCluster(roleCollection, subscriptionId, cloudServiceName, dnsName); break; case "enablerdp": response = this.EnableDisableRdp(roleCollection, subscriptionId, cloudServiceName, dnsName); break; default: throw new NotSupportedException(string.Format(ClustersTestConstants.NotSupportedAction, actionValue)); } return response; } private PassthroughResponse EnableDisableRdp(ClusterRoleCollection roleCollection, string subscriptionId, string cloudServiceName, string dnsName) { Assert.IsNotNull(roleCollection); Assert.IsTrue(roleCollection.Count > 0); var firstRole = roleCollection.FirstOrDefault(); Assert.IsNotNull(firstRole); Assert.IsNotNull(firstRole.RemoteDesktopSettings); if (firstRole.RemoteDesktopSettings.IsEnabled) { return this.EnableRdp(roleCollection, subscriptionId, cloudServiceName, dnsName); } else { return this.DisableRdp(roleCollection, subscriptionId, cloudServiceName, dnsName); } } private PassthroughResponse ResizeCluster(ClusterRoleCollection roleCollection, string subscriptionId, string cloudServiceName, string dnsName) { var workerNode = roleCollection.SingleOrDefault(role => role.FriendlyName.Equals("WorkerNodeRole")); if (workerNode == null) { throw new NullReferenceException(ClustersTestConstants.NoDataNodeException); } int instanceCount = workerNode.InstanceCount; var cluster = this.GetCluster(dnsName, cloudServiceName, subscriptionId); if (cluster == null) { throw new ArgumentNullException(string.Format(ClustersTestConstants.ClusterDoesNotExistException, dnsName, subscriptionId)); } var clusterWorkerRole = cluster.ClusterRoleCollection.SingleOrDefault(role => role.FriendlyName.Equals("WorkerNodeRole")); if (clusterWorkerRole == null) { throw new NullReferenceException(ClustersTestConstants.NoDataNodeException); } clusterWorkerRole.InstanceCount = instanceCount; return new PassthroughResponse { Data = new Contracts.May2014.Operation { OperationId = Guid.NewGuid().ToString(), Status = Contracts.May2014.OperationStatus.InProgress, } }; } private PassthroughResponse EnableRdp(ClusterRoleCollection roleCollection, string subscriptionId, string cloudServiceName, string dnsName) { Assert.IsNotNull(roleCollection, "Role collection is null"); Assert.IsTrue(roleCollection.Count > 0, "There are no roles in the role collection"); var cluster = this.GetCluster(dnsName, cloudServiceName, subscriptionId); if (cluster == null) { throw new ArgumentNullException(string.Format(ClustersTestConstants.ClusterDoesNotExistException, dnsName, subscriptionId)); } ClusterRole previousRole = null; foreach (var role in roleCollection) { Assert.IsNotNull(role,"The role is null"); Assert.IsTrue(role.RemoteDesktopSettings.IsEnabled); if (previousRole != null) { Assert.IsTrue( previousRole.RemoteDesktopSettings.AuthenticationCredential.Username == role.RemoteDesktopSettings.AuthenticationCredential.Username, "rdpUsername between roles doesn't match"); Assert.IsTrue( previousRole.RemoteDesktopSettings.AuthenticationCredential.Password == role.RemoteDesktopSettings.AuthenticationCredential.Password, "rdpPassword between roles doesn't match"); Assert.IsTrue(previousRole.RemoteDesktopSettings.RemoteAccessExpiry == role.RemoteDesktopSettings.RemoteAccessExpiry, "RemoteAccessExpory between roles doesn't match"); } else { Assert.IsNotNull(role.RemoteDesktopSettings.AuthenticationCredential.Username, "rdpUsername is null"); Assert.IsNotNull(role.RemoteDesktopSettings.AuthenticationCredential.Password, "rdpPassword is null"); Assert.IsNotNull(role.RemoteDesktopSettings.RemoteAccessExpiry, "RemoteAccessExpory is numm"); } previousRole = role; } cluster.ClusterRoleCollection = roleCollection; return new PassthroughResponse { Data = new Contracts.May2014.Operation { OperationId = Guid.NewGuid().ToString(), Status = Contracts.May2014.OperationStatus.InProgress, } }; } private PassthroughResponse DisableRdp(ClusterRoleCollection roleCollection, string subscriptionId, string cloudServiceName, string dnsName) { var cluster = this.GetCluster(dnsName, cloudServiceName, subscriptionId); if (cluster == null) { throw new ArgumentNullException(string.Format(ClustersTestConstants.ClusterDoesNotExistException, dnsName, subscriptionId)); } cluster.ClusterRoleCollection = roleCollection; return new PassthroughResponse { Data = new Contracts.May2014.Operation { OperationId = Guid.NewGuid().ToString(), Status = Contracts.May2014.OperationStatus.InProgress, } }; } private Cluster GetCluster(string dnsName, string cloudserviceName, string subscriptionId) { List<Cluster> clusters; bool subExists = _clustersAvailable.TryGetValue(subscriptionId, out clusters); if (!subExists) { return null; } var cluster = clusters.SingleOrDefault(c => c.DnsName.Equals(dnsName) && cloudserviceName.Contains(c.Location.Replace(" ", "-"))); if (cluster == null) { return null; } return cluster; } private OutputItemList GetOutputItems(Cluster cluster) { var oi = new OutputItemList(); var version = new OutputItem(); version.Key = "Version"; version.Value = cluster.Version; oi.Add(version); var components = new OutputItem(); components.Key = "ClusterComponents"; components.Value = this.GetClusterComponents(cluster); oi.Add(components); return oi; } private string GetClusterComponents(Cluster cluster) { return string.Join(",", cluster.Components.Select(c => c.GetType().Name)); } } }
using System; using System.Collections.ObjectModel; using System.Windows.Input; using Afnor.Silverlight.Toolkit.ViewServices; using EspaceClient.BackOffice.Silverlight.Business.Depots; using EspaceClient.BackOffice.Silverlight.Business.Interfaces; using EspaceClient.BackOffice.Silverlight.Business.Loader; using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity; using EspaceClient.BackOffice.Silverlight.ViewModels.Helper.Referentiels.OrganismeCertification; using EspaceClient.BackOffice.Silverlight.ViewModels.Messages; using EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.References.OrganismeCertification; using EspaceClient.FrontOffice.Domaine; using nRoute.Components; using nRoute.Components.Composition; using nRoute.Components.Messaging; using OGDC.Silverlight.Toolkit.DataGrid.Manager; using OGDC.Silverlight.Toolkit.Services.Services; namespace EspaceClient.BackOffice.Silverlight.ViewModels.References.OrganismeCertification.Tabs { /// <summary> /// ViewModel de la vue <see cref="SearchView"/> /// </summary> public class SearchViewModel : TabBase { private readonly IResourceWrapper _resourceWrapper; private readonly IDepotOrganismeCertification _organismeCertification; private readonly IMessenging _messengingService; private readonly IApplicationContext _applicationContext; private readonly ILoaderReferentiel _referentiel; private readonly IDepotTraductionOM _depotTraductionOM; private readonly INavigatableChildWindowService _childWindowService; private readonly INotificationViewService _notificationViewService; private readonly IDepotSelligent _selligent; private readonly IModelBuilderDetails _builderDetails; protected ChannelObserver<UpdateListMessage> ObserverUpdateListMessage { get; private set; } private ObservableCollection<OrganismeCertificationDto> _searchResult; private DataGridColumnManager _manager; private ICommand _searchCommand; private ICommand _doubleClickCommand; [ResolveConstructor] public SearchViewModel( IResourceWrapper resourceWrapper, IDepotOrganismeCertification organismeCertification, IMessenging messengingService, IApplicationContext applicationContext, ILoaderReferentiel referentiel, INotificationViewService notificationViewService, IDepotTraductionOM depotTraductionOM, INavigatableChildWindowService childWindowService, IDepotSelligent selligent, IModelBuilderDetails builderDetails) : base(applicationContext, messengingService) { _resourceWrapper = resourceWrapper; _organismeCertification = organismeCertification; _messengingService = messengingService; _applicationContext = applicationContext; _referentiel = referentiel; _notificationViewService = notificationViewService; _depotTraductionOM = depotTraductionOM; _childWindowService = childWindowService; _notificationViewService = notificationViewService; _selligent = selligent; _builderDetails = builderDetails; InitializeCommands(); InitializeUI(); InitializeMessenging(); //on execute la recherche quand on arrive sur la page OnSearch(); } public DataGridColumnManager DataGridManager { get { return _manager; } set { if (_manager != value) { _manager = value; NotifyPropertyChanged(() => DataGridManager); } } } public ObservableCollection<OrganismeCertificationDto> SearchResult { get { return _searchResult; } set { if (_searchResult != value) { _searchResult = value; NotifyPropertyChanged(() => SearchResult); } } } #region Commands /// <summary> /// Command de recherche des utilisateurs /// </summary> public ICommand SearchCommand { get { return _searchCommand; } } public ICommand DoubleClickCommand { get { return _doubleClickCommand; } } #endregion private void InitializeMessenging() { ObserverUpdateListMessage = _messengingService.CreateObserver<UpdateListMessage>(msg => { if (msg.Type == TypeUpdateList.RechercheOrganismeCertification) { if (SearchCommand.CanExecute(this)) SearchCommand.Execute(this); } }); ObserverUpdateListMessage.Subscribe(ThreadOption.UIThread); } private void DisposeMessenging() { ObserverUpdateListMessage.Unsubscribe(); } private void InitializeCommands() { _searchCommand = new ActionCommand(OnSearch); _doubleClickCommand = new ActionCommand<OrganismeCertificationDto>(OnDoubleClickCommand); } private void InitializeUI() { SearchResult = new ObservableCollection<OrganismeCertificationDto>(); DataGridManager = new DataGridColumnManager(); } private void OnSearch() { _organismeCertification.GetAllOrganismeCertification(r => { SearchResult.Clear(); foreach (var u in r) SearchResult.Add(u); }, error => _messengingService.Publish(new ErrorMessage(error))); } private void OnDoubleClickCommand(OrganismeCertificationDto selected) { if (selected != null) { OrganismeCertificationHelper.AddOrganismeCertificationTab( selected, _organismeCertification, _depotTraductionOM, _messengingService, _applicationContext, _childWindowService, _notificationViewService, _selligent, _resourceWrapper, _builderDetails); } } public override void OnRefreshTab<EntityType>(long id, Action<EntityType> callback) { throw new NotImplementedException(); } protected override void OnRefreshTabCompleted(Action callback) { throw new NotImplementedException(); } } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_15_1_3_3 : EcmaTest { [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0Xdc000XdfffThrowUrierror() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A1.1_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0Xdc000XdfffThrowUrierror2() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A1.1_T2.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0Xd8000XdbffAndStringLengthK1ThrowUrierror() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A1.2_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0Xd8000XdbffAndStringLengthK1ThrowUrierror2() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A1.2_T2.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0Xd8000XdbffAndStringCharatK1NotIn0Xdc000XdfffThrowUrierror() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A1.3_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0X00000X007FUrireservedUriunescapedReturn1Octet000000000Zzzzzzz0Zzzzzzz() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A2.1_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0X00800X07FfReturn2Octets00000YyyYyzzzzzz110Yyyyy10Zzzzzz() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A2.2_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0X08000Xd7FfReturn3OctetsXxxxyyyyYyzzzzzz1110Xxxx10Yyyyyy10Zzzzzz() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A2.3_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0Xd8000XdbffAndStringCharatK1In0Xdc000XdfffReturn4Octets000WwwxxXxxxyyyyYyzzzzzz11110Www10Xxxxxx10Yyyyyy10Zzzzzz() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A2.4_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0Xd8000XdbffAndStringCharatK1In0Xdc000XdfffReturn4Octets000WwwxxXxxxyyyyYyzzzzzz11110Www10Xxxxxx10Yyyyyy10Zzzzzz2() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A2.4_T2.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void IfStringCharatKIn0Xe0000XffffReturn3OctetsXxxxyyyyYyzzzzzz1110Xxxx10Yyyyyy10Zzzzzz() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A2.5_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void UnescapedurisetContainingOneInstanceOfEachCharacterValidInUrireserved() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A3.1_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void UnescapedurisetContainingOneInstanceOfEachCharacterValidInUriunescaped() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A3.2_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void UnescapedurisetContainingOneInstanceOfEachCharacterValidInUriunescaped2() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A3.2_T2.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void UnescapedurisetContainingOneInstanceOfEachCharacterValidInUriunescaped3() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A3.2_T3.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void UnescapedurisetContaining() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A3.3_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void UriTests() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A4_T1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void UriTests2() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A4_T2.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void UriTests3() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A4_T3.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void UriTests4() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A4_T4.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void TheLengthPropertyOfEncodeuriHasTheAttributeDontenum() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A5.1.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void TheLengthPropertyOfEncodeuriHasTheAttributeDontdelete() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A5.2.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void TheLengthPropertyOfEncodeuriHasTheAttributeReadonly() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A5.3.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void TheLengthPropertyOfEncodeuriIs1() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A5.4.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void TheEncodeuriPropertyHasTheAttributeDontenum() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A5.5.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void TheEncodeuriPropertyHasNotPrototypeProperty() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A5.6.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void TheEncodeuriPropertyCanTBeUsedAsConstructor() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A5.7.js", false); } [Fact] [Trait("Category", "15.1.3.3")] public void OperatorUseTostring() { RunTest(@"TestCases/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A6_T1.js", false); } } }
using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.TeamFoundation.DistributedTask.Pipelines; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.Services.Agent.Worker.Build { public sealed class TfsVCSourceProvider : SourceProvider, ISourceProvider { private bool _undoShelvesetPendingChanges = false; public override string RepositoryType => TeamFoundation.DistributedTask.Pipelines.RepositoryTypes.Tfvc; public async Task GetSourceAsync( IExecutionContext executionContext, ServiceEndpoint endpoint, CancellationToken cancellationToken) { Trace.Entering(); // Validate args. ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNull(endpoint, nameof(endpoint)); #if OS_WINDOWS // Validate .NET Framework 4.6 or higher is installed. if (!NetFrameworkUtil.Test(new Version(4, 6), Trace)) { throw new Exception(StringUtil.Loc("MinimumNetFramework46")); } #endif // Create the tf command manager. var tf = HostContext.CreateService<ITfsVCCommandManager>(); tf.CancellationToken = cancellationToken; tf.Endpoint = endpoint; tf.ExecutionContext = executionContext; // Setup proxy. var agentProxy = HostContext.GetService<IVstsAgentWebProxy>(); if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.WebProxy.IsBypassed(endpoint.Url)) { executionContext.Debug($"Configure '{tf.FilePath}' to work through proxy server '{executionContext.Variables.Agent_ProxyUrl}'."); tf.SetupProxy(executionContext.Variables.Agent_ProxyUrl, executionContext.Variables.Agent_ProxyUsername, executionContext.Variables.Agent_ProxyPassword); } // Setup client certificate. var agentCertManager = HostContext.GetService<IAgentCertificateManager>(); if (agentCertManager.SkipServerCertificateValidation) { #if OS_WINDOWS executionContext.Debug("TF.exe does not support ignore SSL certificate validation error."); #else executionContext.Debug("TF does not support ignore SSL certificate validation error."); #endif } var configUrl = new Uri(HostContext.GetService<IConfigurationStore>().GetSettings().ServerUrl); if (!string.IsNullOrEmpty(agentCertManager.ClientCertificateFile) && Uri.Compare(endpoint.Url, configUrl, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0) { executionContext.Debug($"Configure '{tf.FilePath}' to work with client cert '{agentCertManager.ClientCertificateFile}'."); tf.SetupClientCertificate(agentCertManager.ClientCertificateFile, agentCertManager.ClientCertificatePrivateKeyFile, agentCertManager.ClientCertificateArchiveFile, agentCertManager.ClientCertificatePassword); } // Add TF to the PATH. string tfPath = tf.FilePath; ArgUtil.File(tfPath, nameof(tfPath)); executionContext.Output(StringUtil.Loc("Prepending0WithDirectoryContaining1", Constants.PathVariable, Path.GetFileName(tfPath))); PathUtil.PrependPath(Path.GetDirectoryName(tfPath)); executionContext.Debug($"{Constants.PathVariable}: '{Environment.GetEnvironmentVariable(Constants.PathVariable)}'"); #if OS_WINDOWS // Set TFVC_BUILDAGENT_POLICYPATH string policyDllPath = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.ServerOM), "Microsoft.TeamFoundation.VersionControl.Controls.dll"); ArgUtil.File(policyDllPath, nameof(policyDllPath)); const string policyPathEnvKey = "TFVC_BUILDAGENT_POLICYPATH"; executionContext.Output(StringUtil.Loc("SetEnvVar", policyPathEnvKey)); Environment.SetEnvironmentVariable(policyPathEnvKey, policyDllPath); #endif // Check if the administrator accepted the license terms of the TEE EULA when configuring the agent. AgentSettings settings = HostContext.GetService<IConfigurationStore>().GetSettings(); if (tf.Features.HasFlag(TfsVCFeatures.Eula) && settings.AcceptTeeEula) { // Check if the "tf eula -accept" command needs to be run for the current user. bool skipEula = false; try { skipEula = tf.TestEulaAccepted(); } catch (Exception ex) { executionContext.Debug("Unexpected exception while testing whether the TEE EULA has been accepted for the current user."); executionContext.Debug(ex.ToString()); } if (!skipEula) { // Run the command "tf eula -accept". try { await tf.EulaAsync(); } catch (Exception ex) { executionContext.Debug(ex.ToString()); executionContext.Warning(ex.Message); } } } // Get the workspaces. executionContext.Output(StringUtil.Loc("QueryingWorkspaceInfo")); ITfsVCWorkspace[] tfWorkspaces = await tf.WorkspacesAsync(); // Determine the workspace name. string buildDirectory = executionContext.Variables.Get(Constants.Variables.Agent.BuildDirectory); ArgUtil.NotNullOrEmpty(buildDirectory, nameof(buildDirectory)); string workspaceName = $"ws_{Path.GetFileName(buildDirectory)}_{settings.AgentId}"; executionContext.Variables.Set(Constants.Variables.Build.RepoTfvcWorkspace, workspaceName); // Get the definition mappings. DefinitionWorkspaceMapping[] definitionMappings = JsonConvert.DeserializeObject<DefinitionWorkspaceMappings>(endpoint.Data[EndpointData.TfvcWorkspaceMapping])?.Mappings; // Determine the sources directory. string sourcesDirectory = GetEndpointData(endpoint, Constants.EndpointData.SourcesDirectory); ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory)); // Attempt to re-use an existing workspace if the command manager supports scorch // or if clean is not specified. ITfsVCWorkspace existingTFWorkspace = null; bool clean = endpoint.Data.ContainsKey(EndpointData.Clean) && StringUtil.ConvertToBoolean(endpoint.Data[EndpointData.Clean], defaultValue: false); if (tf.Features.HasFlag(TfsVCFeatures.Scorch) || !clean) { existingTFWorkspace = WorkspaceUtil.MatchExactWorkspace( executionContext: executionContext, tfWorkspaces: tfWorkspaces, name: workspaceName, definitionMappings: definitionMappings, sourcesDirectory: sourcesDirectory); if (existingTFWorkspace != null) { if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot)) { // Undo pending changes. ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: sourcesDirectory); if (tfStatus?.HasPendingChanges ?? false) { await tf.UndoAsync(localPath: sourcesDirectory); // Cleanup remaining files/directories from pend adds. tfStatus.AllAdds .OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted. .ToList() .ForEach(x => { executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem)); IOUtil.Delete(x.LocalItem, cancellationToken); }); } } else { // Perform "undo" for each map. foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0]) { if (definitionMapping.MappingType == DefinitionMappingType.Map) { // Check the status. string localPath = definitionMapping.GetRootedLocalPath(sourcesDirectory); ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: localPath); if (tfStatus?.HasPendingChanges ?? false) { // Undo. await tf.UndoAsync(localPath: localPath); // Cleanup remaining files/directories from pend adds. tfStatus.AllAdds .OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted. .ToList() .ForEach(x => { executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem)); IOUtil.Delete(x.LocalItem, cancellationToken); }); } } } } // Scorch. if (clean) { // Try to scorch. try { await tf.ScorchAsync(); } catch (ProcessExitCodeException ex) { // Scorch failed. // Warn, drop the folder, and re-clone. executionContext.Warning(ex.Message); existingTFWorkspace = null; } } } } // Create a new workspace. if (existingTFWorkspace == null) { // Remove any conflicting workspaces. await RemoveConflictingWorkspacesAsync( tf: tf, tfWorkspaces: tfWorkspaces, name: workspaceName, directory: sourcesDirectory); // Remove any conflicting workspace from a different computer. // This is primarily a hosted scenario where a registered hosted // agent can land on a different computer each time. tfWorkspaces = await tf.WorkspacesAsync(matchWorkspaceNameOnAnyComputer: true); foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0]) { await tf.WorkspaceDeleteAsync(tfWorkspace); } // Recreate the sources directory. executionContext.Debug($"Deleting: '{sourcesDirectory}'."); IOUtil.DeleteDirectory(sourcesDirectory, cancellationToken); Directory.CreateDirectory(sourcesDirectory); // Create the workspace. await tf.WorkspaceNewAsync(); // Remove the default mapping. if (tf.Features.HasFlag(TfsVCFeatures.DefaultWorkfoldMap)) { await tf.WorkfoldUnmapAsync("$/"); } // Sort the definition mappings. definitionMappings = (definitionMappings ?? new DefinitionWorkspaceMapping[0]) .OrderBy(x => x.NormalizedServerPath?.Length ?? 0) // By server path length. .ToArray() ?? new DefinitionWorkspaceMapping[0]; // Add the definition mappings to the workspace. foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings) { switch (definitionMapping.MappingType) { case DefinitionMappingType.Cloak: // Add the cloak. await tf.WorkfoldCloakAsync(serverPath: definitionMapping.ServerPath); break; case DefinitionMappingType.Map: // Add the mapping. await tf.WorkfoldMapAsync( serverPath: definitionMapping.ServerPath, localPath: definitionMapping.GetRootedLocalPath(sourcesDirectory)); break; default: throw new NotSupportedException(); } } } if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot)) { // Get. await tf.GetAsync(localPath: sourcesDirectory); } else { // Perform "get" for each map. foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0]) { if (definitionMapping.MappingType == DefinitionMappingType.Map) { await tf.GetAsync(localPath: definitionMapping.GetRootedLocalPath(sourcesDirectory)); } } } // Steps for shelveset/gated. string shelvesetName = GetEndpointData(endpoint, Constants.EndpointData.SourceTfvcShelveset); if (!string.IsNullOrEmpty(shelvesetName)) { // Steps for gated. ITfsVCShelveset tfShelveset = null; string gatedShelvesetName = GetEndpointData(endpoint, Constants.EndpointData.GatedShelvesetName); if (!string.IsNullOrEmpty(gatedShelvesetName)) { // Clean the last-saved-checkin-metadata for existing workspaces. // // A better long term fix is to add a switch to "tf unshelve" that completely overwrites // the last-saved-checkin-metadata, instead of merging associated work items. // // The targeted workaround for now is to create a trivial change and "tf shelve /move", // which will delete the last-saved-checkin-metadata. if (existingTFWorkspace != null) { executionContext.Output("Cleaning last saved checkin metadata."); // Find a local mapped directory. string firstLocalDirectory = (definitionMappings ?? new DefinitionWorkspaceMapping[0]) .Where(x => x.MappingType == DefinitionMappingType.Map) .Select(x => x.GetRootedLocalPath(sourcesDirectory)) .FirstOrDefault(x => Directory.Exists(x)); if (firstLocalDirectory == null) { executionContext.Warning("No mapped folder found. Unable to clean last-saved-checkin-metadata."); } else { // Create a trival change and "tf shelve /move" to clear the // last-saved-checkin-metadata. string cleanName = "__tf_clean_wksp_metadata"; string tempCleanFile = Path.Combine(firstLocalDirectory, cleanName); try { File.WriteAllText(path: tempCleanFile, contents: "clean last-saved-checkin-metadata", encoding: Encoding.UTF8); await tf.AddAsync(tempCleanFile); await tf.ShelveAsync(shelveset: cleanName, commentFile: tempCleanFile, move: true); } catch (Exception ex) { executionContext.Warning($"Unable to clean last-saved-checkin-metadata. {ex.Message}"); try { await tf.UndoAsync(tempCleanFile); } catch (Exception ex2) { executionContext.Warning($"Unable to undo '{tempCleanFile}'. {ex2.Message}"); } } finally { IOUtil.DeleteFile(tempCleanFile); } } } // Get the shelveset metadata. tfShelveset = await tf.ShelvesetsAsync(shelveset: shelvesetName); // The above command throws if the shelveset is not found, // so the following assertion should never fail. ArgUtil.NotNull(tfShelveset, nameof(tfShelveset)); } // Unshelve. await tf.UnshelveAsync(shelveset: shelvesetName); // Ensure we undo pending changes for shelveset build at the end. _undoShelvesetPendingChanges = true; if (!string.IsNullOrEmpty(gatedShelvesetName)) { // Create the comment file for reshelve. StringBuilder comment = new StringBuilder(tfShelveset.Comment ?? string.Empty); string runCi = GetEndpointData(endpoint, Constants.EndpointData.GatedRunCI); bool gatedRunCi = StringUtil.ConvertToBoolean(runCi, true); if (!gatedRunCi) { if (comment.Length > 0) { comment.AppendLine(); } comment.Append(Constants.Build.NoCICheckInComment); } string commentFile = null; try { commentFile = Path.GetTempFileName(); File.WriteAllText(path: commentFile, contents: comment.ToString(), encoding: Encoding.UTF8); // Reshelve. await tf.ShelveAsync(shelveset: gatedShelvesetName, commentFile: commentFile, move: false); } finally { // Cleanup the comment file. if (File.Exists(commentFile)) { File.Delete(commentFile); } } } } // Cleanup proxy settings. if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.WebProxy.IsBypassed(endpoint.Url)) { executionContext.Debug($"Remove proxy setting for '{tf.FilePath}' to work through proxy server '{executionContext.Variables.Agent_ProxyUrl}'."); tf.CleanupProxySetting(); } } public async Task PostJobCleanupAsync(IExecutionContext executionContext, ServiceEndpoint endpoint) { if (_undoShelvesetPendingChanges) { string shelvesetName = GetEndpointData(endpoint, Constants.EndpointData.SourceTfvcShelveset); executionContext.Debug($"Undo pending changes left by shelveset '{shelvesetName}'."); // Create the tf command manager. var tf = HostContext.CreateService<ITfsVCCommandManager>(); tf.CancellationToken = executionContext.CancellationToken; tf.Endpoint = endpoint; tf.ExecutionContext = executionContext; // Get the definition mappings. DefinitionWorkspaceMapping[] definitionMappings = JsonConvert.DeserializeObject<DefinitionWorkspaceMappings>(endpoint.Data[EndpointData.TfvcWorkspaceMapping])?.Mappings; // Determine the sources directory. string sourcesDirectory = GetEndpointData(endpoint, Constants.EndpointData.SourcesDirectory); ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory)); try { if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot)) { // Undo pending changes. ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: sourcesDirectory); if (tfStatus?.HasPendingChanges ?? false) { await tf.UndoAsync(localPath: sourcesDirectory); // Cleanup remaining files/directories from pend adds. tfStatus.AllAdds .OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted. .ToList() .ForEach(x => { executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem)); IOUtil.Delete(x.LocalItem, executionContext.CancellationToken); }); } } else { // Perform "undo" for each map. foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0]) { if (definitionMapping.MappingType == DefinitionMappingType.Map) { // Check the status. string localPath = definitionMapping.GetRootedLocalPath(sourcesDirectory); ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: localPath); if (tfStatus?.HasPendingChanges ?? false) { // Undo. await tf.UndoAsync(localPath: localPath); // Cleanup remaining files/directories from pend adds. tfStatus.AllAdds .OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted. .ToList() .ForEach(x => { executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem)); IOUtil.Delete(x.LocalItem, executionContext.CancellationToken); }); } } } } } catch (Exception ex) { // We can't undo pending changes, log a warning and continue. executionContext.Debug(ex.ToString()); executionContext.Warning(ex.Message); } } } public override string GetLocalPath(IExecutionContext executionContext, RepositoryResource repository, string path) { ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables)); ArgUtil.NotNull(repository, nameof(repository)); ArgUtil.NotNull(repository.Endpoint, nameof(repository.Endpoint)); path = path ?? string.Empty; if (path.StartsWith("$/") || path.StartsWith(@"$\")) { // Create the tf command manager. var tf = HostContext.CreateService<ITfsVCCommandManager>(); tf.CancellationToken = CancellationToken.None; tf.Repository = repository; tf.Endpoint = executionContext.Endpoints.Single(x => (repository.Endpoint.Id != Guid.Empty && x.Id == repository.Endpoint.Id) || (repository.Endpoint.Id == Guid.Empty && string.Equals(x.Name, repository.Endpoint.Name, StringComparison.OrdinalIgnoreCase))); tf.ExecutionContext = executionContext; // Attempt to resolve the path. string localPath = tf.ResolvePath(serverPath: path); if (!string.IsNullOrEmpty(localPath)) { return localPath; } } // Return the original path. return path; } public override void SetVariablesInEndpoint(IExecutionContext executionContext, ServiceEndpoint endpoint) { base.SetVariablesInEndpoint(executionContext, endpoint); endpoint.Data.Add(Constants.EndpointData.SourceTfvcShelveset, executionContext.Variables.Get(Constants.Variables.Build.SourceTfvcShelveset)); endpoint.Data.Add(Constants.EndpointData.GatedShelvesetName, executionContext.Variables.Get(Constants.Variables.Build.GatedShelvesetName)); endpoint.Data.Add(Constants.EndpointData.GatedRunCI, executionContext.Variables.Get(Constants.Variables.Build.GatedRunCI)); } private async Task RemoveConflictingWorkspacesAsync(ITfsVCCommandManager tf, ITfsVCWorkspace[] tfWorkspaces, string name, string directory) { // Validate the args. ArgUtil.NotNullOrEmpty(name, nameof(name)); ArgUtil.NotNullOrEmpty(directory, nameof(directory)); // Fixup the directory. directory = directory.TrimEnd('/', '\\'); ArgUtil.NotNullOrEmpty(directory, nameof(directory)); string directorySlash = $"{directory}{Path.DirectorySeparatorChar}"; foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0]) { // Attempt to match the workspace by name. if (string.Equals(tfWorkspace.Name, name, StringComparison.OrdinalIgnoreCase)) { // Try deleting the workspace from the server. if (!(await tf.TryWorkspaceDeleteAsync(tfWorkspace))) { // Otherwise fallback to deleting the workspace from the local computer. await tf.WorkspacesRemoveAsync(tfWorkspace); } // Continue iterating over the rest of the workspaces. continue; } // Attempt to match the workspace by local path. foreach (ITfsVCMapping tfMapping in tfWorkspace.Mappings ?? new ITfsVCMapping[0]) { // Skip cloaks. if (tfMapping.Cloak) { continue; } if (string.Equals(tfMapping.LocalPath, directory, StringComparison.CurrentCultureIgnoreCase) || (tfMapping.LocalPath ?? string.Empty).StartsWith(directorySlash, StringComparison.CurrentCultureIgnoreCase)) { // Try deleting the workspace from the server. if (!(await tf.TryWorkspaceDeleteAsync(tfWorkspace))) { // Otherwise fallback to deleting the workspace from the local computer. await tf.WorkspacesRemoveAsync(tfWorkspace); } // Break out of this nested for loop only. // Continue iterating over the rest of the workspaces. break; } } } } public static class WorkspaceUtil { public static ITfsVCWorkspace MatchExactWorkspace( IExecutionContext executionContext, ITfsVCWorkspace[] tfWorkspaces, string name, DefinitionWorkspaceMapping[] definitionMappings, string sourcesDirectory) { ArgUtil.NotNullOrEmpty(name, nameof(name)); ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory)); // Short-circuit early if the sources directory is empty. // // Consider the sources directory to be empty if it only contains a .tf directory exists. This can // indicate the workspace is in a corrupted state and the tf commands (e.g. status) will not return // reliable information. An easy way to reproduce this is to delete the workspace directory, then // run "tf status" on that workspace. The .tf directory will be recreated but the contents will be // in a corrupted state. if (!Directory.Exists(sourcesDirectory) || !Directory.EnumerateFileSystemEntries(sourcesDirectory).Any(x => !x.EndsWith($"{Path.DirectorySeparatorChar}.tf"))) { executionContext.Debug("Sources directory does not exist or is empty."); return null; } string machineName = Environment.MachineName; executionContext.Debug($"Attempting to find a workspace: '{name}'"); foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0]) { // Compare the workspace name. if (!string.Equals(tfWorkspace.Name, name, StringComparison.Ordinal)) { executionContext.Debug($"Skipping workspace: '{tfWorkspace.Name}'"); continue; } executionContext.Debug($"Candidate workspace: '{tfWorkspace.Name}'"); // Compare the machine name. if (!string.Equals(tfWorkspace.Computer, machineName, StringComparison.Ordinal)) { executionContext.Debug($"Expected computer name: '{machineName}'. Actual: '{tfWorkspace.Computer}'"); continue; } // Compare the number of mappings. if ((tfWorkspace.Mappings?.Length ?? 0) != (definitionMappings?.Length ?? 0)) { executionContext.Debug($"Expected number of mappings: '{definitionMappings?.Length ?? 0}'. Actual: '{tfWorkspace.Mappings?.Length ?? 0}'"); continue; } // Sort the definition mappings. List<DefinitionWorkspaceMapping> sortedDefinitionMappings = (definitionMappings ?? new DefinitionWorkspaceMapping[0]) .OrderBy(x => x.MappingType != DefinitionMappingType.Cloak) // Cloaks first .ThenBy(x => !x.Recursive) // Then recursive maps .ThenBy(x => x.NormalizedServerPath) // Then sort by the normalized server path .ToList(); for (int i = 0; i < sortedDefinitionMappings.Count; i++) { DefinitionWorkspaceMapping mapping = sortedDefinitionMappings[i]; executionContext.Debug($"Definition mapping[{i}]: cloak '{mapping.MappingType == DefinitionMappingType.Cloak}', recursive '{mapping.Recursive}', server path '{mapping.NormalizedServerPath}', local path '{mapping.GetRootedLocalPath(sourcesDirectory)}'"); } // Sort the TF mappings. List<ITfsVCMapping> sortedTFMappings = (tfWorkspace.Mappings ?? new ITfsVCMapping[0]) .OrderBy(x => !x.Cloak) // Cloaks first .ThenBy(x => !x.Recursive) // Then recursive maps .ThenBy(x => x.ServerPath) // Then sort by server path .ToList(); for (int i = 0; i < sortedTFMappings.Count; i++) { ITfsVCMapping mapping = sortedTFMappings[i]; executionContext.Debug($"Found mapping[{i}]: cloak '{mapping.Cloak}', recursive '{mapping.Recursive}', server path '{mapping.ServerPath}', local path '{mapping.LocalPath}'"); } // Compare the mappings. bool allMatch = true; List<string> matchTrace = new List<string>(); for (int i = 0; i < sortedTFMappings.Count; i++) { ITfsVCMapping tfMapping = sortedTFMappings[i]; DefinitionWorkspaceMapping definitionMapping = sortedDefinitionMappings[i]; // Compare the cloak flag. bool expectedCloak = definitionMapping.MappingType == DefinitionMappingType.Cloak; if (tfMapping.Cloak != expectedCloak) { matchTrace.Add(StringUtil.Loc("ExpectedMappingCloak", i, expectedCloak, tfMapping.Cloak)); allMatch = false; break; } // Compare the recursive flag. if (!expectedCloak && tfMapping.Recursive != definitionMapping.Recursive) { matchTrace.Add(StringUtil.Loc("ExpectedMappingRecursive", i, definitionMapping.Recursive, tfMapping.Recursive)); allMatch = false; break; } // Compare the server path. Normalize the expected server path for a single-level map. string expectedServerPath = definitionMapping.NormalizedServerPath; if (!string.Equals(tfMapping.ServerPath, expectedServerPath, StringComparison.Ordinal)) { matchTrace.Add(StringUtil.Loc("ExpectedMappingServerPath", i, expectedServerPath, tfMapping.ServerPath)); allMatch = false; break; } // Compare the local path. if (!expectedCloak) { string expectedLocalPath = definitionMapping.GetRootedLocalPath(sourcesDirectory); if (!string.Equals(tfMapping.LocalPath, expectedLocalPath, StringComparison.Ordinal)) { matchTrace.Add(StringUtil.Loc("ExpectedMappingLocalPath", i, expectedLocalPath, tfMapping.LocalPath)); allMatch = false; break; } } } if (allMatch) { executionContext.Debug("Matching workspace found."); return tfWorkspace; } else { executionContext.Output(StringUtil.Loc("WorkspaceMappingNotMatched", tfWorkspace.Name)); foreach (var trace in matchTrace) { executionContext.Output(trace); } } } executionContext.Debug("Matching workspace not found."); return null; } } public sealed class DefinitionWorkspaceMappings { public DefinitionWorkspaceMapping[] Mappings { get; set; } } public sealed class DefinitionWorkspaceMapping { public string LocalPath { get; set; } public DefinitionMappingType MappingType { get; set; } /// <summary> /// Remove the trailing "/*" from the single-level mapping server path. /// If the ServerPath is "$/*", then the normalized path is returned /// as "$/" rather than "$". /// </summary> public string NormalizedServerPath { get { string path; if (!Recursive) { // Trim the last two characters (i.e. "/*") from the single-level // mapping server path. path = ServerPath.Substring(0, ServerPath.Length - 2); // Check if trimmed too much. This is important when comparing // against workspaces on disk. if (string.Equals(path, "$", StringComparison.Ordinal)) { path = "$/"; } } else { path = ServerPath ?? string.Empty; } return path; } } /// <summary> /// Returns true if the path does not end with "/*". /// </summary> public bool Recursive => !(ServerPath ?? string.Empty).EndsWith("/*"); public string ServerPath { get; set; } /// <summary> /// Gets the rooted local path and normalizes slashes. /// </summary> public string GetRootedLocalPath(string sourcesDirectory) { // TEE normalizes all slashes in a workspace mapping to match the OS. It is not // possible on OSX/Linux to have a workspace mapping with a backslash, even though // backslash is a legal file name character. string relativePath = (LocalPath ?? string.Empty) .Replace('/', Path.DirectorySeparatorChar) .Replace('\\', Path.DirectorySeparatorChar) .Trim(Path.DirectorySeparatorChar); return Path.Combine(sourcesDirectory, relativePath); } } public enum DefinitionMappingType { Cloak, Map, } } }
using Xunit; namespace SimpSim.NET.Tests { public class AssemblerValidSyntaxTests { private readonly Assembler _assembler; public AssemblerValidSyntaxTests() { _assembler = new Assembler(); } [Fact] public void ShouldAssembleEmptyInstructions() { Assert.Empty(_assembler.Assemble(null)); } [Fact] public void ShouldAssembleImmediateLoadInstructions() { for (int number = 0; number <= byte.MaxValue; number++) { byte b = (byte)number; Assert.Equal(new[] { new Instruction(0x20, b) }, _assembler.Assemble($"load R0,{b}")); Assert.Equal(new[] { new Instruction(0x21, b) }, _assembler.Assemble($"load R1,{b}")); Assert.Equal(new[] { new Instruction(0x22, b) }, _assembler.Assemble($"load R2,{b}")); Assert.Equal(new[] { new Instruction(0x23, b) }, _assembler.Assemble($"load R3,{b}")); Assert.Equal(new[] { new Instruction(0x24, b) }, _assembler.Assemble($"load R4,{b}")); Assert.Equal(new[] { new Instruction(0x25, b) }, _assembler.Assemble($"load R5,{b}")); Assert.Equal(new[] { new Instruction(0x26, b) }, _assembler.Assemble($"load R6,{b}")); Assert.Equal(new[] { new Instruction(0x27, b) }, _assembler.Assemble($"load R7,{b}")); Assert.Equal(new[] { new Instruction(0x28, b) }, _assembler.Assemble($"load R8,{b}")); Assert.Equal(new[] { new Instruction(0x29, b) }, _assembler.Assemble($"load R9,{b}")); Assert.Equal(new[] { new Instruction(0x2A, b) }, _assembler.Assemble($"load RA,{b}")); Assert.Equal(new[] { new Instruction(0x2B, b) }, _assembler.Assemble($"load RB,{b}")); Assert.Equal(new[] { new Instruction(0x2C, b) }, _assembler.Assemble($"load RC,{b}")); Assert.Equal(new[] { new Instruction(0x2D, b) }, _assembler.Assemble($"load RD,{b}")); Assert.Equal(new[] { new Instruction(0x2E, b) }, _assembler.Assemble($"load RE,{b}")); Assert.Equal(new[] { new Instruction(0x2F, b) }, _assembler.Assemble($"load RF,{b}")); } } [Fact] public void ShouldAssembleDirectLoadInstructions() { for (int number = 0; number <= byte.MaxValue; number++) { byte b = (byte)number; Assert.Equal(new[] { new Instruction(0x10, b) }, _assembler.Assemble($"load R0,[{b}]")); Assert.Equal(new[] { new Instruction(0x11, b) }, _assembler.Assemble($"load R1,[{b}]")); Assert.Equal(new[] { new Instruction(0x12, b) }, _assembler.Assemble($"load R2,[{b}]")); Assert.Equal(new[] { new Instruction(0x13, b) }, _assembler.Assemble($"load R3,[{b}]")); Assert.Equal(new[] { new Instruction(0x14, b) }, _assembler.Assemble($"load R4,[{b}]")); Assert.Equal(new[] { new Instruction(0x15, b) }, _assembler.Assemble($"load R5,[{b}]")); Assert.Equal(new[] { new Instruction(0x16, b) }, _assembler.Assemble($"load R6,[{b}]")); Assert.Equal(new[] { new Instruction(0x17, b) }, _assembler.Assemble($"load R7,[{b}]")); Assert.Equal(new[] { new Instruction(0x18, b) }, _assembler.Assemble($"load R8,[{b}]")); Assert.Equal(new[] { new Instruction(0x19, b) }, _assembler.Assemble($"load R9,[{b}]")); Assert.Equal(new[] { new Instruction(0x1A, b) }, _assembler.Assemble($"load RA,[{b}]")); Assert.Equal(new[] { new Instruction(0x1B, b) }, _assembler.Assemble($"load RB,[{b}]")); Assert.Equal(new[] { new Instruction(0x1C, b) }, _assembler.Assemble($"load RC,[{b}]")); Assert.Equal(new[] { new Instruction(0x1D, b) }, _assembler.Assemble($"load RD,[{b}]")); Assert.Equal(new[] { new Instruction(0x1E, b) }, _assembler.Assemble($"load RE,[{b}]")); Assert.Equal(new[] { new Instruction(0x1F, b) }, _assembler.Assemble($"load RF,[{b}]")); } } [Fact] public void ShouldAssembleIndirectLoadInstructions() { for (byte registerIndex = 0; registerIndex < 16; registerIndex++) { Assert.Equal(new[] { new Instruction(0xD0, ((byte)0x0, registerIndex).Combine()) }, _assembler.Assemble($"load R0,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0x1, registerIndex).Combine()) }, _assembler.Assemble($"load R1,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0x2, registerIndex).Combine()) }, _assembler.Assemble($"load R2,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0x3, registerIndex).Combine()) }, _assembler.Assemble($"load R3,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0x4, registerIndex).Combine()) }, _assembler.Assemble($"load R4,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0x5, registerIndex).Combine()) }, _assembler.Assemble($"load R5,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0x6, registerIndex).Combine()) }, _assembler.Assemble($"load R6,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0x7, registerIndex).Combine()) }, _assembler.Assemble($"load R7,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0x8, registerIndex).Combine()) }, _assembler.Assemble($"load R8,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0x9, registerIndex).Combine()) }, _assembler.Assemble($"load R9,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0xA, registerIndex).Combine()) }, _assembler.Assemble($"load RA,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0xB, registerIndex).Combine()) }, _assembler.Assemble($"load RB,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0xC, registerIndex).Combine()) }, _assembler.Assemble($"load RC,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0xD, registerIndex).Combine()) }, _assembler.Assemble($"load RD,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0xE, registerIndex).Combine()) }, _assembler.Assemble($"load RE,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xD0, ((byte)0xF, registerIndex).Combine()) }, _assembler.Assemble($"load RF,[R{registerIndex.ToHexString()}]")); } } [Fact] public void ShouldAssembleAddIntegerInstructions() { for (byte i = 0; i < 16; i++) for (byte j = 0; j < 16; j++) for (byte k = 0; k < 16; k++) { Instruction[] expected = { new Instruction(((byte)0x5, i).Combine(), (j, k).Combine()) }; Instruction[] actual = _assembler.Assemble($"addi R{i.ToHexString()},R{j.ToHexString()},R{k.ToHexString()}"); Assert.Equal(expected, actual); } } [Fact] public void ShouldAssembleAddFloatInstructions() { for (byte i = 0; i < 16; i++) for (byte j = 0; j < 16; j++) for (byte k = 0; k < 16; k++) { Instruction[] expected = { new Instruction(((byte)0x6, i).Combine(), (j, k).Combine()) }; Instruction[] actual = _assembler.Assemble($"addf R{i.ToHexString()},R{j.ToHexString()},R{k.ToHexString()}"); Assert.Equal(expected, actual); } } [Fact] public void ShouldAssembleBitwiseAndInstructions() { for (byte i = 0; i < 16; i++) for (byte j = 0; j < 16; j++) for (byte k = 0; k < 16; k++) { Instruction[] expected = { new Instruction(((byte)0x8, i).Combine(), (j, k).Combine()) }; Instruction[] actual = _assembler.Assemble($"and R{i.ToHexString()},R{j.ToHexString()},R{k.ToHexString()}"); Assert.Equal(expected, actual); } } [Fact] public void ShouldAssembleBitwiseOrInstructions() { for (byte i = 0; i < 16; i++) for (byte j = 0; j < 16; j++) for (byte k = 0; k < 16; k++) { Instruction[] expected = { new Instruction(((byte)0x7, i).Combine(), (j, k).Combine()) }; Instruction[] actual = _assembler.Assemble($"or R{i.ToHexString()},R{j.ToHexString()},R{k.ToHexString()}"); Assert.Equal(expected, actual); } } [Fact] public void ShouldAssembleBitwiseExclusiveOrInstructions() { for (byte i = 0; i < 16; i++) for (byte j = 0; j < 16; j++) for (byte k = 0; k < 16; k++) { Instruction[] expected = { new Instruction(((byte)0x9, i).Combine(), (j, k).Combine()) }; Instruction[] actual = _assembler.Assemble($"xor R{i.ToHexString()},R{j.ToHexString()},R{k.ToHexString()}"); Assert.Equal(expected, actual); } } [Fact] public void ShouldAssembleRorInstructions() { for (byte number = 0; number < 16; number++) { Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0x0).Combine(), number) }, _assembler.Assemble($"ror R0,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0x1).Combine(), number) }, _assembler.Assemble($"ror R1,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0x2).Combine(), number) }, _assembler.Assemble($"ror R2,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0x3).Combine(), number) }, _assembler.Assemble($"ror R3,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0x4).Combine(), number) }, _assembler.Assemble($"ror R4,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0x5).Combine(), number) }, _assembler.Assemble($"ror R5,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0x6).Combine(), number) }, _assembler.Assemble($"ror R6,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0x7).Combine(), number) }, _assembler.Assemble($"ror R7,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0x8).Combine(), number) }, _assembler.Assemble($"ror R8,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0x9).Combine(), number) }, _assembler.Assemble($"ror R9,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0xA).Combine(), number) }, _assembler.Assemble($"ror RA,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0xB).Combine(), number) }, _assembler.Assemble($"ror RB,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0xC).Combine(), number) }, _assembler.Assemble($"ror RC,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0xD).Combine(), number) }, _assembler.Assemble($"ror RD,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0xE).Combine(), number) }, _assembler.Assemble($"ror RE,{number}")); Assert.Equal(new[] { new Instruction(((byte)0xA, (byte)0xF).Combine(), number) }, _assembler.Assemble($"ror RF,{number}")); } } [Fact] public void ShouldAssembleJumpEqualInstructions() { for (byte registerIndex = 0; registerIndex < 16; registerIndex++) for (int number = 0; number <= byte.MaxValue; number++) Assert.Equal(new[] { new Instruction(((byte)0xB, registerIndex).Combine(), (byte)number) }, _assembler.Assemble($"jmpEQ R{registerIndex.ToHexString()}=R0,{number}")); } [Fact] public void ShouldAssembleJumpLessEqualInstructions() { for (byte registerIndex = 0; registerIndex < 16; registerIndex++) for (int number = 0; number <= byte.MaxValue; number++) Assert.Equal(new[] { new Instruction(((byte)0xF, registerIndex).Combine(), (byte)number) }, _assembler.Assemble($"jmpLE R{registerIndex.ToHexString()}<=R0,{number}")); } [Fact] public void ShouldAssembleJumpInstructions() { for (int number = 0; number <= byte.MaxValue; number++) Assert.Equal(new[] { new Instruction(0xB0, (byte)number) }, _assembler.Assemble($"jmp {number}")); } [Fact] public void ShouldAssembleDataByteInstructions() { Instruction[] expected = { new Instruction(0x01, 0x04), new Instruction(0x09, 0x10), new Instruction(0x19, 0x24), new Instruction(0x48, 0x65), new Instruction(0x6C, 0x6C), new Instruction(0x6F, 0x20), new Instruction(0x57, 0x6F), new Instruction(0x72, 0x6C), new Instruction(0x64, 0x00) }; Assert.Equal(expected, _assembler.Assemble("db 1,4,9,16,25,36,\"Hello World\"")); Assert.Equal(expected, _assembler.Assemble("db 1,4,9,16,25,36,'Hello World'")); } [Theory] [InlineData(":")] // label delimiter [InlineData(";")] // comment delimiter [InlineData(",")] // operand delimiter public void ShouldAssembleDataByteInstructionWithDelimiterInsideQuotes(string delimiter) { _assembler.Assemble($"db \"{delimiter}\""); _assembler.Assemble($"db 1,\"{delimiter}\""); _assembler.Assemble($"db '{delimiter}'"); _assembler.Assemble($"db 1,'{delimiter}'"); } [Fact] public void ShouldAssembleHaltInstruction() { Assert.Equal(new[] { new Instruction(0xC0, 0x00) }, _assembler.Assemble("halt")); } [Fact] public void ShouldAssembleDirectStoreInstructions() { for (int number = 0; number <= byte.MaxValue; number++) { byte b = (byte)number; Assert.Equal(new[] { new Instruction(0x30, b) }, _assembler.Assemble($"store R0,[{b}]")); Assert.Equal(new[] { new Instruction(0x31, b) }, _assembler.Assemble($"store R1,[{b}]")); Assert.Equal(new[] { new Instruction(0x32, b) }, _assembler.Assemble($"store R2,[{b}]")); Assert.Equal(new[] { new Instruction(0x33, b) }, _assembler.Assemble($"store R3,[{b}]")); Assert.Equal(new[] { new Instruction(0x34, b) }, _assembler.Assemble($"store R4,[{b}]")); Assert.Equal(new[] { new Instruction(0x35, b) }, _assembler.Assemble($"store R5,[{b}]")); Assert.Equal(new[] { new Instruction(0x36, b) }, _assembler.Assemble($"store R6,[{b}]")); Assert.Equal(new[] { new Instruction(0x37, b) }, _assembler.Assemble($"store R7,[{b}]")); Assert.Equal(new[] { new Instruction(0x38, b) }, _assembler.Assemble($"store R8,[{b}]")); Assert.Equal(new[] { new Instruction(0x39, b) }, _assembler.Assemble($"store R9,[{b}]")); Assert.Equal(new[] { new Instruction(0x3A, b) }, _assembler.Assemble($"store RA,[{b}]")); Assert.Equal(new[] { new Instruction(0x3B, b) }, _assembler.Assemble($"store RB,[{b}]")); Assert.Equal(new[] { new Instruction(0x3C, b) }, _assembler.Assemble($"store RC,[{b}]")); Assert.Equal(new[] { new Instruction(0x3D, b) }, _assembler.Assemble($"store RD,[{b}]")); Assert.Equal(new[] { new Instruction(0x3E, b) }, _assembler.Assemble($"store RE,[{b}]")); Assert.Equal(new[] { new Instruction(0x3F, b) }, _assembler.Assemble($"store RF,[{b}]")); } } [Fact] public void ShouldAssembleIndirectStoreInstructions() { for (byte registerIndex = 0; registerIndex < 16; registerIndex++) { Assert.Equal(new[] { new Instruction(0xE0, ((byte)0x0, registerIndex).Combine()) }, _assembler.Assemble($"store R0,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0x1, registerIndex).Combine()) }, _assembler.Assemble($"store R1,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0x2, registerIndex).Combine()) }, _assembler.Assemble($"store R2,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0x3, registerIndex).Combine()) }, _assembler.Assemble($"store R3,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0x4, registerIndex).Combine()) }, _assembler.Assemble($"store R4,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0x5, registerIndex).Combine()) }, _assembler.Assemble($"store R5,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0x6, registerIndex).Combine()) }, _assembler.Assemble($"store R6,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0x7, registerIndex).Combine()) }, _assembler.Assemble($"store R7,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0x8, registerIndex).Combine()) }, _assembler.Assemble($"store R8,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0x9, registerIndex).Combine()) }, _assembler.Assemble($"store R9,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0xA, registerIndex).Combine()) }, _assembler.Assemble($"store RA,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0xB, registerIndex).Combine()) }, _assembler.Assemble($"store RB,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0xC, registerIndex).Combine()) }, _assembler.Assemble($"store RC,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0xD, registerIndex).Combine()) }, _assembler.Assemble($"store RD,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0xE, registerIndex).Combine()) }, _assembler.Assemble($"store RE,[R{registerIndex.ToHexString()}]")); Assert.Equal(new[] { new Instruction(0xE0, ((byte)0xF, registerIndex).Combine()) }, _assembler.Assemble($"store RF,[R{registerIndex.ToHexString()}]")); } } [Fact] public void ShouldAssembleMoveInstructions() { for (byte registerIndex = 0; registerIndex < 16; registerIndex++) { Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0x0).Combine()) }, _assembler.Assemble($"move R0,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0x1).Combine()) }, _assembler.Assemble($"move R1,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0x2).Combine()) }, _assembler.Assemble($"move R2,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0x3).Combine()) }, _assembler.Assemble($"move R3,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0x4).Combine()) }, _assembler.Assemble($"move R4,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0x5).Combine()) }, _assembler.Assemble($"move R5,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0x6).Combine()) }, _assembler.Assemble($"move R6,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0x7).Combine()) }, _assembler.Assemble($"move R7,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0x8).Combine()) }, _assembler.Assemble($"move R8,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0x9).Combine()) }, _assembler.Assemble($"move R9,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0xA).Combine()) }, _assembler.Assemble($"move RA,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0xB).Combine()) }, _assembler.Assemble($"move RB,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0xC).Combine()) }, _assembler.Assemble($"move RC,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0xD).Combine()) }, _assembler.Assemble($"move RD,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0xE).Combine()) }, _assembler.Assemble($"move RE,R{registerIndex.ToHexString()}")); Assert.Equal(new[] { new Instruction(0x40, (registerIndex, (byte)0xF).Combine()) }, _assembler.Assemble($"move RF,R{registerIndex.ToHexString()}")); } } [Fact] public void ShouldAssembleHelloWorldSampleProgram() { Assert.Equal(SamplePrograms.HelloWorldInstructions, _assembler.Assemble(SamplePrograms.HelloWorldCode)); } [Fact] public void ShouldAssembleOutputTestSampleProgram() { Assert.Equal(SamplePrograms.OutputTestInstructions, _assembler.Assemble(SamplePrograms.OutputTestCode)); } [Fact] public void ShouldAssembleTemplateSampleProgram() { Assert.Equal(SamplePrograms.TemplateInstructions, _assembler.Assemble(SamplePrograms.TemplateCode)); } [Fact] public void ShouldAssembleProgramWithLabelUsageBeforeDeclaration() { Assert.Equal(new[] { new Instruction(0x21, 0x02), new Instruction(0x0A, 0x00) }, _assembler.Assemble("load R1,Text\r\nText: db 10")); } [Fact] public void ShouldAssembleDecimalLiterals() { Assert.Equal(new[] { new Instruction(0x01, 0x00) }, _assembler.Assemble("db 1d")); Assert.Equal(new[] { new Instruction(0x64, 0x00) }, _assembler.Assemble("db 100d")); Assert.Equal(new[] { new Instruction(0xFF, 0x00) }, _assembler.Assemble("db 255d")); } [Fact] public void ShouldAssembleNegativeDecimalLiterals() { Assert.Equal(new[] { new Instruction(0x80, 0x00) }, _assembler.Assemble("db -128")); Assert.Equal(new[] { new Instruction(0xAF, 0x00) }, _assembler.Assemble("db -81d")); } [Fact] public void ShouldAssembleBinaryLiterals() { Assert.Equal(new[] { new Instruction(0x01, 0x00) }, _assembler.Assemble("db 00000001b")); Assert.Equal(new[] { new Instruction(0x64, 0x00) }, _assembler.Assemble("db 01100100b")); Assert.Equal(new[] { new Instruction(0xFF, 0x00) }, _assembler.Assemble("db 11111111b")); } [Fact] public void ShouldAssembleHexLiterals() { Assert.Equal(new[] { new Instruction(0x01, 0x00) }, _assembler.Assemble("db 0x01")); Assert.Equal(new[] { new Instruction(0x64, 0x00) }, _assembler.Assemble("db 0x64")); Assert.Equal(new[] { new Instruction(0xFF, 0x00) }, _assembler.Assemble("db 0xFF")); Assert.Equal(new[] { new Instruction(0x01, 0x00) }, _assembler.Assemble("db $01")); Assert.Equal(new[] { new Instruction(0x64, 0x00) }, _assembler.Assemble("db $64")); Assert.Equal(new[] { new Instruction(0xFF, 0x00) }, _assembler.Assemble("db $FF")); Assert.Equal(new[] { new Instruction(0x01, 0x00) }, _assembler.Assemble("db 01h")); Assert.Equal(new[] { new Instruction(0x64, 0x00) }, _assembler.Assemble("db 64h")); Assert.Equal(new[] { new Instruction(0xFF, 0x00) }, _assembler.Assemble("db 0FFh")); } [Fact] public void ShouldIgnoreComments() { Assert.Equal(new[] { new Instruction(0x23, 0xAA) }, _assembler.Assemble("load R3, 0xAA; This is an immediate load instruction.")); Assert.Equal(new Instruction[] { }, _assembler.Assemble(";load R3, 0xAA; This is a commented immediate load instruction.")); Assert.Equal(new Instruction[] { }, _assembler.Assemble(";This is a comment with no instructions preceding it.")); Assert.Equal(new Instruction[] { }, _assembler.Assemble(";This;comment;has;multiple;semicolons.")); Assert.Equal(new Instruction[] { }, _assembler.Assemble(";")); } [Fact] public void ShouldAssembleOriginInstruction_WithOneOriginOnly() { Assert.Equal(new[] { new Instruction(0x00, 0x00), new Instruction(0x00, 0x00), new Instruction(0x00, 0x00), new Instruction(0x20, 0x02) }, _assembler.Assemble(@"org 6 load R0,2")); } [Fact] public void ShouldAssembleOriginInstruction_WithLowerOriginFollowingHigherOrigin() { Assert.Equal(new[] { new Instruction(0x00, 0x00), new Instruction(0x25, 0x01), new Instruction(0x00, 0x00), new Instruction(0x00, 0x00), new Instruction(0x00, 0x00), new Instruction(0x20, 0x02) }, _assembler.Assemble(@"org 10 load R0,2 org 2 load R5,1")); } [Fact] public void ShouldAssembleOriginInstruction_WithOriginPreceedingLabel() { Assert.Equal(new[] { new Instruction(0xB0, 0x0A), new Instruction(0x00, 0x00), new Instruction(0x00, 0x00), new Instruction(0x00, 0x00), new Instruction(0x00, 0x00), }, _assembler.Assemble(@"jmp MyLabel org 10 MyLabel:")); } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using Amazon.OpsWorks.Model; using Amazon.Runtime.Internal.Transform; namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations { /// <summary> /// LayerUnmarshaller /// </summary> internal class LayerUnmarshaller : IUnmarshaller<Layer, XmlUnmarshallerContext>, IUnmarshaller<Layer, JsonUnmarshallerContext> { Layer IUnmarshaller<Layer, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } public Layer Unmarshall(JsonUnmarshallerContext context) { Layer layer = new Layer(); layer.Attributes = null; layer.CustomSecurityGroupIds = null; layer.DefaultSecurityGroupNames = null; layer.Packages = null; layer.VolumeConfigurations = null; int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; while (context.Read()) { if ((context.IsKey) && (context.CurrentDepth == targetDepth)) { context.Read(); context.Read(); if (context.TestExpression("StackId", targetDepth)) { layer.StackId = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("LayerId", targetDepth)) { layer.LayerId = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("Type", targetDepth)) { layer.Type = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("Name", targetDepth)) { layer.Name = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("Shortname", targetDepth)) { layer.Shortname = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("Attributes", targetDepth)) { layer.Attributes = new Dictionary<String,String>(); KeyValueUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller> unmarshaller = new KeyValueUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.GetInstance(), StringUnmarshaller.GetInstance()); while (context.Read()) { if (((context.IsStartArray || context.IsStartElement || context.IsLeafValue) && (context.CurrentDepth == targetDepth)) || ((context.IsKey) && (context.CurrentDepth == targetDepth+1))) { KeyValuePair<string, string> kvp = unmarshaller.Unmarshall(context); layer.Attributes.Add(kvp.Key, kvp.Value); } else if (context.IsEndElement) { break; } } continue; } if (context.TestExpression("CustomInstanceProfileArn", targetDepth)) { layer.CustomInstanceProfileArn = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("CustomSecurityGroupIds", targetDepth)) { layer.CustomSecurityGroupIds = new List<String>(); StringUnmarshaller unmarshaller = StringUnmarshaller.GetInstance(); while (context.Read()) { if ((context.IsArrayElement) && (context.CurrentDepth == targetDepth)) { layer.CustomSecurityGroupIds.Add(unmarshaller.Unmarshall(context)); } else if (context.IsEndArray) { break; } } continue; } if (context.TestExpression("DefaultSecurityGroupNames", targetDepth)) { layer.DefaultSecurityGroupNames = new List<String>(); StringUnmarshaller unmarshaller = StringUnmarshaller.GetInstance(); while (context.Read()) { if ((context.IsArrayElement) && (context.CurrentDepth == targetDepth)) { layer.DefaultSecurityGroupNames.Add(unmarshaller.Unmarshall(context)); } else if (context.IsEndArray) { break; } } continue; } if (context.TestExpression("Packages", targetDepth)) { layer.Packages = new List<String>(); StringUnmarshaller unmarshaller = StringUnmarshaller.GetInstance(); while (context.Read()) { if ((context.IsArrayElement) && (context.CurrentDepth == targetDepth)) { layer.Packages.Add(unmarshaller.Unmarshall(context)); } else if (context.IsEndArray) { break; } } continue; } if (context.TestExpression("VolumeConfigurations", targetDepth)) { layer.VolumeConfigurations = new List<VolumeConfiguration>(); VolumeConfigurationUnmarshaller unmarshaller = VolumeConfigurationUnmarshaller.GetInstance(); while (context.Read()) { if ((context.IsArrayElement) && (context.CurrentDepth == targetDepth)) { layer.VolumeConfigurations.Add(unmarshaller.Unmarshall(context)); } else if (context.IsEndArray) { break; } } continue; } if (context.TestExpression("EnableAutoHealing", targetDepth)) { layer.EnableAutoHealing = BoolUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("AutoAssignElasticIps", targetDepth)) { layer.AutoAssignElasticIps = BoolUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("DefaultRecipes", targetDepth)) { layer.DefaultRecipes = RecipesUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("CustomRecipes", targetDepth)) { layer.CustomRecipes = RecipesUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("CreatedAt", targetDepth)) { layer.CreatedAt = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("InstallUpdatesOnBoot", targetDepth)) { layer.InstallUpdatesOnBoot = BoolUnmarshaller.GetInstance().Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth <= originalDepth) { return layer; } } return layer; } private static LayerUnmarshaller instance; public static LayerUnmarshaller GetInstance() { if (instance == null) instance = new LayerUnmarshaller(); return instance; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; #if ENABLE_WINRT using Internal.Runtime.Augments; #endif namespace System.Globalization { #if CORECLR using StringList = List<string>; #else using StringList = LowLevelList<string>; #endif internal partial class CultureData { private const uint LOCALE_NOUSEROVERRIDE = 0x80000000; private const uint LOCALE_RETURN_NUMBER = 0x20000000; private const uint LOCALE_SISO3166CTRYNAME = 0x0000005A; private const uint TIME_NOSECONDS = 0x00000002; /// <summary> /// Check with the OS to see if this is a valid culture. /// If so we populate a limited number of fields. If its not valid we return false. /// /// The fields we populate: /// /// sWindowsName -- The name that windows thinks this culture is, ie: /// en-US if you pass in en-US /// de-DE_phoneb if you pass in de-DE_phoneb /// fj-FJ if you pass in fj (neutral, on a pre-Windows 7 machine) /// fj if you pass in fj (neutral, post-Windows 7 machine) /// /// sRealName -- The name you used to construct the culture, in pretty form /// en-US if you pass in EN-us /// en if you pass in en /// de-DE_phoneb if you pass in de-DE_phoneb /// /// sSpecificCulture -- The specific culture for this culture /// en-US for en-US /// en-US for en /// de-DE_phoneb for alt sort /// fj-FJ for fj (neutral) /// /// sName -- The IETF name of this culture (ie: no sort info, could be neutral) /// en-US if you pass in en-US /// en if you pass in en /// de-DE if you pass in de-DE_phoneb /// /// bNeutral -- TRUE if it is a neutral locale /// /// For a neutral we just populate the neutral name, but we leave the windows name pointing to the /// windows locale that's going to provide data for us. /// </summary> private unsafe bool InitCultureData() { Debug.Assert(!GlobalizationMode.Invariant); const uint LOCALE_ILANGUAGE = 0x00000001; const uint LOCALE_INEUTRAL = 0x00000071; const uint LOCALE_SNAME = 0x0000005c; int result; string realNameBuffer = _sRealName; char* pBuffer = stackalloc char[LOCALE_NAME_MAX_LENGTH]; result = GetLocaleInfoEx(realNameBuffer, LOCALE_SNAME, pBuffer, LOCALE_NAME_MAX_LENGTH); // Did it fail? if (result == 0) { return false; } // It worked, note that the name is the locale name, so use that (even for neutrals) // We need to clean up our "real" name, which should look like the windows name right now // so overwrite the input with the cleaned up name _sRealName = new String(pBuffer, 0, result - 1); realNameBuffer = _sRealName; // Check for neutrality, don't expect to fail // (buffer has our name in it, so we don't have to do the gc. stuff) result = GetLocaleInfoEx(realNameBuffer, LOCALE_INEUTRAL | LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char)); if (result == 0) { return false; } // Remember our neutrality _bNeutral = *((uint*)pBuffer) != 0; // Note: Parents will be set dynamically // Start by assuming the windows name will be the same as the specific name since windows knows // about specifics on all versions. Only for downlevel Neutral locales does this have to change. _sWindowsName = realNameBuffer; // Neutrals and non-neutrals are slightly different if (_bNeutral) { // Neutral Locale // IETF name looks like neutral name _sName = realNameBuffer; // Specific locale name is whatever ResolveLocaleName (win7+) returns. // (Buffer has our name in it, and we can recycle that because windows resolves it before writing to the buffer) result = Interop.Kernel32.ResolveLocaleName(realNameBuffer, pBuffer, LOCALE_NAME_MAX_LENGTH); // 0 is failure, 1 is invariant (""), which we expect if (result < 1) { return false; } // We found a locale name, so use it. // In vista this should look like a sort name (de-DE_phoneb) or a specific culture (en-US) and be in the "pretty" form _sSpecificCulture = new String(pBuffer, 0, result - 1); } else { // Specific Locale // Specific culture's the same as the locale name since we know its not neutral // On mac we'll use this as well, even for neutrals. There's no obvious specific // culture to use and this isn't exposed, but behaviorally this is correct on mac. // Note that specifics include the sort name (de-DE_phoneb) _sSpecificCulture = realNameBuffer; _sName = realNameBuffer; // We need the IETF name (sname) // If we aren't an alt sort locale then this is the same as the windows name. // If we are an alt sort locale then this is the same as the part before the _ in the windows name // This is for like de-DE_phoneb and es-ES_tradnl that hsouldn't have the _ part result = GetLocaleInfoEx(realNameBuffer, LOCALE_ILANGUAGE | LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char)); if (result == 0) { return false; } _iLanguage = *((int*)pBuffer); if (!IsCustomCultureId(_iLanguage)) { // not custom locale int index = realNameBuffer.IndexOf('_'); if (index > 0 && index < realNameBuffer.Length) { _sName = realNameBuffer.Substring(0, index); } } } // It succeeded. return true; } // Wrappers around the GetLocaleInfoEx APIs which handle marshalling the returned // data as either and Int or String. internal static unsafe String GetLocaleInfoEx(String localeName, uint field) { // REVIEW: Determine the maximum size for the buffer const int BUFFER_SIZE = 530; char* pBuffer = stackalloc char[BUFFER_SIZE]; int resultCode = GetLocaleInfoEx(localeName, field, pBuffer, BUFFER_SIZE); if (resultCode > 0) { return new String(pBuffer); } return null; } internal static unsafe int GetLocaleInfoExInt(String localeName, uint field) { const uint LOCALE_RETURN_NUMBER = 0x20000000; field |= LOCALE_RETURN_NUMBER; int value = 0; GetLocaleInfoEx(localeName, field, (char*) &value, sizeof(int)); return value; } internal static unsafe int GetLocaleInfoEx(string lpLocaleName, uint lcType, char* lpLCData, int cchData) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.Kernel32.GetLocaleInfoEx(lpLocaleName, lcType, lpLCData, cchData); } private string GetLocaleInfo(LocaleStringData type) { Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already"); return GetLocaleInfo(_sWindowsName, type); } // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the // "windows" name, which can be specific for downlevel (< windows 7) os's. private string GetLocaleInfo(string localeName, LocaleStringData type) { uint lctype = (uint)type; return GetLocaleInfoFromLCType(localeName, lctype, UseUserOverride); } private int GetLocaleInfo(LocaleNumberData type) { uint lctype = (uint)type; // Fix lctype if we don't want overrides if (!UseUserOverride) { lctype |= LOCALE_NOUSEROVERRIDE; } // Ask OS for data, note that we presume it returns success, so we have to know that // sWindowsName is valid before calling. Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); return GetLocaleInfoExInt(_sWindowsName, lctype); } private int[] GetLocaleInfo(LocaleGroupingData type) { return ConvertWin32GroupString(GetLocaleInfoFromLCType(_sWindowsName, (uint)type, UseUserOverride)); } private string GetTimeFormatString() { const uint LOCALE_STIMEFORMAT = 0x00001003; return ReescapeWin32String(GetLocaleInfoFromLCType(_sWindowsName, LOCALE_STIMEFORMAT, UseUserOverride)); } private int GetFirstDayOfWeek() { Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C; int result = GetLocaleInfoExInt(_sWindowsName, LOCALE_IFIRSTDAYOFWEEK | (!UseUserOverride ? LOCALE_NOUSEROVERRIDE : 0)); // Win32 and .NET disagree on the numbering for days of the week, so we have to convert. return ConvertFirstDayOfWeekMonToSun(result); } private String[] GetTimeFormats() { // Note that this gets overrides for us all the time Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already"); String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, 0, UseUserOverride)); return result; } private String[] GetShortTimeFormats() { // Note that this gets overrides for us all the time Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already"); String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, TIME_NOSECONDS, UseUserOverride)); return result; } // Enumerate all system cultures and then try to find out which culture has // region name match the requested region name private static CultureData GetCultureDataFromRegionName(String regionName) { Debug.Assert(regionName != null); const uint LOCALE_SUPPLEMENTAL = 0x00000002; const uint LOCALE_SPECIFICDATA = 0x00000020; EnumLocaleData context = new EnumLocaleData(); context.cultureName = null; context.regionName = regionName; unsafe { Interop.Kernel32.EnumSystemLocalesEx(EnumSystemLocalesProc, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, Unsafe.AsPointer(ref context), IntPtr.Zero); } if (context.cultureName != null) { // we got a matched culture return GetCultureData(context.cultureName, true); } return null; } private string GetLanguageDisplayName(string cultureName) { #if ENABLE_WINRT return WinRTInterop.Callbacks.GetLanguageDisplayName(cultureName); #else // Usually the UI culture shouldn't be different than what we got from WinRT except // if DefaultThreadCurrentUICulture was set CultureInfo ci; if (CultureInfo.DefaultThreadCurrentUICulture != null && ((ci = GetUserDefaultCulture()) != null) && !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name)) { return SNATIVEDISPLAYNAME; } else { return GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName); } #endif // ENABLE_WINRT } private string GetRegionDisplayName(string isoCountryCode) { #if ENABLE_WINRT return WinRTInterop.Callbacks.GetRegionDisplayName(isoCountryCode); #else // Usually the UI culture shouldn't be different than what we got from WinRT except // if DefaultThreadCurrentUICulture was set CultureInfo ci; if (CultureInfo.DefaultThreadCurrentUICulture != null && ((ci = GetUserDefaultCulture()) != null) && !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name)) { return SNATIVECOUNTRY; } else { return GetLocaleInfo(LocaleStringData.LocalizedCountryName); } #endif // ENABLE_WINRT } private static CultureInfo GetUserDefaultCulture() { #if ENABLE_WINRT return (CultureInfo)WinRTInterop.Callbacks.GetUserDefaultCulture(); #else return CultureInfo.GetUserDefaultCulture(); #endif // ENABLE_WINRT } // PAL methods end here. private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOveride) { Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null"); // Fix lctype if we don't want overrides if (!useUserOveride) { lctype |= LOCALE_NOUSEROVERRIDE; } // Ask OS for data string result = GetLocaleInfoEx(localeName, lctype); if (result == null) { // Failed, just use empty string result = String.Empty; } return result; } //////////////////////////////////////////////////////////////////////////// // // Reescape a Win32 style quote string as a NLS+ style quoted string // // This is also the escaping style used by custom culture data files // // NLS+ uses \ to escape the next character, whether in a quoted string or // not, so we always have to change \ to \\. // // NLS+ uses \' to escape a quote inside a quoted string so we have to change // '' to \' (if inside a quoted string) // // We don't build the stringbuilder unless we find something to change //////////////////////////////////////////////////////////////////////////// internal static String ReescapeWin32String(String str) { // If we don't have data, then don't try anything if (str == null) return null; StringBuilder result = null; bool inQuote = false; for (int i = 0; i < str.Length; i++) { // Look for quote if (str[i] == '\'') { // Already in quote? if (inQuote) { // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote? if (i + 1 < str.Length && str[i + 1] == '\'') { // Found another ', so we have ''. Need to add \' instead. // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append a \' and keep going (so we don't turn off quote mode) result.Append("\\'"); i++; continue; } // Turning off quote mode, fall through to add it inQuote = false; } else { // Found beginning quote, fall through to add it inQuote = true; } } // Is there a single \ character? else if (str[i] == '\\') { // Found a \, need to change it to \\ // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append our \\ to the string & continue result.Append("\\\\"); continue; } // If we have a builder we need to add our character if (result != null) result.Append(str[i]); } // Unchanged string? , just return input string if (result == null) return str; // String changed, need to use the builder return result.ToString(); } internal static String[] ReescapeWin32Strings(String[] array) { if (array != null) { for (int i = 0; i < array.Length; i++) { array[i] = ReescapeWin32String(array[i]); } } return array; } // If we get a group from windows, then its in 3;0 format with the 0 backwards // of how NLS+ uses it (ie: if the string has a 0, then the int[] shouldn't and vice versa) // EXCEPT in the case where the list only contains 0 in which NLS and NLS+ have the same meaning. private static int[] ConvertWin32GroupString(String win32Str) { // None of these cases make any sense if (win32Str == null || win32Str.Length == 0) { return (new int[] { 3 }); } if (win32Str[0] == '0') { return (new int[] { 0 }); } // Since its in n;n;n;n;n format, we can always get the length quickly int[] values; if (win32Str[win32Str.Length - 1] == '0') { // Trailing 0 gets dropped. 1;0 -> 1 values = new int[(win32Str.Length / 2)]; } else { // Need extra space for trailing zero 1 -> 1;0 values = new int[(win32Str.Length / 2) + 2]; values[values.Length - 1] = 0; } int i; int j; for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++) { // Note that this # shouldn't ever be zero, 'cause 0 is only at end // But we'll test because its registry that could be anything if (win32Str[i] < '1' || win32Str[i] > '9') return new int[] { 3 }; values[j] = (int)(win32Str[i] - '0'); } return (values); } private static int ConvertFirstDayOfWeekMonToSun(int iTemp) { // Convert Mon-Sun to Sun-Sat format iTemp++; if (iTemp > 6) { // Wrap Sunday and convert invalid data to Sunday iTemp = 0; } return iTemp; } // Context for EnumCalendarInfoExEx callback. private class EnumLocaleData { public string regionName; public string cultureName; } // EnumSystemLocaleEx callback. // [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static unsafe Interop.BOOL EnumSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle) { ref EnumLocaleData context = ref Unsafe.As<byte, EnumLocaleData>(ref *(byte*)contextHandle); try { string cultureName = new string(lpLocaleString); string regionName = GetLocaleInfoEx(cultureName, LOCALE_SISO3166CTRYNAME); if (regionName != null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase)) { context.cultureName = cultureName; return Interop.BOOL.FALSE; // we found a match, then stop the enumeration } return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } // EnumSystemLocaleEx callback. // [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static unsafe Interop.BOOL EnumAllSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle) { ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)contextHandle); try { context.strings.Add(new string(lpLocaleString)); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } // Context for EnumTimeFormatsEx callback. private class EnumData { public StringList strings; } // EnumTimeFormatsEx callback itself. // [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static unsafe Interop.BOOL EnumTimeCallback(char* lpTimeFormatString, void* lParam) { ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam); try { context.strings.Add(new string(lpTimeFormatString)); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } private static unsafe String[] nativeEnumTimeFormats(String localeName, uint dwFlags, bool useUserOverride) { const uint LOCALE_SSHORTTIME = 0x00000079; const uint LOCALE_STIMEFORMAT = 0x00001003; EnumData data = new EnumData(); data.strings = new StringList(); // Now call the enumeration API. Work is done by our callback function Interop.Kernel32.EnumTimeFormatsEx(EnumTimeCallback, localeName, (uint)dwFlags, Unsafe.AsPointer(ref data)); if (data.strings.Count > 0) { // Now we need to allocate our stringarray and populate it string[] results = data.strings.ToArray(); if (!useUserOverride && data.strings.Count > 1) { // Since there is no "NoUserOverride" aware EnumTimeFormatsEx, we always get an override // The override is the first entry if it is overriden. // We can check if we have overrides by checking the GetLocaleInfo with no override // If we do have an override, we don't know if it is a user defined override or if the // user has just selected one of the predefined formats so we can't just remove it // but we can move it down. uint lcType = (dwFlags == TIME_NOSECONDS) ? LOCALE_SSHORTTIME : LOCALE_STIMEFORMAT; string timeFormatNoUserOverride = GetLocaleInfoFromLCType(localeName, lcType, useUserOverride); if (timeFormatNoUserOverride != "") { string firstTimeFormat = results[0]; if (timeFormatNoUserOverride != firstTimeFormat) { results[0] = results[1]; results[1] = firstTimeFormat; } } } return results; } return null; } private static int LocaleNameToLCID(string cultureName) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.Kernel32.LocaleNameToLCID(cultureName, Interop.Kernel32.LOCALE_ALLOW_NEUTRAL_NAMES); } private static unsafe string LCIDToLocaleName(int culture) { Debug.Assert(!GlobalizationMode.Invariant); char *pBuffer = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH + 1]; // +1 for the null termination int length = Interop.Kernel32.LCIDToLocaleName(culture, pBuffer, Interop.Kernel32.LOCALE_NAME_MAX_LENGTH + 1, Interop.Kernel32.LOCALE_ALLOW_NEUTRAL_NAMES); if (length > 0) { return new String(pBuffer); } return null; } private int GetAnsiCodePage(string cultureName) { return GetLocaleInfo(LocaleNumberData.AnsiCodePage); } private int GetOemCodePage(string cultureName) { return GetLocaleInfo(LocaleNumberData.OemCodePage); } private int GetMacCodePage(string cultureName) { return GetLocaleInfo(LocaleNumberData.MacCodePage); } private int GetEbcdicCodePage(string cultureName) { return GetLocaleInfo(LocaleNumberData.EbcdicCodePage); } private int GetGeoId(string cultureName) { return GetLocaleInfo(LocaleNumberData.GeoId); } private int GetDigitSubstitution(string cultureName) { return GetLocaleInfo(LocaleNumberData.DigitSubstitution); } private string GetThreeLetterWindowsLanguageName(string cultureName) { return GetLocaleInfo(cultureName, LocaleStringData.AbbreviatedWindowsLanguageName); } private static CultureInfo[] EnumCultures(CultureTypes types) { Debug.Assert(!GlobalizationMode.Invariant); uint flags = 0; #pragma warning disable 618 if ((types & (CultureTypes.FrameworkCultures | CultureTypes.InstalledWin32Cultures | CultureTypes.ReplacementCultures)) != 0) { flags |= Interop.Kernel32.LOCALE_NEUTRALDATA | Interop.Kernel32.LOCALE_SPECIFICDATA; } #pragma warning restore 618 if ((types & CultureTypes.NeutralCultures) != 0) { flags |= Interop.Kernel32.LOCALE_NEUTRALDATA; } if ((types & CultureTypes.SpecificCultures) != 0) { flags |= Interop.Kernel32.LOCALE_SPECIFICDATA; } if ((types & CultureTypes.UserCustomCulture) != 0) { flags |= Interop.Kernel32.LOCALE_SUPPLEMENTAL; } if ((types & CultureTypes.ReplacementCultures) != 0) { flags |= Interop.Kernel32.LOCALE_SUPPLEMENTAL; } EnumData context = new EnumData(); context.strings = new StringList(); unsafe { Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, flags, Unsafe.AsPointer(ref context), IntPtr.Zero); } CultureInfo [] cultures = new CultureInfo[context.strings.Count]; for (int i = 0; i < cultures.Length; i++) { cultures[i] = new CultureInfo(context.strings[i]); } return cultures; } private string GetConsoleFallbackName(string cultureName) { return GetLocaleInfo(cultureName, LocaleStringData.ConsoleFallbackName); } internal bool IsFramework { get { return false; } } internal bool IsWin32Installed { get { return true; } } internal bool IsReplacementCulture { get { EnumData context = new EnumData(); context.strings = new StringList(); unsafe { Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, Interop.Kernel32.LOCALE_REPLACEMENT, Unsafe.AsPointer(ref context), IntPtr.Zero); } for (int i=0; i<context.strings.Count; i++) { if (String.Compare(context.strings[i], _sWindowsName, StringComparison.OrdinalIgnoreCase) == 0) return true; } return false; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; using System.Threading.Tasks; using Microsoft.Extensions.Options; using Orleans; using Orleans.Configuration; namespace Orleankka { using Utility; public interface IDispatcherRegistry { Dispatcher GetDispatcher(Type type); } class DispatcherRegistry : IDispatcherRegistry { static readonly Dictionary<Type, Dispatcher> dispatchers = new Dictionary<Type, Dispatcher>(); public void Register(Type type, Dispatcher dispatcher) => dispatchers.Add(type, dispatcher); public Dispatcher GetDispatcher(Type type) => dispatchers[type]; } /// <summary> /// Configures built-in <see cref="Dispatcher"/> /// </summary> public class DispatcherOptions { /// <summary> /// The handler naming conventions to use /// </summary> public string[] HandlerNamingConventions { get; set; } = Dispatcher.DefaultHandlerNamingConventions; /// <summary> /// The base types where the handler traversal should stop (ie root types) /// </summary> public Type[] RootTypes { get; set; } = Dispatcher.DefaultRootTypes; } /// <summary> /// Validator for <see cref="DispatcherOptions"/> /// </summary> public class DispatcherOptionsValidator : IConfigurationValidator { readonly DispatcherOptions options; public DispatcherOptionsValidator(IOptions<DispatcherOptions> options) => this.options = options.Value; public void ValidateConfiguration() { if (options.HandlerNamingConventions == null || options.HandlerNamingConventions.Length == 0) throw new Exception( $"Configuration for {nameof(DispatcherOptions)} is invalid. " + $"A non-null, non-empty array for {nameof(options.HandlerNamingConventions)} is required"); if (options.RootTypes == null || options.RootTypes.Length == 0) throw new Exception( $"Configuration for {nameof(DispatcherOptions)} is invalid. " + $"A non-null, non-empty array for {nameof(options.RootTypes)} is required"); } } public class Dispatcher { public static readonly string[] DefaultHandlerNamingConventions = {"On", "Handle", "Answer", "Apply"}; public static readonly Type[] DefaultRootTypes = {typeof(ActorGrain), typeof(object)}; readonly Dictionary<Type, Action<object, object>> actions = new Dictionary<Type, Action<object, object>>(); readonly Dictionary<Type, Func<object, object, object>> funcs = new Dictionary<Type, Func<object, object, object>>(); readonly Dictionary<Type, Func<object, object, Task<object>>> uniform = new Dictionary<Type, Func<object, object, Task<object>>>(); readonly Type type; public Dispatcher(Type type, string[] handlerNamingConventions = null, Type[] rootTypes = null) { this.type = type; var methods = GetMethods(type, rootTypes ?? DefaultRootTypes, handlerNamingConventions ?? DefaultHandlerNamingConventions); foreach (var method in methods) Register(method); } static IEnumerable<MethodInfo> GetMethods(Type type, Type[] roots, string[] conventions) { while (type != null) { if (roots.Contains(type)) yield break; const BindingFlags scope = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; var methods = type .GetMethods(scope) .Where(m => m.GetParameters().Length == 1 && !m.GetParameters()[0].IsOut && !m.GetParameters()[0].IsRetval && !m.IsGenericMethod && !m.ContainsGenericParameters && conventions.Contains(m.Name)); foreach (var method in methods) yield return method; type = type.BaseType; } } void Register(MethodInfo method) { RegisterUniform(method); RegisterNonUniform(method); } void RegisterUniform(MethodInfo method) { var message = method.GetParameters()[0].ParameterType; var handler = Bind.Uniform.Handler(method, type); if (uniform.ContainsKey(message)) throw new InvalidOperationException( $"Handler for {message} has been already defined by {type}"); uniform.Add(message, handler); } void RegisterNonUniform(MethodInfo method) { if (typeof(Task).IsAssignableFrom(method.ReturnType)) return; if (method.ReturnType == typeof(void)) { RegisterAction(method); return; } RegisterFunc(method); } void RegisterAction(MethodInfo method) { var message = method.GetParameters()[0].ParameterType; var handler = Bind.NonUniform.ActionHandler(method, type); actions.Add(message, handler); } void RegisterFunc(MethodInfo method) { var message = method.GetParameters()[0].ParameterType; var handler = Bind.NonUniform.FuncHandler(method, type); funcs.Add(message, handler); } public bool CanHandle(Type message) => uniform.Find(message) != null; public IEnumerable<Type> Handlers => uniform.Keys; public Task<object> DispatchResultAsync(object target, object message, Func<object, Task<object>> fallback = null) => DispatchResultAsync<object>(target, message, fallback); public async Task<T> DispatchResultAsync<T>(object target, object message, Func<object, Task<T>> fallback = null) { var handler = uniform.Find(message.GetType()); if (handler != null) return (T) await handler(target, message); if (fallback == null) throw new HandlerNotFoundException(target, message.GetType()); return await fallback(message); } public async Task DispatchAsync(object target, object message, Func<object, Task> fallback = null) { await DispatchResultAsync<object>(target, message, async x => { if (fallback != null) await fallback(x); return null; }); } public object DispatchResult(object target, object message, Func<object, object> fallback = null) => DispatchResult<object>(target, message, fallback); public T DispatchResult<T>(object target, object message, Func<object, T> fallback = null) { var handler = funcs.Find(message.GetType()); if (handler != null) return (T) handler(target, message); if (fallback == null) throw new HandlerNotFoundException(target, message.GetType()); return fallback(message); } public void Dispatch(object target, object message, Action<object> fallback = null) { var handler = actions.Find(message.GetType()); if (handler != null) { handler(target, message); return; } if (fallback == null) throw new HandlerNotFoundException(target, message.GetType()); fallback(message); } [Serializable] internal class HandlerNotFoundException : ApplicationException { const string description = "Can't find handler for '{1}'.\r\n on actor '{0}'." + "Check that handler method has single argument and " + "named 'On', 'Handle', 'Answer' or 'Apply'"; internal HandlerNotFoundException(object target, Type message) : base(string.Format(description, target.GetType(), message)) {} protected HandlerNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {} } static class Bind { static readonly Task<object> Done = Task.FromResult((object)null); internal static class NonUniform { public static Action<object, object> ActionHandler(MethodInfo method, Type actor) { var compiler = typeof(Void<>) .MakeGenericType(method.GetParameters()[0].ParameterType) .GetMethod("Action", BindingFlags.Public | BindingFlags.Static); return (Action<object, object>)compiler.Invoke(null, new object[] {method, actor}); } public static Func<object, object, object> FuncHandler(MethodInfo method, Type actor) { var compiler = typeof(Result<>) .MakeGenericType(method.GetParameters()[0].ParameterType) .GetMethod("Func", BindingFlags.Public | BindingFlags.Static) .MakeGenericMethod(method.ReturnType); return (Func<object, object, object>)compiler.Invoke(null, new object[] {method, actor}); } static class Void<TRequest> { public static Action<object, object> Action(MethodInfo method, Type type) { return method.IsStatic ? StaticAction(method) : InstanceAction(method, type); } static Action<object, object> StaticAction(MethodInfo method) { var request = Expression.Parameter(typeof(object)); var requestConversion = Expression.Convert(request, typeof(TRequest)); var call = Expression.Call(null, method, requestConversion); var action = Expression.Lambda<Action<object>>(call, request).Compile(); return (t, r) => action(r); } static Action<object, object> InstanceAction(MethodInfo method, Type type) { Debug.Assert(method.DeclaringType != null); var target = Expression.Parameter(typeof(object)); var request = Expression.Parameter(typeof(object)); var targetConversion = Expression.Convert(target, type); var requestConversion = Expression.Convert(request, typeof(TRequest)); var call = Expression.Call(targetConversion, method, requestConversion); var action = Expression.Lambda<Action<object, object>>(call, target, request).Compile(); return action; } } static class Result<TRequest> { public static Func<object, object, object> Func<TResult>(MethodInfo method, Type type) { return method.IsStatic ? StaticFunc<TResult>(method) : InstanceFunc<TResult>(method, type); } static Func<object, object, object> StaticFunc<TResult>(MethodInfo method) { var request = Expression.Parameter(typeof(object)); var requestConversion = Expression.Convert(request, typeof(TRequest)); var call = Expression.Call(null, method, requestConversion); var func = Expression.Lambda<Func<object, TResult>>(call, request).Compile(); return (t, r) => func(r); } static Func<object, object, object> InstanceFunc<TResult>(MethodInfo method, Type type) { Debug.Assert(method.DeclaringType != null); var target = Expression.Parameter(typeof(object)); var request = Expression.Parameter(typeof(object)); var targetConversion = Expression.Convert(target, type); var requestConversion = Expression.Convert(request, typeof(TRequest)); var call = Expression.Call(targetConversion, method, requestConversion); var func = Expression.Lambda<Func<object, object, TResult>>(call, target, request).Compile(); return (t, r) => (object)func(t, r); } } } public static class Uniform { public static Func<object, object, Task<object>> Handler(MethodInfo method, Type actor) { if (typeof(Task).IsAssignableFrom(method.ReturnType)) { return method.ReturnType.GenericTypeArguments.Length != 0 ? Lambda(typeof(Async<>), "Func", method.ReturnType.GenericTypeArguments[0], method, actor) : Lambda(typeof(Async<>), "Action", null, method, actor); } return method.ReturnType != typeof(void) ? NonAsync.Func(method, actor) : NonAsync.Action(method, actor); } static Func<object, object, Task<object>> Lambda(Type binder, string kind, Type arg, MethodInfo method, Type type) { var compiler = binder .MakeGenericType(method.GetParameters()[0].ParameterType) .GetMethod(kind, BindingFlags.Public | BindingFlags.Static); if (arg != null) compiler = compiler.MakeGenericMethod(arg); return (Func<object, object, Task<object>>)compiler.Invoke(null, new object[] { method, type }); } static class Async<TRequest> { public static Func<object, object, Task<object>> Func<TResult>(MethodInfo method, Type type) { return method.IsStatic ? StaticFunc<TResult>(method) : InstanceFunc<TResult>(method, type); } static Func<object, object, Task<object>> StaticFunc<TResult>(MethodInfo method) { var request = Expression.Parameter(typeof(object)); var requestConversion = Expression.Convert(request, typeof(TRequest)); var call = Expression.Call(null, method, requestConversion); var func = Expression.Lambda<Func<object, Task<TResult>>>(call, request).Compile(); return async (t, r) => await func(r); } static Func<object, object, Task<object>> InstanceFunc<TResult>(MethodInfo method, Type type) { Debug.Assert(method.DeclaringType != null); var target = Expression.Parameter(typeof(object)); var request = Expression.Parameter(typeof(object)); var targetConversion = Expression.Convert(target, type); var requestConversion = Expression.Convert(request, typeof(TRequest)); var call = Expression.Call(targetConversion, method, requestConversion); var func = Expression.Lambda<Func<object, object, Task<TResult>>>(call, target, request).Compile(); return async (t, r) => await func(t, r); } public static Func<object, object, Task<object>> Action(MethodInfo method, Type type) { return method.IsStatic ? StaticAction(method) : InstanceAction(method, type); } static Func<object, object, Task<object>> StaticAction(MethodInfo method) { var request = Expression.Parameter(typeof(object)); var requestConversion = Expression.Convert(request, typeof(TRequest)); var call = Expression.Call(null, method, requestConversion); var func = Expression.Lambda<Func<object, Task>>(call, request).Compile(); return async (t, r) => { await func(r); return null; }; } static Func<object, object, Task<object>> InstanceAction(MethodInfo method, Type type) { Debug.Assert(method.DeclaringType != null); var target = Expression.Parameter(typeof(object)); var request = Expression.Parameter(typeof(object)); var targetConversion = Expression.Convert(target, type); var requestConversion = Expression.Convert(request, typeof(TRequest)); var call = Expression.Call(targetConversion, method, requestConversion); var func = Expression.Lambda<Func<object, object, Task>>(call, target, request).Compile(); return async (t, r) => { await func(t, r); return null; }; } } static class NonAsync { public static Func<object, object, Task<object>> Func(MethodInfo method, Type type) { var handler = NonUniform.FuncHandler(method, type); return (t, r) => Task.FromResult(handler(t, r)); } public static Func<object, object, Task<object>> Action(MethodInfo method, Type type) { var handler = NonUniform.ActionHandler(method, type); return (t, r) => { handler(t, r); return Done; }; } } } } } }
// *********************************************************************** // Copyright (c) 2010-2014 Charlie Poole, Rob Prouse // // 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.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using NUnit.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal { /// <summary> /// The TestResult class represents the result of a test. /// </summary> public abstract class TestResult : LongLivedMarshalByRefObject, ITestResult { #region Fields /// <summary> /// Error message for when child tests have errors /// </summary> internal static readonly string CHILD_ERRORS_MESSAGE = "One or more child tests had errors"; /// <summary> /// Error message for when child tests have warnings /// </summary> internal static readonly string CHILD_WARNINGS_MESSAGE = "One or more child tests had warnings"; /// <summary> /// Error message for when child tests are ignored /// </summary> internal static readonly string CHILD_IGNORE_MESSAGE = "One or more child tests were ignored"; /// <summary> /// The minimum duration for tests /// </summary> internal const double MIN_DURATION = 0.000001d; // static Logger log = InternalTrace.GetLogger("TestResult"); private readonly StringBuilder _output = new StringBuilder(); private double _duration; /// <summary> /// Aggregate assertion count /// </summary> protected int InternalAssertCount; private ResultState _resultState; private string _message; private string _stackTrace; private readonly List<AssertionResult> _assertionResults = new List<AssertionResult>(); private readonly List<TestAttachment> _testAttachments = new List<TestAttachment>(); #if PARALLEL /// <summary> /// ReaderWriterLock /// </summary> #if NET20 protected ReaderWriterLock RwLock = new ReaderWriterLock(); #else protected ReaderWriterLockSlim RwLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); #endif #endif #endregion #region Constructor /// <summary> /// Construct a test result given a Test /// </summary> /// <param name="test">The test to be used</param> public TestResult(ITest test) { Test = test; ResultState = ResultState.Inconclusive; #if !PARALLEL OutWriter = new StringWriter(_output); #else OutWriter = TextWriter.Synchronized(new StringWriter(_output)); #endif } #endregion #region ITestResult Members /// <summary> /// Gets the test with which this result is associated. /// </summary> public ITest Test { get; } /// <summary> /// Gets the ResultState of the test result, which /// indicates the success or failure of the test. /// </summary> public ResultState ResultState { get { #if PARALLEL RwLock.EnterReadLock(); #endif try { return _resultState; } finally { #if PARALLEL RwLock.ExitReadLock(); #endif } } private set { _resultState = value; } } /// <summary> /// Gets the name of the test result /// </summary> public virtual string Name { get { return Test.Name; } } /// <summary> /// Gets the full name of the test result /// </summary> public virtual string FullName { get { return Test.FullName; } } /// <summary> /// Gets or sets the elapsed time for running the test in seconds /// </summary> public double Duration { get { return _duration; } set { _duration = value >= MIN_DURATION ? value : MIN_DURATION; } } /// <summary> /// Gets or sets the time the test started running. /// </summary> public DateTime StartTime { get; set; } /// <summary> /// Gets or sets the time the test finished running. /// </summary> public DateTime EndTime { get; set; } /// <summary> /// Adds a test attachment to the test result /// </summary> /// <param name="attachment">The TestAttachment object to attach</param> internal void AddTestAttachment(TestAttachment attachment) { _testAttachments.Add(attachment); } /// <summary> /// Gets the collection of files attached to the test /// </summary> public ICollection<TestAttachment> TestAttachments => new ReadOnlyCollection<TestAttachment>(_testAttachments); /// <summary> /// Gets the message associated with a test /// failure or with not running the test /// </summary> public string Message { get { #if PARALLEL RwLock.EnterReadLock(); #endif try { return _message; } finally { #if PARALLEL RwLock.ExitReadLock(); #endif } } private set { _message = value; } } /// <summary> /// Gets any stack trace associated with an /// error or failure. /// </summary> public virtual string StackTrace { get { #if PARALLEL RwLock.EnterReadLock(); #endif try { return _stackTrace; } finally { #if PARALLEL RwLock.ExitReadLock(); #endif } } private set { _stackTrace = value; } } /// <summary> /// Gets or sets the count of asserts executed /// when running the test. /// </summary> public int AssertCount { get { #if PARALLEL RwLock.EnterReadLock(); #endif try { return InternalAssertCount; } finally { #if PARALLEL RwLock.ExitReadLock (); #endif } } internal set { InternalAssertCount = value; } } /// <summary> /// Gets the number of test cases that failed /// when running the test and all its children. /// </summary> public abstract int FailCount { get; } /// <summary> /// Gets the number of test cases that had warnings /// when running the test and all its children. /// </summary> public abstract int WarningCount { get; } /// <summary> /// Gets the number of test cases that passed /// when running the test and all its children. /// </summary> public abstract int PassCount { get; } /// <summary> /// Gets the number of test cases that were skipped /// when running the test and all its children. /// </summary> public abstract int SkipCount { get; } /// <summary> /// Gets the number of test cases that were inconclusive /// when running the test and all its children. /// </summary> public abstract int InconclusiveCount { get; } /// <summary> /// Indicates whether this result has any child results. /// </summary> public abstract bool HasChildren { get; } /// <summary> /// Gets the collection of child results. /// </summary> public abstract IEnumerable<ITestResult> Children { get; } /// <summary> /// Gets a TextWriter, which will write output to be included in the result. /// </summary> public TextWriter OutWriter { get; } /// <summary> /// Gets any text output written to this result. /// </summary> public string Output { get { #if PARALLEL lock (OutWriter) { return _output.ToString(); } #else return _output.ToString(); #endif } } /// <summary> /// Gets a list of assertion results associated with the test. /// </summary> public IList<AssertionResult> AssertionResults { get { return _assertionResults; } } #endregion #region IXmlNodeBuilder Members /// <summary> /// Returns the XML representation of the result. /// </summary> /// <param name="recursive">If true, descendant results are included</param> /// <returns>An XmlNode representing the result</returns> public TNode ToXml(bool recursive) { return AddToXml(new TNode("dummy"), recursive); } /// <summary> /// Adds the XML representation of the result as a child of the /// supplied parent node.. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public virtual TNode AddToXml(TNode parentNode, bool recursive) { // A result node looks like a test node with extra info added TNode thisNode = Test.AddToXml(parentNode, false); thisNode.AddAttribute("result", ResultState.Status.ToString()); if (ResultState.Label != string.Empty) // && ResultState.Label != ResultState.Status.ToString()) thisNode.AddAttribute("label", ResultState.Label); if (ResultState.Site != FailureSite.Test) thisNode.AddAttribute("site", ResultState.Site.ToString()); thisNode.AddAttribute("start-time", StartTime.ToString("u")); thisNode.AddAttribute("end-time", EndTime.ToString("u")); thisNode.AddAttribute("duration", Duration.ToString("0.000000", NumberFormatInfo.InvariantInfo)); if (Test is TestSuite) { thisNode.AddAttribute("total", (PassCount + FailCount + SkipCount + InconclusiveCount).ToString()); thisNode.AddAttribute("passed", PassCount.ToString()); thisNode.AddAttribute("failed", FailCount.ToString()); thisNode.AddAttribute("warnings", WarningCount.ToString()); thisNode.AddAttribute("inconclusive", InconclusiveCount.ToString()); thisNode.AddAttribute("skipped", SkipCount.ToString()); } thisNode.AddAttribute("asserts", AssertCount.ToString()); switch (ResultState.Status) { case TestStatus.Failed: AddFailureElement(thisNode); break; case TestStatus.Skipped: case TestStatus.Passed: case TestStatus.Inconclusive: case TestStatus.Warning: if (Message != null && Message.Trim().Length > 0) AddReasonElement(thisNode); break; } if (Output.Length > 0) AddOutputElement(thisNode); if (AssertionResults.Count > 0) AddAssertionsElement(thisNode); if (_testAttachments.Count > 0) AddAttachmentsElement(thisNode); if (recursive && HasChildren) foreach (TestResult child in Children) child.AddToXml(thisNode, recursive); return thisNode; } #endregion #region Other Public Properties /// <summary> /// Gets a count of pending failures (from Multiple Assert) /// </summary> public int PendingFailures { get { return AssertionResults.Count(ar => ar.Status == AssertionStatus.Failed); } } /// <summary> /// Gets the worst assertion status (highest enum) in all the assertion results /// </summary> public AssertionStatus WorstAssertionStatus { get { return AssertionResults.Aggregate((ar1, ar2) => ar1.Status > ar2.Status ? ar1 : ar2).Status; } } #endregion #region Other Public Methods /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> public void SetResult(ResultState resultState) { SetResult(resultState, null, null); } /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> /// <param name="message">A message associated with the result state</param> public void SetResult(ResultState resultState, string message) { SetResult(resultState, message, null); } /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> /// <param name="message">A message associated with the result state</param> /// <param name="stackTrace">Stack trace giving the location of the command</param> public void SetResult(ResultState resultState, string message, string stackTrace) { #if PARALLEL RwLock.EnterWriteLock(); #endif try { ResultState = resultState; Message = message; StackTrace = stackTrace; } finally { #if PARALLEL RwLock.ExitWriteLock(); #endif } } /// <summary> /// Set the test result based on the type of exception thrown /// </summary> /// <param name="ex">The exception that was thrown</param> public void RecordException(Exception ex) { var result = new ExceptionResult(ex, FailureSite.Test); SetResult(result.ResultState, result.Message, result.StackTrace); if (AssertionResults.Count > 0 && result.ResultState == ResultState.Error) { // Add pending failures to the legacy result message Message += CreateLegacyFailureMessage(); // Add to the list of assertion errors, so that newer runners will see it AssertionResults.Add(new AssertionResult(AssertionStatus.Error, result.Message, result.StackTrace)); } } /// <summary> /// Set the test result based on the type of exception thrown /// </summary> /// <param name="ex">The exception that was thrown</param> /// <param name="site">The FailureSite to use in the result</param> public void RecordException(Exception ex, FailureSite site) { var result = new ExceptionResult(ex, site); SetResult(result.ResultState, result.Message, result.StackTrace); } /// <summary> /// RecordTearDownException appends the message and stack trace /// from an exception arising during teardown of the test /// to any previously recorded information, so that any /// earlier failure information is not lost. Note that /// calling Assert.Ignore, Assert.Inconclusive, etc. during /// teardown is treated as an error. If the current result /// represents a suite, it may show a teardown error even /// though all contained tests passed. /// </summary> /// <param name="ex">The Exception to be recorded</param> public void RecordTearDownException(Exception ex) { ex = ValidateAndUnwrap(ex); ResultState resultState = ResultState == ResultState.Cancelled ? ResultState.Cancelled : ResultState.Error; if (Test.IsSuite) resultState = resultState.WithSite(FailureSite.TearDown); string message = "TearDown : " + ExceptionHelper.BuildMessage(ex); if (Message != null) message = Message + Environment.NewLine + message; string stackTrace = "--TearDown" + Environment.NewLine + ExceptionHelper.BuildStackTrace(ex); if (StackTrace != null) stackTrace = StackTrace + Environment.NewLine + stackTrace; SetResult(resultState, message, stackTrace); } private static Exception ValidateAndUnwrap(Exception ex) { Guard.ArgumentNotNull(ex, nameof(ex)); if ((ex is NUnitException || ex is TargetInvocationException) && ex.InnerException != null) return ex.InnerException; return ex; } private struct ExceptionResult { public ResultState ResultState { get; } public string Message { get; } public string StackTrace { get; } public ExceptionResult(Exception ex, FailureSite site) { ex = ValidateAndUnwrap(ex); if (ex is ResultStateException) { ResultState = ((ResultStateException)ex).ResultState.WithSite(site); Message = ex.Message; StackTrace = StackFilter.DefaultFilter.Filter(ex.StackTrace); } #if THREAD_ABORT else if (ex is ThreadAbortException) { ResultState = ResultState.Cancelled.WithSite(site); Message = "Test cancelled by user"; StackTrace = ex.StackTrace; } #endif else { ResultState = ResultState.Error.WithSite(site); Message = ExceptionHelper.BuildMessage(ex); StackTrace = ExceptionHelper.BuildStackTrace(ex); } } } /// <summary> /// Update overall test result, including legacy Message, based /// on AssertionResults that have been saved to this point. /// </summary> public void RecordTestCompletion() { switch (AssertionResults.Count) { case 0: SetResult(ResultState.Success); break; case 1: SetResult( AssertionStatusToResultState(AssertionResults[0].Status), AssertionResults[0].Message, AssertionResults[0].StackTrace); break; default: SetResult( AssertionStatusToResultState(WorstAssertionStatus), CreateLegacyFailureMessage()); break; } } /// <summary> /// Record an assertion result /// </summary> public void RecordAssertion(AssertionResult assertion) { _assertionResults.Add(assertion); } /// <summary> /// Record an assertion result /// </summary> public void RecordAssertion(AssertionStatus status, string message, string stackTrace) { RecordAssertion(new AssertionResult(status, message, stackTrace)); } /// <summary> /// Record an assertion result /// </summary> public void RecordAssertion(AssertionStatus status, string message) { RecordAssertion(status, message, null); } /// <summary> /// Creates a failure message incorporating failures /// from a Multiple Assert block for use by runners /// that don't know about AssertionResults. /// </summary> /// <returns>Message as a string</returns> private string CreateLegacyFailureMessage() { var writer = new StringWriter(); if (AssertionResults.Count > 1) writer.WriteLine("Multiple failures or warnings in test:"); int counter = 0; foreach (var assertion in AssertionResults) writer.WriteLine(string.Format(" {0}) {1}", ++counter, assertion.Message)); return writer.ToString(); } #endregion #region Helper Methods /// <summary> /// Adds a reason element to a node and returns it. /// </summary> /// <param name="targetNode">The target node.</param> /// <returns>The new reason element.</returns> private TNode AddReasonElement(TNode targetNode) { TNode reasonNode = targetNode.AddElement("reason"); return reasonNode.AddElementWithCDATA("message", Message); } /// <summary> /// Adds a failure element to a node and returns it. /// </summary> /// <param name="targetNode">The target node.</param> /// <returns>The new failure element.</returns> private TNode AddFailureElement(TNode targetNode) { TNode failureNode = targetNode.AddElement("failure"); if (Message != null && Message.Trim().Length > 0) failureNode.AddElementWithCDATA("message", Message); if (StackTrace != null && StackTrace.Trim().Length > 0) failureNode.AddElementWithCDATA("stack-trace", StackTrace); return failureNode; } private TNode AddOutputElement(TNode targetNode) { return targetNode.AddElementWithCDATA("output", Output); } private TNode AddAssertionsElement(TNode targetNode) { var assertionsNode = targetNode.AddElement("assertions"); foreach (var assertion in AssertionResults) { TNode assertionNode = assertionsNode.AddElement("assertion"); assertionNode.AddAttribute("result", assertion.Status.ToString()); if (assertion.Message != null) assertionNode.AddElementWithCDATA("message", assertion.Message); if (assertion.StackTrace != null) assertionNode.AddElementWithCDATA("stack-trace", assertion.StackTrace); } return assertionsNode; } private ResultState AssertionStatusToResultState(AssertionStatus status) { switch (status) { case AssertionStatus.Inconclusive: return ResultState.Inconclusive; default: case AssertionStatus.Passed: return ResultState.Success; case AssertionStatus.Warning: return ResultState.Warning; case AssertionStatus.Failed: return ResultState.Failure; case AssertionStatus.Error: return ResultState.Error; } } /// <summary> /// Adds an attachments element to a node and returns it. /// </summary> /// <param name="targetNode">The target node.</param> /// <returns>The new attachments element.</returns> private TNode AddAttachmentsElement(TNode targetNode) { TNode attachmentsNode = targetNode.AddElement("attachments"); foreach (var attachment in _testAttachments) { var attachmentNode = attachmentsNode.AddElement("attachment"); attachmentNode.AddElement("filePath", attachment.FilePath); if (attachment.Description != null) attachmentNode.AddElementWithCDATA("description", attachment.Description); } return attachmentsNode; } #endregion } }
using System.Windows.Forms; using SIL.Media.Naudio.UI; namespace HearThis.UI { partial class RecordingToolControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) components?.Dispose(); base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this._bookFlow = new System.Windows.Forms.FlowLayoutPanel(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this._chapterFlow = new System.Windows.Forms.FlowLayoutPanel(); this._bookLabel = new System.Windows.Forms.Label(); this._chapterLabel = new System.Windows.Forms.Label(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this._segmentLabel = new System.Windows.Forms.Label(); this._lineCountLabel = new System.Windows.Forms.Label(); this._peakMeter = new SIL.Media.Naudio.UI.PeakMeterCtrl(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this._instantToolTip = new System.Windows.Forms.ToolTip(this.components); this.recordingDeviceButton1 = new SIL.Media.Naudio.UI.RecordingDeviceIndicator(); this._endOfUnitMessage = new System.Windows.Forms.Label(); this._nextChapterLink = new System.Windows.Forms.LinkLabel(); this.l10NSharpExtender1 = new L10NSharp.UI.L10NSharpExtender(this.components); this._contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this._mnuShiftClips = new System.Windows.Forms.ToolStripMenuItem(); this._smallerButton = new HearThis.UI.HearThisToolbarButton(); this._largerButton = new HearThis.UI.HearThisToolbarButton(); this._skipButton = new HearThis.UI.HearThisToolbarButton(); this._recordInPartsButton = new HearThis.UI.HearThisToolbarButton(); this._deleteRecordingButton = new HearThis.UI.HearThisToolbarButton(); this._breakLinesAtCommasButton = new HearThis.UI.HearThisToolbarButton(); this._scriptSlider = new HearThis.UI.DiscontiguousProgressTrackBar(); this._scriptControl = new HearThis.UI.ScriptControl(); this._audioButtonsControl = new HearThis.UI.AudioButtonsControl(); this.tableLayoutPanel1.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.l10NSharpExtender1)).BeginInit(); this._contextMenuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this._smallerButton)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._largerButton)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._skipButton)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._recordInPartsButton)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._deleteRecordingButton)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._breakLinesAtCommasButton)).BeginInit(); this.SuspendLayout(); // // _bookFlow // this._bookFlow.AutoSize = true; this.tableLayoutPanel1.SetColumnSpan(this._bookFlow, 2); this._bookFlow.Dock = System.Windows.Forms.DockStyle.Fill; this._bookFlow.Location = new System.Drawing.Point(3, 32); this._bookFlow.Margin = new System.Windows.Forms.Padding(3, 0, 3, 13); this._bookFlow.Name = "_bookFlow"; this._bookFlow.Size = new System.Drawing.Size(661, 1); this._bookFlow.TabIndex = 0; this._bookFlow.MouseEnter += new System.EventHandler(this.HandleNavigationArea_MouseEnter); this._bookFlow.MouseLeave += new System.EventHandler(this.HandleNavigationArea_MouseLeave); // // tableLayoutPanel1 // this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this._bookFlow, 0, 1); this.tableLayoutPanel1.Controls.Add(this._chapterFlow, 0, 3); this.tableLayoutPanel1.Controls.Add(this._bookLabel, 0, 0); this.tableLayoutPanel1.Controls.Add(this._chapterLabel, 0, 2); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 4); this.tableLayoutPanel1.Controls.Add(this._lineCountLabel, 1, 4); this.tableLayoutPanel1.Controls.Add(this._scriptSlider, 0, 5); this.tableLayoutPanel1.Controls.Add(this._peakMeter, 1, 7); this.tableLayoutPanel1.Controls.Add(this._scriptControl, 0, 6); this.tableLayoutPanel1.Controls.Add(this._audioButtonsControl, 1, 6); this.tableLayoutPanel1.Location = new System.Drawing.Point(13, 15); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 8; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(667, 457); this.tableLayoutPanel1.TabIndex = 1; // // _chapterFlow // this._chapterFlow.AutoSize = true; this.tableLayoutPanel1.SetColumnSpan(this._chapterFlow, 2); this._chapterFlow.Dock = System.Windows.Forms.DockStyle.Fill; this._chapterFlow.Location = new System.Drawing.Point(6, 77); this._chapterFlow.Margin = new System.Windows.Forms.Padding(6, 0, 3, 3); this._chapterFlow.Name = "_chapterFlow"; this._chapterFlow.Size = new System.Drawing.Size(658, 1); this._chapterFlow.TabIndex = 5; this._chapterFlow.MouseEnter += new System.EventHandler(this.HandleNavigationArea_MouseEnter); this._chapterFlow.MouseLeave += new System.EventHandler(this.HandleNavigationArea_MouseLeave); // // _bookLabel // this._bookLabel.Anchor = System.Windows.Forms.AnchorStyles.Left; this._bookLabel.AutoSize = true; this.tableLayoutPanel1.SetColumnSpan(this._bookLabel, 2); this._bookLabel.Font = new System.Drawing.Font("Segoe UI", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._bookLabel.ForeColor = System.Drawing.Color.DarkGray; this.l10NSharpExtender1.SetLocalizableToolTip(this._bookLabel, null); this.l10NSharpExtender1.SetLocalizationComment(this._bookLabel, null); this.l10NSharpExtender1.SetLocalizationPriority(this._bookLabel, L10NSharp.LocalizationPriority.NotLocalizable); this.l10NSharpExtender1.SetLocalizingId(this._bookLabel, "RecordingControl.BookLabel"); this._bookLabel.Location = new System.Drawing.Point(0, 0); this._bookLabel.Margin = new System.Windows.Forms.Padding(0); this._bookLabel.Name = "_bookLabel"; this._bookLabel.Size = new System.Drawing.Size(29, 32); this._bookLabel.TabIndex = 3; this._bookLabel.Text = "#"; // // _chapterLabel // this._chapterLabel.Anchor = System.Windows.Forms.AnchorStyles.Left; this._chapterLabel.AutoSize = true; this.tableLayoutPanel1.SetColumnSpan(this._chapterLabel, 2); this._chapterLabel.Font = new System.Drawing.Font("Segoe UI", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._chapterLabel.ForeColor = System.Drawing.Color.DarkGray; this.l10NSharpExtender1.SetLocalizableToolTip(this._chapterLabel, null); this.l10NSharpExtender1.SetLocalizationComment(this._chapterLabel, null); this.l10NSharpExtender1.SetLocalizationPriority(this._chapterLabel, L10NSharp.LocalizationPriority.NotLocalizable); this.l10NSharpExtender1.SetLocalizingId(this._chapterLabel, "RecordingControl.ChapterLabel"); this._chapterLabel.Location = new System.Drawing.Point(0, 45); this._chapterLabel.Margin = new System.Windows.Forms.Padding(0); this._chapterLabel.Name = "_chapterLabel"; this._chapterLabel.Size = new System.Drawing.Size(29, 32); this._chapterLabel.TabIndex = 4; this._chapterLabel.Text = "#"; // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this._segmentLabel); this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 83); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(361, 35); this.flowLayoutPanel1.TabIndex = 41; // // _segmentLabel // this._segmentLabel.AutoSize = true; this._segmentLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65))))); this._segmentLabel.Font = new System.Drawing.Font("Segoe UI", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._segmentLabel.ForeColor = System.Drawing.Color.DarkGray; this.l10NSharpExtender1.SetLocalizableToolTip(this._segmentLabel, null); this.l10NSharpExtender1.SetLocalizationComment(this._segmentLabel, null); this.l10NSharpExtender1.SetLocalizationPriority(this._segmentLabel, L10NSharp.LocalizationPriority.NotLocalizable); this.l10NSharpExtender1.SetLocalizingId(this._segmentLabel, "RecordingControl.SegmentLabel"); this._segmentLabel.Location = new System.Drawing.Point(0, 0); this._segmentLabel.Margin = new System.Windows.Forms.Padding(0); this._segmentLabel.Name = "_segmentLabel"; this._segmentLabel.Size = new System.Drawing.Size(105, 32); this._segmentLabel.TabIndex = 12; this._segmentLabel.Text = "Verse 20"; // // _lineCountLabel // this._lineCountLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this._lineCountLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65))))); this._lineCountLabel.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._lineCountLabel.ForeColor = System.Drawing.Color.DarkGray; this.l10NSharpExtender1.SetLocalizableToolTip(this._lineCountLabel, null); this.l10NSharpExtender1.SetLocalizationComment(this._lineCountLabel, null); this.l10NSharpExtender1.SetLocalizingId(this._lineCountLabel, "RecordingControl.LineCountLabel"); this._lineCountLabel.Location = new System.Drawing.Point(414, 80); this._lineCountLabel.Name = "_lineCountLabel"; this._lineCountLabel.Size = new System.Drawing.Size(250, 25); this._lineCountLabel.TabIndex = 25; this._lineCountLabel.Text = "Block {0}/{1}"; this._lineCountLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // _peakMeter // this._peakMeter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this._peakMeter.BandsCount = 1; this._peakMeter.ColorHigh = System.Drawing.Color.Red; this._peakMeter.ColorHighBack = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(150)))), ((int)(((byte)(150))))); this._peakMeter.ColorMedium = System.Drawing.Color.Yellow; this._peakMeter.ColorMediumBack = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(150))))); this._peakMeter.ColorNormal = System.Drawing.Color.Green; this._peakMeter.ColorNormalBack = System.Drawing.Color.FromArgb(((int)(((byte)(150)))), ((int)(((byte)(255)))), ((int)(((byte)(150))))); this._peakMeter.FalloffColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(180)))), ((int)(((byte)(180))))); this._peakMeter.FalloffEffect = false; this._peakMeter.GridColor = System.Drawing.Color.Gainsboro; this._peakMeter.LEDCount = 15; this.l10NSharpExtender1.SetLocalizableToolTip(this._peakMeter, null); this.l10NSharpExtender1.SetLocalizationComment(this._peakMeter, null); this.l10NSharpExtender1.SetLocalizationPriority(this._peakMeter, L10NSharp.LocalizationPriority.NotLocalizable); this.l10NSharpExtender1.SetLocalizingId(this._peakMeter, "RecordingControl.PeakMeter"); this._peakMeter.Location = new System.Drawing.Point(644, 345); this._peakMeter.Name = "_peakMeter"; this._peakMeter.ShowGrid = false; this._peakMeter.Size = new System.Drawing.Size(20, 109); this._peakMeter.TabIndex = 22; this._peakMeter.Text = "peakMeterCtrl1"; // // toolTip1 // this.toolTip1.AutoPopDelay = 6500; this.toolTip1.InitialDelay = 500; this.toolTip1.ReshowDelay = 100; // // _instantToolTip // this._instantToolTip.AutomaticDelay = 0; this._instantToolTip.UseAnimation = false; this._instantToolTip.UseFading = false; // // recordingDeviceButton1 // this.recordingDeviceButton1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.recordingDeviceButton1.BackColor = System.Drawing.Color.Transparent; this.recordingDeviceButton1.ComputerInternalImage = null; this.recordingDeviceButton1.KnownHeadsetImage = null; this.recordingDeviceButton1.LineImage = null; this.l10NSharpExtender1.SetLocalizableToolTip(this.recordingDeviceButton1, null); this.l10NSharpExtender1.SetLocalizationComment(this.recordingDeviceButton1, null); this.l10NSharpExtender1.SetLocalizationPriority(this.recordingDeviceButton1, L10NSharp.LocalizationPriority.Low); this.l10NSharpExtender1.SetLocalizingId(this.recordingDeviceButton1, "RecordingControl.RecordingDeviceButton"); this.recordingDeviceButton1.Location = new System.Drawing.Point(659, 494); this.recordingDeviceButton1.Margin = new System.Windows.Forms.Padding(0, 3, 3, 3); this.recordingDeviceButton1.MicrophoneImage = null; this.recordingDeviceButton1.Name = "recordingDeviceButton1"; this.recordingDeviceButton1.NoAudioDeviceImage = null; this.recordingDeviceButton1.Recorder = null; this.recordingDeviceButton1.RecorderImage = null; this.recordingDeviceButton1.Size = new System.Drawing.Size(22, 25); this.recordingDeviceButton1.TabIndex = 23; this.recordingDeviceButton1.UsbAudioDeviceImage = null; this.recordingDeviceButton1.WebcamImage = null; // // _endOfUnitMessage // this._endOfUnitMessage.BackColor = System.Drawing.Color.Transparent; this._endOfUnitMessage.Font = new System.Drawing.Font("Microsoft Sans Serif", 22F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._endOfUnitMessage.ForeColor = System.Drawing.Color.White; this.l10NSharpExtender1.SetLocalizableToolTip(this._endOfUnitMessage, null); this.l10NSharpExtender1.SetLocalizationComment(this._endOfUnitMessage, null); this.l10NSharpExtender1.SetLocalizingId(this._endOfUnitMessage, "RecordingControl.RecordingToolControl._endOfUnitMessage"); this._endOfUnitMessage.Location = new System.Drawing.Point(19, 312); this._endOfUnitMessage.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6); this._endOfUnitMessage.Name = "_endOfUnitMessage"; this._endOfUnitMessage.Size = new System.Drawing.Size(356, 50); this._endOfUnitMessage.TabIndex = 35; this._endOfUnitMessage.Text = "End of Chapter/Book"; this._endOfUnitMessage.Visible = false; // // _nextChapterLink // this._nextChapterLink.BackColor = System.Drawing.Color.Transparent; this._nextChapterLink.Font = new System.Drawing.Font("Microsoft Sans Serif", 22F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._nextChapterLink.ForeColor = System.Drawing.Color.White; this.l10NSharpExtender1.SetLocalizableToolTip(this._nextChapterLink, null); this.l10NSharpExtender1.SetLocalizationComment(this._nextChapterLink, null); this.l10NSharpExtender1.SetLocalizingId(this._nextChapterLink, "RecordingControl.RecordingToolControl._nextChapterLink"); this._nextChapterLink.Location = new System.Drawing.Point(19, 365); this._nextChapterLink.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6); this._nextChapterLink.Name = "_nextChapterLink"; this._nextChapterLink.Size = new System.Drawing.Size(356, 50); this._nextChapterLink.TabIndex = 36; this._nextChapterLink.TabStop = true; this._nextChapterLink.Text = "Go To Chapter x"; this._nextChapterLink.Visible = false; this._nextChapterLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.OnNextChapterLink_LinkClicked); // // l10NSharpExtender1 // this.l10NSharpExtender1.LocalizationManagerId = "HearThis"; this.l10NSharpExtender1.PrefixForNewItems = "RecordingControl"; // // _contextMenuStrip // this._contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this._mnuShiftClips}); this.l10NSharpExtender1.SetLocalizableToolTip(this._contextMenuStrip, null); this.l10NSharpExtender1.SetLocalizationComment(this._contextMenuStrip, null); this.l10NSharpExtender1.SetLocalizationPriority(this._contextMenuStrip, L10NSharp.LocalizationPriority.NotLocalizable); this.l10NSharpExtender1.SetLocalizingId(this._contextMenuStrip, "RecordingControl._contextMenuStrip._contextMenuStrip"); this._contextMenuStrip.Name = "_contextMenuStrip"; this._contextMenuStrip.Size = new System.Drawing.Size(181, 48); // // _mnuShiftClips // this.l10NSharpExtender1.SetLocalizableToolTip(this._mnuShiftClips, null); this.l10NSharpExtender1.SetLocalizationComment(this._mnuShiftClips, null); this.l10NSharpExtender1.SetLocalizingId(this._mnuShiftClips, "RecordingControl.ShiftClipsToolStripMenuItem"); this._mnuShiftClips.Name = "_mnuShiftClips"; this._mnuShiftClips.Size = new System.Drawing.Size(180, 22); this._mnuShiftClips.Text = "Shift Clips..."; this._mnuShiftClips.Click += new System.EventHandler(this._mnuShiftClips_Click); // // _smallerButton // this._smallerButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this._smallerButton.CheckBox = false; this._smallerButton.Checked = false; this._smallerButton.Image = global::HearThis.Properties.Resources.BottomToolbar_Smaller; this.l10NSharpExtender1.SetLocalizableToolTip(this._smallerButton, "Smaller Text"); this.l10NSharpExtender1.SetLocalizationComment(this._smallerButton, null); this.l10NSharpExtender1.SetLocalizingId(this._smallerButton, "RecordingControl.SmallerButton"); this._smallerButton.Location = new System.Drawing.Point(14, 490); this._smallerButton.Name = "_smallerButton"; this._smallerButton.Size = new System.Drawing.Size(18, 24); this._smallerButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this._smallerButton.TabIndex = 46; this._smallerButton.TabStop = false; this._smallerButton.Click += new System.EventHandler(this.OnSmallerClick); // // _largerButton // this._largerButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this._largerButton.CheckBox = false; this._largerButton.Checked = false; this._largerButton.Image = global::HearThis.Properties.Resources.BottomToolbar_Larger; this.l10NSharpExtender1.SetLocalizableToolTip(this._largerButton, "Larger Text"); this.l10NSharpExtender1.SetLocalizationComment(this._largerButton, null); this.l10NSharpExtender1.SetLocalizingId(this._largerButton, "RecordingControl.LargerButton"); this._largerButton.Location = new System.Drawing.Point(36, 490); this._largerButton.Name = "_largerButton"; this._largerButton.Size = new System.Drawing.Size(23, 24); this._largerButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this._largerButton.TabIndex = 45; this._largerButton.TabStop = false; this._largerButton.Click += new System.EventHandler(this.OnLargerClick); // // _skipButton // this._skipButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this._skipButton.CheckBox = true; this._skipButton.Checked = false; this._skipButton.Image = global::HearThis.Properties.Resources.BottomToolbar_Skip; this.l10NSharpExtender1.SetLocalizableToolTip(this._skipButton, "Skip this block - it does not need to be recorded."); this.l10NSharpExtender1.SetLocalizationComment(this._skipButton, null); this.l10NSharpExtender1.SetLocalizingId(this._skipButton, "RecordingControl.skipButton1"); this._skipButton.Location = new System.Drawing.Point(374, 490); this._skipButton.Margin = new System.Windows.Forms.Padding(0); this._skipButton.Name = "_skipButton"; this._skipButton.Size = new System.Drawing.Size(22, 24); this._skipButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this._skipButton.TabIndex = 44; this._skipButton.TabStop = false; this._skipButton.CheckedChanged += new System.EventHandler(this.OnSkipButtonCheckedChanged); // // _recordInPartsButton // this._recordInPartsButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this._recordInPartsButton.CheckBox = false; this._recordInPartsButton.Checked = false; this._recordInPartsButton.Image = global::HearThis.Properties.Resources.BottomToolbar_RecordInParts; this.l10NSharpExtender1.SetLocalizableToolTip(this._recordInPartsButton, "Record long lines in parts. (Press P)"); this.l10NSharpExtender1.SetLocalizationComment(this._recordInPartsButton, null); this.l10NSharpExtender1.SetLocalizingId(this._recordInPartsButton, "RecordingControl.RecordLongLinesInParts"); this._recordInPartsButton.Location = new System.Drawing.Point(314, 490); this._recordInPartsButton.Margin = new System.Windows.Forms.Padding(0); this._recordInPartsButton.Name = "_recordInPartsButton"; this._recordInPartsButton.Size = new System.Drawing.Size(40, 24); this._recordInPartsButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this._recordInPartsButton.TabIndex = 43; this._recordInPartsButton.TabStop = false; this._recordInPartsButton.Click += new System.EventHandler(this.longLineButton_Click); // // _deleteRecordingButton // this._deleteRecordingButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this._deleteRecordingButton.CheckBox = false; this._deleteRecordingButton.Checked = false; this._deleteRecordingButton.Image = global::HearThis.Properties.Resources.BottomToolbar_Delete; this.l10NSharpExtender1.SetLocalizableToolTip(this._deleteRecordingButton, "Remove this recorded clip (Delete Key)"); this.l10NSharpExtender1.SetLocalizationComment(this._deleteRecordingButton, "Shows as an \'X\' when on a script line that has been recorded."); this.l10NSharpExtender1.SetLocalizingId(this._deleteRecordingButton, "RecordingControl.RemoveThisRecording"); this._deleteRecordingButton.Location = new System.Drawing.Point(619, 490); this._deleteRecordingButton.Name = "_deleteRecordingButton"; this._deleteRecordingButton.Size = new System.Drawing.Size(21, 24); this._deleteRecordingButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this._deleteRecordingButton.TabIndex = 39; this._deleteRecordingButton.TabStop = false; this._deleteRecordingButton.Click += new System.EventHandler(this._deleteRecordingButton_Click); this._deleteRecordingButton.MouseEnter += new System.EventHandler(this._deleteRecordingButton_MouseEnter); this._deleteRecordingButton.MouseLeave += new System.EventHandler(this._deleteRecordingButton_MouseLeave); // // _breakLinesAtCommasButton // this._breakLinesAtCommasButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this._breakLinesAtCommasButton.CheckBox = true; this._breakLinesAtCommasButton.Checked = false; this._breakLinesAtCommasButton.Image = global::HearThis.Properties.Resources.BottomToolbar_BreakOnCommas; this.l10NSharpExtender1.SetLocalizableToolTip(this._breakLinesAtCommasButton, "Start new line at pause punctuation"); this.l10NSharpExtender1.SetLocalizationComment(this._breakLinesAtCommasButton, null); this.l10NSharpExtender1.SetLocalizingId(this._breakLinesAtCommasButton, "RecordingControl.BreakLinesAtClauses"); this._breakLinesAtCommasButton.Location = new System.Drawing.Point(100, 490); this._breakLinesAtCommasButton.Name = "_breakLinesAtCommasButton"; this._breakLinesAtCommasButton.Size = new System.Drawing.Size(28, 24); this._breakLinesAtCommasButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this._breakLinesAtCommasButton.TabIndex = 38; this._breakLinesAtCommasButton.TabStop = false; this._breakLinesAtCommasButton.Click += new System.EventHandler(this._breakLinesAtCommasButton_Click); // // _scriptSlider // this._scriptSlider.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._scriptSlider.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65))))); this.tableLayoutPanel1.SetColumnSpan(this._scriptSlider, 2); this.l10NSharpExtender1.SetLocalizableToolTip(this._scriptSlider, null); this.l10NSharpExtender1.SetLocalizationComment(this._scriptSlider, null); this.l10NSharpExtender1.SetLocalizingId(this._scriptSlider, "RecordingControl.ScriptLineSlider"); this._scriptSlider.Location = new System.Drawing.Point(3, 124); this._scriptSlider.Name = "_scriptSlider"; this._scriptSlider.SegmentCount = 50; this._scriptSlider.Size = new System.Drawing.Size(661, 25); this._scriptSlider.TabIndex = 11; this._scriptSlider.Value = 4; this._scriptSlider.ValueChanged += new System.EventHandler(this.OnLineSlider_ValueChanged); this._scriptSlider.MouseClick += new System.Windows.Forms.MouseEventHandler(this._scriptSlider_MouseClick); // // _scriptControl // this._scriptControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._scriptControl.BackColor = System.Drawing.Color.Transparent; this._scriptControl.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._scriptControl.ForeColor = System.Drawing.Color.White; this.l10NSharpExtender1.SetLocalizableToolTip(this._scriptControl, null); this.l10NSharpExtender1.SetLocalizationComment(this._scriptControl, null); this.l10NSharpExtender1.SetLocalizingId(this._scriptControl, "RecordingControl.ScriptControl"); this._scriptControl.Location = new System.Drawing.Point(4, 158); this._scriptControl.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6); this._scriptControl.Name = "_scriptControl"; this.tableLayoutPanel1.SetRowSpan(this._scriptControl, 2); this._scriptControl.ShowSkippedBlocks = false; this._scriptControl.Size = new System.Drawing.Size(403, 293); this._scriptControl.TabIndex = 15; this._scriptControl.ZoomFactor = 1F; this._scriptControl.LocationChanged += new System.EventHandler(this._scriptControl_LocationChanged); // // _audioButtonsControl // this._audioButtonsControl.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this._audioButtonsControl.BackColor = System.Drawing.Color.Transparent; this._audioButtonsControl.ButtonHighlightMode = HearThis.UI.AudioButtonsControl.ButtonHighlightModes.Default; this.l10NSharpExtender1.SetLocalizableToolTip(this._audioButtonsControl, null); this.l10NSharpExtender1.SetLocalizationComment(this._audioButtonsControl, null); this.l10NSharpExtender1.SetLocalizingId(this._audioButtonsControl, "RecordingControl.AudioButtonsControl"); this._audioButtonsControl.Location = new System.Drawing.Point(541, 155); this._audioButtonsControl.Name = "_audioButtonsControl"; this._audioButtonsControl.RecordingDevice = null; this._audioButtonsControl.Size = new System.Drawing.Size(123, 43); this._audioButtonsControl.TabIndex = 20; this._audioButtonsControl.NextClick += new System.EventHandler(this.OnNextButton); this._audioButtonsControl.RecordButtonStateChanged += new HearThis.UI.AudioButtonsControl.ButtonStateChangedHandler(this.OnRecordButtonStateChanged); // // RecordingToolControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65))))); this.Controls.Add(this._smallerButton); this.Controls.Add(this._largerButton); this.Controls.Add(this._skipButton); this.Controls.Add(this._recordInPartsButton); this.Controls.Add(this._deleteRecordingButton); this.Controls.Add(this._breakLinesAtCommasButton); this.Controls.Add(this.recordingDeviceButton1); this.Controls.Add(this._endOfUnitMessage); this.Controls.Add(this.tableLayoutPanel1); this.Controls.Add(this._nextChapterLink); this.l10NSharpExtender1.SetLocalizableToolTip(this, null); this.l10NSharpExtender1.SetLocalizationComment(this, null); this.l10NSharpExtender1.SetLocalizationPriority(this, L10NSharp.LocalizationPriority.NotLocalizable); this.l10NSharpExtender1.SetLocalizingId(this, "RecordingControl.RecordingToolControl.RecordingToolControl"); this.Margin = new System.Windows.Forms.Padding(10); this.Name = "RecordingToolControl"; this.Size = new System.Drawing.Size(706, 527); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.l10NSharpExtender1)).EndInit(); this._contextMenuStrip.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this._smallerButton)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._largerButton)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._skipButton)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._recordInPartsButton)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._deleteRecordingButton)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._breakLinesAtCommasButton)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.FlowLayoutPanel _bookFlow; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label _bookLabel; private System.Windows.Forms.Label _chapterLabel; private System.Windows.Forms.FlowLayoutPanel _chapterFlow; private DiscontiguousProgressTrackBar _scriptSlider; private System.Windows.Forms.Label _segmentLabel; private ScriptControl _scriptControl; private System.Windows.Forms.Label _endOfUnitMessage; private System.Windows.Forms.LinkLabel _nextChapterLink; private AudioButtonsControl _audioButtonsControl; private System.Windows.Forms.ToolTip toolTip1; private PeakMeterCtrl _peakMeter; private System.Windows.Forms.ToolTip _instantToolTip; private RecordingDeviceIndicator recordingDeviceButton1; private System.Windows.Forms.Label _lineCountLabel; private L10NSharp.UI.L10NSharpExtender l10NSharpExtender1; private HearThisToolbarButton _breakLinesAtCommasButton; private HearThisToolbarButton _deleteRecordingButton; private FlowLayoutPanel flowLayoutPanel1; private HearThisToolbarButton _recordInPartsButton; private HearThisToolbarButton _skipButton; private HearThisToolbarButton _largerButton; private HearThisToolbarButton _smallerButton; private ContextMenuStrip _contextMenuStrip; private ToolStripMenuItem _mnuShiftClips; } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcdv = Google.Cloud.DataCatalog.V1; using sys = System; namespace Google.Cloud.DataCatalog.V1 { /// <summary>Resource name for the <c>Taxonomy</c> resource.</summary> public sealed partial class TaxonomyName : gax::IResourceName, sys::IEquatable<TaxonomyName> { /// <summary>The possible contents of <see cref="TaxonomyName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </summary> ProjectLocationTaxonomy = 1, } private static gax::PathTemplate s_projectLocationTaxonomy = new gax::PathTemplate("projects/{project}/locations/{location}/taxonomies/{taxonomy}"); /// <summary>Creates a <see cref="TaxonomyName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TaxonomyName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static TaxonomyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TaxonomyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TaxonomyName"/> with the pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TaxonomyName"/> constructed from the provided ids.</returns> public static TaxonomyName FromProjectLocationTaxonomy(string projectId, string locationId, string taxonomyId) => new TaxonomyName(ResourceNameType.ProjectLocationTaxonomy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), taxonomyId: gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TaxonomyName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TaxonomyName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </returns> public static string Format(string projectId, string locationId, string taxonomyId) => FormatProjectLocationTaxonomy(projectId, locationId, taxonomyId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TaxonomyName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TaxonomyName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </returns> public static string FormatProjectLocationTaxonomy(string projectId, string locationId, string taxonomyId) => s_projectLocationTaxonomy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId))); /// <summary>Parses the given resource name string into a new <see cref="TaxonomyName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c></description> /// </item> /// </list> /// </remarks> /// <param name="taxonomyName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TaxonomyName"/> if successful.</returns> public static TaxonomyName Parse(string taxonomyName) => Parse(taxonomyName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TaxonomyName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="taxonomyName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TaxonomyName"/> if successful.</returns> public static TaxonomyName Parse(string taxonomyName, bool allowUnparsed) => TryParse(taxonomyName, allowUnparsed, out TaxonomyName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TaxonomyName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c></description> /// </item> /// </list> /// </remarks> /// <param name="taxonomyName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TaxonomyName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string taxonomyName, out TaxonomyName result) => TryParse(taxonomyName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TaxonomyName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="taxonomyName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TaxonomyName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string taxonomyName, bool allowUnparsed, out TaxonomyName result) { gax::GaxPreconditions.CheckNotNull(taxonomyName, nameof(taxonomyName)); gax::TemplatedResourceName resourceName; if (s_projectLocationTaxonomy.TryParseName(taxonomyName, out resourceName)) { result = FromProjectLocationTaxonomy(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(taxonomyName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TaxonomyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string taxonomyId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; TaxonomyId = taxonomyId; } /// <summary> /// Constructs a new instance of a <see cref="TaxonomyName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> public TaxonomyName(string projectId, string locationId, string taxonomyId) : this(ResourceNameType.ProjectLocationTaxonomy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), taxonomyId: gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Taxonomy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TaxonomyId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationTaxonomy: return s_projectLocationTaxonomy.Expand(ProjectId, LocationId, TaxonomyId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TaxonomyName); /// <inheritdoc/> public bool Equals(TaxonomyName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TaxonomyName a, TaxonomyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TaxonomyName a, TaxonomyName b) => !(a == b); } /// <summary>Resource name for the <c>PolicyTag</c> resource.</summary> public sealed partial class PolicyTagName : gax::IResourceName, sys::IEquatable<PolicyTagName> { /// <summary>The possible contents of <see cref="PolicyTagName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </summary> ProjectLocationTaxonomyPolicyTag = 1, } private static gax::PathTemplate s_projectLocationTaxonomyPolicyTag = new gax::PathTemplate("projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}"); /// <summary>Creates a <see cref="PolicyTagName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="PolicyTagName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static PolicyTagName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new PolicyTagName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="PolicyTagName"/> with the pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="policyTagId">The <c>PolicyTag</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="PolicyTagName"/> constructed from the provided ids.</returns> public static PolicyTagName FromProjectLocationTaxonomyPolicyTag(string projectId, string locationId, string taxonomyId, string policyTagId) => new PolicyTagName(ResourceNameType.ProjectLocationTaxonomyPolicyTag, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), taxonomyId: gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId)), policyTagId: gax::GaxPreconditions.CheckNotNullOrEmpty(policyTagId, nameof(policyTagId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="PolicyTagName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="policyTagId">The <c>PolicyTag</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PolicyTagName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </returns> public static string Format(string projectId, string locationId, string taxonomyId, string policyTagId) => FormatProjectLocationTaxonomyPolicyTag(projectId, locationId, taxonomyId, policyTagId); /// <summary> /// Formats the IDs into the string representation of this <see cref="PolicyTagName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="policyTagId">The <c>PolicyTag</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PolicyTagName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </returns> public static string FormatProjectLocationTaxonomyPolicyTag(string projectId, string locationId, string taxonomyId, string policyTagId) => s_projectLocationTaxonomyPolicyTag.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId)), gax::GaxPreconditions.CheckNotNullOrEmpty(policyTagId, nameof(policyTagId))); /// <summary>Parses the given resource name string into a new <see cref="PolicyTagName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="policyTagName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="PolicyTagName"/> if successful.</returns> public static PolicyTagName Parse(string policyTagName) => Parse(policyTagName, false); /// <summary> /// Parses the given resource name string into a new <see cref="PolicyTagName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="policyTagName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="PolicyTagName"/> if successful.</returns> public static PolicyTagName Parse(string policyTagName, bool allowUnparsed) => TryParse(policyTagName, allowUnparsed, out PolicyTagName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="PolicyTagName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="policyTagName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="PolicyTagName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string policyTagName, out PolicyTagName result) => TryParse(policyTagName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="PolicyTagName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="policyTagName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="PolicyTagName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string policyTagName, bool allowUnparsed, out PolicyTagName result) { gax::GaxPreconditions.CheckNotNull(policyTagName, nameof(policyTagName)); gax::TemplatedResourceName resourceName; if (s_projectLocationTaxonomyPolicyTag.TryParseName(policyTagName, out resourceName)) { result = FromProjectLocationTaxonomyPolicyTag(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(policyTagName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private PolicyTagName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string policyTagId = null, string projectId = null, string taxonomyId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; PolicyTagId = policyTagId; ProjectId = projectId; TaxonomyId = taxonomyId; } /// <summary> /// Constructs a new instance of a <see cref="PolicyTagName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="policyTagId">The <c>PolicyTag</c> ID. Must not be <c>null</c> or empty.</param> public PolicyTagName(string projectId, string locationId, string taxonomyId, string policyTagId) : this(ResourceNameType.ProjectLocationTaxonomyPolicyTag, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), taxonomyId: gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId)), policyTagId: gax::GaxPreconditions.CheckNotNullOrEmpty(policyTagId, nameof(policyTagId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>PolicyTag</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string PolicyTagId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Taxonomy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TaxonomyId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationTaxonomyPolicyTag: return s_projectLocationTaxonomyPolicyTag.Expand(ProjectId, LocationId, TaxonomyId, PolicyTagId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as PolicyTagName); /// <inheritdoc/> public bool Equals(PolicyTagName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(PolicyTagName a, PolicyTagName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(PolicyTagName a, PolicyTagName b) => !(a == b); } public partial class Taxonomy { /// <summary> /// <see cref="gcdv::TaxonomyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::TaxonomyName TaxonomyName { get => string.IsNullOrEmpty(Name) ? null : gcdv::TaxonomyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class PolicyTag { /// <summary> /// <see cref="gcdv::PolicyTagName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::PolicyTagName PolicyTagName { get => string.IsNullOrEmpty(Name) ? null : gcdv::PolicyTagName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateTaxonomyRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteTaxonomyRequest { /// <summary> /// <see cref="gcdv::TaxonomyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::TaxonomyName TaxonomyName { get => string.IsNullOrEmpty(Name) ? null : gcdv::TaxonomyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListTaxonomiesRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetTaxonomyRequest { /// <summary> /// <see cref="gcdv::TaxonomyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::TaxonomyName TaxonomyName { get => string.IsNullOrEmpty(Name) ? null : gcdv::TaxonomyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreatePolicyTagRequest { /// <summary> /// <see cref="TaxonomyName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public TaxonomyName ParentAsTaxonomyName { get => string.IsNullOrEmpty(Parent) ? null : TaxonomyName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeletePolicyTagRequest { /// <summary> /// <see cref="gcdv::PolicyTagName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::PolicyTagName PolicyTagName { get => string.IsNullOrEmpty(Name) ? null : gcdv::PolicyTagName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListPolicyTagsRequest { /// <summary> /// <see cref="TaxonomyName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public TaxonomyName ParentAsTaxonomyName { get => string.IsNullOrEmpty(Parent) ? null : TaxonomyName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetPolicyTagRequest { /// <summary> /// <see cref="gcdv::PolicyTagName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::PolicyTagName PolicyTagName { get => string.IsNullOrEmpty(Name) ? null : gcdv::PolicyTagName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Web; using System.Text.RegularExpressions; using System.Security.Cryptography; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Com.Aspose.Words.Model; namespace Com.Aspose.Words { public struct FileInfo { public string Name; public string MimeType; public byte[] file; } public class ApiInvoker { private static readonly ApiInvoker _instance = new ApiInvoker(); private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>(); public String APP_SID = "appSid"; public String API_KEY = "apiKey"; public static ApiInvoker GetInstance() { return _instance; } public void addDefaultHeader(string key, string value) { defaultHeaderMap.Add(key, value); } public string escapeString(string str) { return str; } public static object deserialize(string json, Type type) { try { if (json.StartsWith("{") || json.StartsWith("[")) return JsonConvert.DeserializeObject(json, type); else { System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(json); return JsonConvert.SerializeXmlNode(xmlDoc); } } catch (IOException e) { throw new ApiException(500, e.Message); } catch (JsonSerializationException jse) { throw new ApiException(500, jse.Message); } catch (System.Xml.XmlException xmle) { throw new ApiException(500, xmle.Message); } } public static object deserialize(byte[] BinaryData, Type type) { try { return new ResponseMessage(BinaryData); } catch (IOException e) { throw new ApiException(500, e.Message); } } private static string Sign(string url, string appKey) { UriBuilder uriBuilder = new UriBuilder(url); // Remove final slash here as it can be added automatically. uriBuilder.Path = uriBuilder.Path.TrimEnd('/'); // Compute the hash. byte[] privateKey = Encoding.UTF8.GetBytes(appKey); HMACSHA1 algorithm = new HMACSHA1(privateKey); byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri); byte[] hash = algorithm.ComputeHash(sequence); string signature = Convert.ToBase64String(hash); // Remove invalid symbols. signature = signature.TrimEnd('='); signature = HttpUtility.UrlEncode(signature); // Convert codes to upper case as they can be updated automatically. signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper()); // Add the signature to query string. return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature); } public static string serialize(object obj) { try { System.Diagnostics.Debug.WriteLine("Serialize:" + JsonConvert.SerializeObject(obj)); return obj != null ? JsonConvert.SerializeObject(obj) : null; } catch (Exception e) { throw new ApiException(500, e.Message); } } public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) { return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; } public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) { return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; } public static void CopyTo(Stream source, Stream destination, int bufferSize = 81920) { byte[] array = new byte[bufferSize]; int count; while ((count = source.Read(array, 0, array.Length)) != 0) { destination.Write(array, 0, count); } } private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) { path = path.Replace("{appSid}", this.defaultHeaderMap[APP_SID]); path = Regex.Replace(path, @"{.+?}", ""); //var b = new StringBuilder(); host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; path = Sign(host + path, this.defaultHeaderMap[API_KEY]); var client = WebRequest.Create(path); client.Method = method; byte[] formData = null; if (formParams.Count > 0) { if (formParams.Count > 1) { string formDataBoundary = String.Format("Somthing"); client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; formData = GetMultipartFormData(formParams, formDataBoundary); } else { client.ContentType = "multipart/form-data"; formData = GetMultipartFormData(formParams, ""); } client.ContentLength = formData.Length; } else { client.ContentType = "application/json"; } foreach (var headerParamsItem in headerParams) { client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); } foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) { client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); } switch (method) { case "GET": break; case "POST": case "PUT": case "DELETE": using (Stream requestStream = client.GetRequestStream()) { if (formData != null) { requestStream.Write(formData, 0, formData.Length); } if (body != null) { var swRequestWriter = new StreamWriter(requestStream); swRequestWriter.Write(serialize(body)); swRequestWriter.Close(); } else System.Diagnostics.Debug.WriteLine("body is null"); } break; default: throw new ApiException(500, "unknown method type " + method); } try { var webResponse = (HttpWebResponse)client.GetResponse(); if (webResponse.StatusCode != HttpStatusCode.OK) { webResponse.Close(); throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); } if (binaryResponse) { using (var memoryStream = new MemoryStream()) { CopyTo(webResponse.GetResponseStream(), memoryStream); return memoryStream.ToArray(); } } else { using (var responseReader = new StreamReader(webResponse.GetResponseStream())) { var responseData = responseReader.ReadToEnd(); return responseData; } } } catch (WebException ex) { var response = ex.Response as HttpWebResponse; int statusCode = 0; if (response != null) { statusCode = (int)response.StatusCode; response.Close(); } throw new ApiException(statusCode, ex.Message); } } private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary) { Stream formDataStream = new System.IO.MemoryStream(); bool needsCLRF = false; if (postParameters.Count > 1) { foreach (var param in postParameters) { // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. // Skip it on the first parameter, add it to subsequent parameters. if (needsCLRF) formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); needsCLRF = true; var fileInfo = (FileInfo)param.Value; if (param.Value is FileInfo) { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", boundary, param.Key, fileInfo.MimeType); formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length); } else { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, param.Key, fileInfo.file); formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } // Add the end of the request. Start with a newline string footer = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); } else { foreach (var param in postParameters) { var fileInfo = (FileInfo)param.Value; if (param.Value is FileInfo) { // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length); } else { string postData = (string)param.Value; formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } } // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return formData; } /** * Overloaded method for returning the path value * For a string value an empty value is returned if the value is null * @param value * @return */ public String ToPathValue(String value) { return (value == null) ? "" : value; } public String ToPathValue(int value) { return value.ToString(); } public String ToPathValue(int? value) { return value.ToString(); } public String ToPathValue(float value) { return value.ToString(); } public String ToPathValue(float? value) { return value.ToString(); } public String ToPathValue(long value) { return value.ToString(); } public String ToPathValue(bool value) { return value.ToString(); } public String ToPathValue(bool? value) { return value.ToString(); } public String ToPathValue(Double value) { return value.ToString(); } public String ToPathValue(DateTime value) { //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); //return format.format(value); return value.ToString(); } } }
// 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.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Extensions; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Input; using osuTK; using osuTK.Graphics; using osuTK.Input; namespace osu.Game.Overlays.KeyBinding { public class KeyBindingRow : Container, IFilterable { private readonly object action; private readonly IEnumerable<Framework.Input.Bindings.KeyBinding> bindings; private const float transition_time = 150; private const float height = 20; private const float padding = 5; private bool matchingFilter; public bool MatchingFilter { get => matchingFilter; set { matchingFilter = value; this.FadeTo(!matchingFilter ? 0 : 1); } } public bool FilteringActive { get; set; } private OsuSpriteText text; private Drawable pressAKey; private FillFlowContainer<KeyButton> buttons; public IEnumerable<string> FilterTerms => bindings.Select(b => b.KeyCombination.ReadableString()).Prepend((string)text.Text); public KeyBindingRow(object action, IEnumerable<Framework.Input.Bindings.KeyBinding> bindings) { this.action = action; this.bindings = bindings; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Masking = true; CornerRadius = padding; } [Resolved] private KeyBindingStore store { get; set; } [BackgroundDependencyLoader] private void load(OsuColour colours) { EdgeEffect = new EdgeEffectParameters { Radius = 2, Colour = colours.YellowDark.Opacity(0), Type = EdgeEffectType.Shadow, Hollow = true, }; Children = new[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, Alpha = 0.6f, }, text = new OsuSpriteText { Text = action.GetDescription(), Margin = new MarginPadding(padding), }, buttons = new FillFlowContainer<KeyButton> { AutoSizeAxes = Axes.Both, Anchor = Anchor.TopRight, Origin = Anchor.TopRight }, pressAKey = new FillFlowContainer { AutoSizeAxes = Axes.Both, Padding = new MarginPadding(padding) { Top = height + padding * 2 }, Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Alpha = 0, Spacing = new Vector2(5), Children = new Drawable[] { new CancelButton { Action = finalise }, new ClearButton { Action = clear }, }, } }; foreach (var b in bindings) buttons.Add(new KeyButton(b)); } public void RestoreDefaults() { int i = 0; foreach (var d in Defaults) { var button = buttons[i++]; button.UpdateKeyCombination(d); store.Update(button.KeyBinding); } } protected override bool OnHover(HoverEvent e) { FadeEdgeEffectTo(1, transition_time, Easing.OutQuint); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { FadeEdgeEffectTo(0, transition_time, Easing.OutQuint); base.OnHoverLost(e); } public override bool AcceptsFocus => bindTarget == null; private KeyButton bindTarget; public bool AllowMainMouseButtons; public IEnumerable<KeyCombination> Defaults; private bool isModifier(Key k) => k < Key.F1; protected override bool OnClick(ClickEvent e) => true; protected override bool OnMouseDown(MouseDownEvent e) { if (!HasFocus || !bindTarget.IsHovered) return base.OnMouseDown(e); if (!AllowMainMouseButtons) { switch (e.Button) { case MouseButton.Left: case MouseButton.Right: return true; } } bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState)); return true; } protected override void OnMouseUp(MouseUpEvent e) { // don't do anything until the last button is released. if (!HasFocus || e.HasAnyButtonPressed) { base.OnMouseUp(e); return; } if (bindTarget.IsHovered) finalise(); else updateBindTarget(); } protected override bool OnScroll(ScrollEvent e) { if (HasFocus) { if (bindTarget.IsHovered) { bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState, e.ScrollDelta)); finalise(); return true; } } return base.OnScroll(e); } protected override bool OnKeyDown(KeyDownEvent e) { if (!HasFocus) return false; bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState)); if (!isModifier(e.Key)) finalise(); return true; } protected override void OnKeyUp(KeyUpEvent e) { if (!HasFocus) { base.OnKeyUp(e); return; } finalise(); } protected override bool OnJoystickPress(JoystickPressEvent e) { if (!HasFocus) return false; bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState)); finalise(); return true; } protected override void OnJoystickRelease(JoystickReleaseEvent e) { if (!HasFocus) { base.OnJoystickRelease(e); return; } finalise(); } private void clear() { bindTarget.UpdateKeyCombination(InputKey.None); finalise(); } private void finalise() { if (bindTarget != null) { store.Update(bindTarget.KeyBinding); bindTarget.IsBinding = false; Schedule(() => { // schedule to ensure we don't instantly get focus back on next OnMouseClick (see AcceptFocus impl.) bindTarget = null; }); } if (HasFocus) GetContainingInputManager().ChangeFocus(null); pressAKey.FadeOut(300, Easing.OutQuint); pressAKey.BypassAutoSizeAxes |= Axes.Y; } protected override void OnFocus(FocusEvent e) { AutoSizeDuration = 500; AutoSizeEasing = Easing.OutQuint; pressAKey.FadeIn(300, Easing.OutQuint); pressAKey.BypassAutoSizeAxes &= ~Axes.Y; updateBindTarget(); base.OnFocus(e); } protected override void OnFocusLost(FocusLostEvent e) { finalise(); base.OnFocusLost(e); } private void updateBindTarget() { if (bindTarget != null) bindTarget.IsBinding = false; bindTarget = buttons.FirstOrDefault(b => b.IsHovered) ?? buttons.FirstOrDefault(); if (bindTarget != null) bindTarget.IsBinding = true; } private class CancelButton : TriangleButton { public CancelButton() { Text = "Cancel"; Size = new Vector2(80, 20); } } private class ClearButton : TriangleButton { public ClearButton() { Text = "Clear"; Size = new Vector2(80, 20); } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Pink; Triangles.ColourDark = colours.PinkDark; Triangles.ColourLight = colours.PinkLight; } } private class KeyButton : Container { public readonly Framework.Input.Bindings.KeyBinding KeyBinding; private readonly Box box; public readonly OsuSpriteText Text; private Color4 hoverColour; private bool isBinding; public bool IsBinding { get => isBinding; set { if (value == isBinding) return; isBinding = value; updateHoverState(); } } public KeyButton(Framework.Input.Bindings.KeyBinding keyBinding) { KeyBinding = keyBinding; Margin = new MarginPadding(padding); // todo: use this in a meaningful way // var isDefault = keyBinding.Action is Enum; Masking = true; CornerRadius = padding; Height = height; AutoSizeAxes = Axes.X; Children = new Drawable[] { new Container { AlwaysPresent = true, Width = 80, Height = height, }, box = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black }, Text = new OsuSpriteText { Font = OsuFont.Numeric.With(size: 10), Margin = new MarginPadding(5), Anchor = Anchor.Centre, Origin = Anchor.Centre, Text = keyBinding.KeyCombination.ReadableString(), }, }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { hoverColour = colours.YellowDark; } protected override bool OnHover(HoverEvent e) { updateHoverState(); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { updateHoverState(); base.OnHoverLost(e); } private void updateHoverState() { if (isBinding) { box.FadeColour(Color4.White, transition_time, Easing.OutQuint); Text.FadeColour(Color4.Black, transition_time, Easing.OutQuint); } else { box.FadeColour(IsHovered ? hoverColour : Color4.Black, transition_time, Easing.OutQuint); Text.FadeColour(IsHovered ? Color4.Black : Color4.White, transition_time, Easing.OutQuint); } } public void UpdateKeyCombination(KeyCombination newCombination) { KeyBinding.KeyCombination = newCombination; Text.Text = KeyBinding.KeyCombination.ReadableString(); } } } }
// // System.Web.CapabilitiesLoader // // Loads data from browscap.ini file provided by Gary J. Keith from // http://www.GaryKeith.com/browsers. Please don't abuse the // site when updating browscap.ini file. Use the update-browscap.exe tool. // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (c) 2003-2009 Novell, Inc. (http://www.novell.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Text.RegularExpressions; namespace HTTP.Net { sealed class BrowserData { static char [] wildchars = new char [] {'*', '?'}; object this_lock = new object (); BrowserData parent; string text; string pattern; #if TARGET_JVM java.util.regex.Pattern regex; #else Regex regex; #endif ListDictionary data; public BrowserData (string pattern) { int norx = pattern.IndexOfAny (wildchars); if (norx == -1) { text = pattern; } else { this.pattern = pattern.Substring (norx); text = pattern.Substring (0, norx); if (text.Length == 0) text = null; this.pattern = this.pattern.Replace (".", "\\."); this.pattern = this.pattern.Replace ("(", "\\("); this.pattern = this.pattern.Replace (")", "\\)"); this.pattern = this.pattern.Replace ("[", "\\["); this.pattern = this.pattern.Replace ("]", "\\]"); this.pattern = this.pattern.Replace ('?', '.'); this.pattern = this.pattern.Replace ("*", ".*"); } } public BrowserData Parent { get { return parent; } set { parent = value; } } public void Add (string key, string value) { if (data == null) data = new ListDictionary (); data.Add (key, value); } public Hashtable GetProperties (Hashtable tbl) { if (parent != null) parent.GetProperties (tbl); if (data ["browser"] != null) { // Last one (most derived) will win. tbl ["browser"] = data ["browser"]; } else if (tbl ["browser"] == null) { // If none so far defined value set to * tbl ["browser"] = "*"; } if (!tbl.ContainsKey ("browsers")) { tbl ["browsers"] = new ArrayList (); } ((ArrayList) tbl ["browsers"]).Add (tbl["browser"]); foreach (string key in data.Keys) tbl [key.ToLower (System.Globalization.CultureInfo.InvariantCulture).Trim ()] = data [key]; return tbl; } public string GetParentName () { return (string)(data.Contains("parent")? data ["parent"] : null); } public string GetAlternateBrowser () { return (pattern == null) ? text : null; } public string GetBrowser () { if (pattern == null) return text; return (string) data ["browser"]; } public bool IsMatch (string expression) { if (expression == null || expression.Length == 0) return false; if (text != null) { if (text [0] != expression [0] || String.Compare (text, 1, expression, 1, text.Length - 1, false, System.Globalization.CultureInfo.InvariantCulture) != 0) { return false; } expression = expression.Substring (text.Length); } if (pattern == null) return expression.Length == 0; lock (this_lock) { if (regex == null) #if TARGET_JVM regex = java.util.regex.Pattern.compile (pattern); #else regex = new Regex (pattern); #endif } #if TARGET_JVM return regex.matcher ((java.lang.CharSequence) (object) expression).matches (); #else return regex.Match (expression).Success; #endif } } sealed class CapabilitiesLoader : MarshalByRefObject { const int userAgentsCacheSize = 3000; static Hashtable defaultCaps; static readonly object lockobj = new object (); #if TARGET_JVM static bool loaded { get { return alldata != null; } set { if (alldata == null) alldata = new ArrayList (); } } const string alldataKey = "System.Web.CapabilitiesLoader.alldata"; static ICollection alldata { get { return (ICollection) AppDomain.CurrentDomain.GetData (alldataKey); } set { AppDomain.CurrentDomain.SetData (alldataKey, value); } } const string userAgentsCacheKey = "System.Web.CapabilitiesLoader.userAgentsCache"; static Hashtable userAgentsCache { get { lock (typeof (CapabilitiesLoader)) { Hashtable agentsCache = (Hashtable) AppDomain.CurrentDomain.GetData (userAgentsCacheKey); if (agentsCache == null) { agentsCache = Hashtable.Synchronized (new Hashtable (userAgentsCacheSize + 10)); AppDomain.CurrentDomain.SetData (userAgentsCacheKey, agentsCache); } return agentsCache; } } } #else static volatile bool loaded; static ICollection alldata; static Hashtable userAgentsCache = Hashtable.Synchronized(new Hashtable(userAgentsCacheSize+10)); #endif CapabilitiesLoader () {} static CapabilitiesLoader () { defaultCaps = new Hashtable (); defaultCaps.Add ("activexcontrols", "False"); defaultCaps.Add ("alpha", "False"); defaultCaps.Add ("aol", "False"); defaultCaps.Add ("aolversion", "0"); defaultCaps.Add ("authenticodeupdate", ""); defaultCaps.Add ("backgroundsounds", "False"); defaultCaps.Add ("beta", "False"); defaultCaps.Add ("browser", "*"); defaultCaps.Add ("browsers", new ArrayList ()); defaultCaps.Add ("cdf", "False"); defaultCaps.Add ("clrversion", "0"); defaultCaps.Add ("cookies", "False"); defaultCaps.Add ("crawler", "False"); defaultCaps.Add ("css", "0"); defaultCaps.Add ("cssversion", "0"); defaultCaps.Add ("ecmascriptversion", "0.0"); defaultCaps.Add ("frames", "False"); defaultCaps.Add ("iframes", "False"); defaultCaps.Add ("isbanned", "False"); defaultCaps.Add ("ismobiledevice", "False"); defaultCaps.Add ("issyndicationreader", "False"); defaultCaps.Add ("javaapplets", "False"); defaultCaps.Add ("javascript", "False"); defaultCaps.Add ("majorver", "0"); defaultCaps.Add ("minorver", "0"); defaultCaps.Add ("msdomversion", "0.0"); defaultCaps.Add ("netclr", "False"); defaultCaps.Add ("platform", "unknown"); defaultCaps.Add ("stripper", "False"); defaultCaps.Add ("supportscss", "False"); defaultCaps.Add ("tables", "False"); defaultCaps.Add ("vbscript", "False"); defaultCaps.Add ("version", "0"); defaultCaps.Add ("w3cdomversion", "0.0"); defaultCaps.Add ("wap", "False"); defaultCaps.Add ("win16", "False"); defaultCaps.Add ("win32", "False"); defaultCaps.Add ("win64", "False"); defaultCaps.Add ("adapters", new Hashtable ()); defaultCaps.Add ("cancombineformsindeck", "False"); defaultCaps.Add ("caninitiatevoicecall", "False"); defaultCaps.Add ("canrenderafterinputorselectelement", "False"); defaultCaps.Add ("canrenderemptyselects", "False"); defaultCaps.Add ("canrenderinputandselectelementstogether", "False"); defaultCaps.Add ("canrendermixedselects", "False"); defaultCaps.Add ("canrenderoneventandprevelementstogether", "False"); defaultCaps.Add ("canrenderpostbackcards", "False"); defaultCaps.Add ("canrendersetvarzerowithmultiselectionlist", "False"); defaultCaps.Add ("cansendmail", "False"); defaultCaps.Add ("defaultsubmitbuttonlimit", "0"); defaultCaps.Add ("gatewayminorversion", "0"); defaultCaps.Add ("gatewaymajorversion", "0"); defaultCaps.Add ("gatewayversion", "None"); defaultCaps.Add ("hasbackbutton", "True"); defaultCaps.Add ("hidesrightalignedmultiselectscrollbars", "False"); defaultCaps.Add ("inputtype", "telephoneKeypad"); defaultCaps.Add ("iscolor", "False"); defaultCaps.Add ("jscriptversion", "0.0"); defaultCaps.Add ("maximumhreflength", "0"); defaultCaps.Add ("maximumrenderedpagesize", "2000"); defaultCaps.Add ("maximumsoftkeylabellength", "5"); defaultCaps.Add ("minorversionstring", "0.0"); defaultCaps.Add ("mobiledevicemanufacturer", "Unknown"); defaultCaps.Add ("mobiledevicemodel", "Unknown"); defaultCaps.Add ("numberofsoftkeys", "0"); defaultCaps.Add ("preferredimagemime", "image/gif"); defaultCaps.Add ("preferredrenderingmime", "text/html"); defaultCaps.Add ("preferredrenderingtype", "html32"); defaultCaps.Add ("preferredrequestencoding", ""); defaultCaps.Add ("preferredresponseencoding", ""); defaultCaps.Add ("rendersbreakbeforewmlselectandinput", "False"); defaultCaps.Add ("rendersbreaksafterhtmllists", "True"); defaultCaps.Add ("rendersbreaksafterwmlanchor", "False"); defaultCaps.Add ("rendersbreaksafterwmlinput", "False"); defaultCaps.Add ("renderswmldoacceptsinline", "True"); defaultCaps.Add ("renderswmlselectsasmenucards", "False"); defaultCaps.Add ("requiredmetatagnamevalue", ""); defaultCaps.Add ("requiresattributecolonsubstitution", "False"); defaultCaps.Add ("requirescontenttypemetatag", "False"); defaultCaps.Add ("requirescontrolstateinsession", "False"); defaultCaps.Add ("requiresdbcscharacter", "False"); defaultCaps.Add ("requireshtmladaptiveerrorreporting", "False"); defaultCaps.Add ("requiresleadingpagebreak", "False"); defaultCaps.Add ("requiresnobreakinformatting", "False"); defaultCaps.Add ("requiresoutputoptimization", "False"); defaultCaps.Add ("requiresphonenumbersasplaintext", "False"); defaultCaps.Add ("requiresspecialviewstateencoding", "False"); defaultCaps.Add ("requiresuniquefilepathsuffix", "False"); defaultCaps.Add ("requiresuniquehtmlcheckboxnames", "False"); defaultCaps.Add ("requiresuniquehtmlinputnames", "False"); defaultCaps.Add ("requiresurlencodedpostfieldvalues", "False"); defaultCaps.Add ("screenbitdepth", "1"); defaultCaps.Add ("screencharactersheight", "6"); defaultCaps.Add ("screencharacterswidth", "12"); defaultCaps.Add ("screenpixelsheight", "72"); defaultCaps.Add ("screenpixelswidth", "96"); defaultCaps.Add ("supportsaccesskeyattribute", "False"); defaultCaps.Add ("supportsbodycolor", "True"); defaultCaps.Add ("supportsbold", "False"); defaultCaps.Add ("supportscachecontrolmetatag", "True"); defaultCaps.Add ("supportscallback", "False"); defaultCaps.Add ("supportsdivalign", "True"); defaultCaps.Add ("supportsdivnowrap", "False"); defaultCaps.Add ("supportsemptystringincookievalue", "False"); defaultCaps.Add ("supportsfontcolor", "True"); defaultCaps.Add ("supportsfontname", "False"); defaultCaps.Add ("supportsfontsize", "False"); defaultCaps.Add ("supportsimagesubmit", "False"); defaultCaps.Add ("supportsimodesymbols", "False"); defaultCaps.Add ("supportsinputistyle", "False"); defaultCaps.Add ("supportsinputmode", "False"); defaultCaps.Add ("supportsitalic", "False"); defaultCaps.Add ("supportsjphonemultimediaattributes", "False"); defaultCaps.Add ("supportsjphonesymbols", "False"); defaultCaps.Add ("supportsquerystringinformaction", "True"); defaultCaps.Add ("supportsredirectwithcookie", "True"); defaultCaps.Add ("supportsselectmultiple", "True"); defaultCaps.Add ("supportsuncheck", "True"); defaultCaps.Add ("supportsxmlhttp", "False"); defaultCaps.Add ("type", "Unknown"); } public static Hashtable GetCapabilities (string userAgent) { Init (); if (userAgent != null) userAgent = userAgent.Trim (); if (alldata == null || userAgent == null || userAgent.Length == 0) return defaultCaps; Hashtable userBrowserCaps = (Hashtable) (userAgentsCache.Contains(userAgent)? userAgentsCache [userAgent] : null); if (userBrowserCaps == null) { foreach (BrowserData bd in alldata) { if (bd.IsMatch (userAgent)) { Hashtable tbl; tbl = new Hashtable (defaultCaps); userBrowserCaps = bd.GetProperties (tbl); break; } } if (userBrowserCaps == null) userBrowserCaps = defaultCaps; lock (lockobj) { if (userAgentsCache.Count >= userAgentsCacheSize) userAgentsCache.Clear (); } userAgentsCache [userAgent] = userBrowserCaps; } return userBrowserCaps; } static void Init () { if (loaded) return; lock (lockobj) { if (loaded) return; #if TARGET_J2EE string filepath = "browscap.ini"; #else string dir = "HttpRuntime.MachineConfigurationDirectory"; string filepath = Path.Combine (dir, "browscap.ini"); if (!File.Exists (filepath)) { // try removing the trailing version directory dir = Path.GetDirectoryName (dir); filepath = Path.Combine (dir, "browscap.ini"); } #endif try { LoadFile (filepath); } catch (Exception) {} loaded = true; } } #if TARGET_J2EE static TextReader GetJavaTextReader(string filename) { try { java.lang.ClassLoader cl = (java.lang.ClassLoader) AppDomain.CurrentDomain.GetData("GH_ContextClassLoader"); if (cl == null) return null; string custom = String.Concat("browscap/", filename); java.io.InputStream inputStream = cl.getResourceAsStream(custom); if (inputStream == null) inputStream = cl.getResourceAsStream(filename); if (inputStream == null) return null; return new StreamReader (new System.Web.J2EE.J2EEUtils.InputStreamWrapper (inputStream)); } catch (Exception e) { return null; } } #endif static void LoadFile (string filename) { #if TARGET_J2EE TextReader input = GetJavaTextReader(filename); if(input == null) return; #else if (!File.Exists (filename)) return; TextReader input = new StreamReader (File.OpenRead (filename)); #endif using (input) { string str; Hashtable allhash = new Hashtable (); int aux = 0; ArrayList browserData = new ArrayList (); while ((str = input.ReadLine ()) != null) { if (str.Length == 0 || str [0] == ';') continue; string userAgent = str.Substring (1, str.Length - 2); BrowserData data = new BrowserData (userAgent); ReadCapabilities (input, data); /* Ignore default browser and file version information */ if (userAgent == "*" || userAgent == "GJK_Browscap_Version") continue; string key = data.GetBrowser (); if (key == null || allhash.ContainsKey (key)) { allhash.Add (aux++, data); browserData.Add (data); } else { allhash.Add (key, data); browserData.Add (data); } } alldata = browserData; foreach (BrowserData data in alldata) { string pname = data.GetParentName (); if (pname == null) continue; data.Parent = (BrowserData) allhash [pname]; } } } static char [] eq = new char []{'='}; static void ReadCapabilities (TextReader input, BrowserData data) { string str, key; string [] keyvalue; while ((str = input.ReadLine ()) != null && str.Length != 0) { keyvalue = str.Split (eq, 2); key = keyvalue[0].ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim(); if (key.Length == 0) continue; data.Add (key, keyvalue [1]); } } } }
using System.Collections.Generic; using Kayak.Http; using NUnit.Framework; using Rhino.Mocks; namespace HttpMock.Unit.Tests { [TestFixture] public class EndpointMatchingRuleTests { [Test] public void urls_match_it_returns_true( ) { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.QueryParams = new Dictionary<string, string>(); var httpRequestHead = new HttpRequestHead { Uri = "test" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead)); } [Test] public void urls_and_methods_the_same_it_returns_true() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "PUT"; requestHandler.QueryParams = new Dictionary<string, string>(); var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "PUT" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead)); } [Test] public void urls_and_methods_differ_it_returns_false() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string>(); var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "PUT" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False); } [Test] public void urls_differ_and_methods_match_it_returns_false() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "pest"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string>(); var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "GET" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False); } [Test] public void urls_and_methods_match_queryparams_differ_it_returns_false() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string> { { "myParam", "one" } }; var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "GET" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False); } [Test] public void urls_and_methods_match_and_queryparams_exist_it_returns_true() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string> { { "myParam", "one" } }; var httpRequestHead = new HttpRequestHead { Uri = "test?oauth_consumer_key=test-api&elvis=alive&moonlandings=faked&myParam=one", Method = "GET" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead)); } [Test] public void urls_and_methods_match_and_queryparams_does_not_exist_it_returns_false() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string> { { "myParam", "one" } }; var httpRequestHead = new HttpRequestHead { Uri = "test?oauth_consumer_key=test-api&elvis=alive&moonlandings=faked", Method = "GET" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False); } [Test] public void urls_and_methods_match_and_no_query_params_are_set_but_request_has_query_params_returns_true() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string> (); var httpRequestHead = new HttpRequestHead { Uri = "test?oauth_consumer_key=test-api&elvis=alive&moonlandings=faked", Method = "GET" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.True); } [Test] public void urls_and_methods_and_queryparams_match_it_returns_true() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string>{{"myParam", "one"}}; var httpRequestHead = new HttpRequestHead { Uri = "test?myParam=one", Method = "GET" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead)); } [Test] public void urls_and_methods_match_headers_differ_it_returns_false() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string>(); requestHandler.RequestHeaders = new Dictionary<string, string> { { "myHeader", "one" } }; var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "GET", Headers = new Dictionary<string, string> { { "myHeader", "two" } } }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False); } [Test] public void urls_and_methods_match_and_headers_match_it_returns_true() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string>(); requestHandler.RequestHeaders = new Dictionary<string, string> { { "myHeader", "one" } }; var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "GET", Headers = new Dictionary<string, string> { { "myHeader", "one" }, { "anotherHeader", "two" } } }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead)); } [Test] public void urls_and_methods_match_and_header_does_not_exist_it_returns_false() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string>(); requestHandler.RequestHeaders = new Dictionary<string, string> { { "myHeader", "one" } }; var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "GET" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False); } [Test] public void should_do_a_case_insensitive_match_on_query_string_parameter_values() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string> { { "myParam", "one" } }; var httpRequestHead = new HttpRequestHead { Uri = "test?myParam=OnE", Method = "GET" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead)); } [Test] public void should_do_a_case_insensitive_match_on_header_names_and_values() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string>(); requestHandler.RequestHeaders = new Dictionary<string, string> { { "myHeader", "one" } }; var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "GET", Headers = new Dictionary<string, string> { { "MYheaDER", "OnE" } } }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead)); } [Test] public void should_match_when_the_query_string_has_a_trailing_ampersand() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "test"; requestHandler.Method = "GET"; requestHandler.QueryParams = new Dictionary<string, string> { { "a", "b" } ,{"c","d"}}; var httpRequestHead = new HttpRequestHead { Uri = "test?a=b&c=d&", Method = "GET" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead)); } [Test] public void should_match_urls_containings_regex_reserved_characters() { var requestHandler = MockRepository.GenerateStub<IRequestHandler>(); requestHandler.Path = "/test()"; requestHandler.QueryParams = new Dictionary<string, string>(); var httpRequestHead = new HttpRequestHead { Uri = "/test()" }; var endpointMatchingRule = new EndpointMatchingRule(); Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead)); } } [TestFixture] public class RequestMatcherTests { [Test] public void Should_match_a_handler() { var expectedRequest = MockRepository.GenerateStub<IRequestHandler>(); expectedRequest.Method = "GET"; expectedRequest.Path = "/path"; expectedRequest.QueryParams = new Dictionary<string, string>(); expectedRequest.Stub(s => s.CanVerifyConstraintsFor("")).IgnoreArguments().Return(true); var requestMatcher = new RequestMatcher(new EndpointMatchingRule()); var requestHandlerList = new List<IRequestHandler>{expectedRequest}; var httpRequestHead = new HttpRequestHead{Method = "GET", Path = "/path/", Uri = "/path"}; var matchedRequest = requestMatcher.Match(httpRequestHead, requestHandlerList); Assert.That(matchedRequest.Path, Is.EqualTo(expectedRequest.Path)); } [Test] public void Should_match_a_specific_handler() { var expectedRequest = MockRepository.GenerateStub<IRequestHandler>(); expectedRequest.Method = "GET"; expectedRequest.Path = "/path/specific"; expectedRequest.QueryParams = new Dictionary<string, string>(); expectedRequest.Stub(s => s.CanVerifyConstraintsFor("")).IgnoreArguments().Return(true); var otherRequest = MockRepository.GenerateStub<IRequestHandler>(); otherRequest.Method = "GET"; otherRequest.Path = "/path/"; otherRequest.QueryParams = new Dictionary<string, string>(); otherRequest.Stub(s => s.CanVerifyConstraintsFor("")).IgnoreArguments().Return(true); var requestMatcher = new RequestMatcher(new EndpointMatchingRule()); var requestHandlerList = new List<IRequestHandler> { otherRequest, expectedRequest }; var httpRequestHead = new HttpRequestHead { Method = "GET", Path = "/path/specific", Uri = "/path/specific" }; var matchedRequest = requestMatcher.Match(httpRequestHead, requestHandlerList); Assert.That(matchedRequest.Path, Is.EqualTo(expectedRequest.Path)); } } }
// 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.Drawing; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Game.Tournament.Models; using osuTK; using osuTK.Graphics; using osuTK.Input; namespace osu.Game.Tournament.Screens.Ladder.Components { public class DrawableTournamentMatch : CompositeDrawable { public readonly TournamentMatch Match; private readonly bool editor; protected readonly FillFlowContainer<DrawableMatchTeam> Flow; private readonly Drawable selectionBox; protected readonly Drawable CurrentMatchSelectionBox; private Bindable<TournamentMatch> globalSelection; [Resolved(CanBeNull = true)] private LadderEditorInfo editorInfo { get; set; } [Resolved(CanBeNull = true)] private LadderInfo ladderInfo { get; set; } public DrawableTournamentMatch(TournamentMatch match, bool editor = false) { Match = match; this.editor = editor; AutoSizeAxes = Axes.Both; Margin = new MarginPadding(5); InternalChildren = new[] { selectionBox = new Container { Scale = new Vector2(1.1f), RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Alpha = 0, Colour = Color4.YellowGreen, Child = new Box { RelativeSizeAxes = Axes.Both } }, CurrentMatchSelectionBox = new Container { Scale = new Vector2(1.05f, 1.1f), RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Alpha = 0, Colour = Color4.White, Child = new Box { RelativeSizeAxes = Axes.Both } }, Flow = new FillFlowContainer<DrawableMatchTeam> { AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Spacing = new Vector2(2) } }; boundReference(match.Team1).BindValueChanged(_ => updateTeams()); boundReference(match.Team2).BindValueChanged(_ => updateTeams()); boundReference(match.Team1Score).BindValueChanged(_ => updateWinConditions()); boundReference(match.Team2Score).BindValueChanged(_ => updateWinConditions()); boundReference(match.Round).BindValueChanged(_ => { updateWinConditions(); Changed?.Invoke(); }); boundReference(match.Completed).BindValueChanged(_ => updateProgression()); boundReference(match.Progression).BindValueChanged(_ => updateProgression()); boundReference(match.LosersProgression).BindValueChanged(_ => updateProgression()); boundReference(match.Losers).BindValueChanged(_ => { updateTeams(); Changed?.Invoke(); }); boundReference(match.Current).BindValueChanged(_ => updateCurrentMatch(), true); boundReference(match.Position).BindValueChanged(pos => { if (!IsDragged) Position = new Vector2(pos.NewValue.X, pos.NewValue.Y); Changed?.Invoke(); }, true); updateTeams(); } /// <summary> /// Fired when somethign changed that requires a ladder redraw. /// </summary> public Action Changed; private readonly List<IUnbindable> refBindables = new List<IUnbindable>(); private T boundReference<T>(T obj) where T : IBindable { obj = (T)obj.GetBoundCopy(); refBindables.Add(obj); return obj; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); foreach (var b in refBindables) b.UnbindAll(); } private void updateCurrentMatch() { if (Match.Current.Value) CurrentMatchSelectionBox.Show(); else CurrentMatchSelectionBox.Hide(); } private bool selected; public bool Selected { get => selected; set { if (value == selected) return; selected = value; if (selected) { selectionBox.Show(); if (editor && editorInfo != null) editorInfo.Selected.Value = Match; else if (ladderInfo != null) ladderInfo.CurrentMatch.Value = Match; } else selectionBox.Hide(); } } private void updateProgression() { if (!Match.Completed.Value) { // ensure we clear any of our teams from our progression. // this is not pretty logic but should suffice for now. if (Match.Progression.Value != null && Match.Progression.Value.Team1.Value == Match.Team1.Value) Match.Progression.Value.Team1.Value = null; if (Match.Progression.Value != null && Match.Progression.Value.Team2.Value == Match.Team2.Value) Match.Progression.Value.Team2.Value = null; if (Match.LosersProgression.Value != null && Match.LosersProgression.Value.Team1.Value == Match.Team1.Value) Match.LosersProgression.Value.Team1.Value = null; if (Match.LosersProgression.Value != null && Match.LosersProgression.Value.Team2.Value == Match.Team2.Value) Match.LosersProgression.Value.Team2.Value = null; } else { transferProgression(Match.Progression?.Value, Match.Winner); transferProgression(Match.LosersProgression?.Value, Match.Loser); } Changed?.Invoke(); } private void transferProgression(TournamentMatch destination, TournamentTeam team) { if (destination == null) return; bool progressionAbove = destination.ID < Match.ID; Bindable<TournamentTeam> destinationTeam; // check for the case where we have already transferred out value if (destination.Team1.Value == team) destinationTeam = destination.Team1; else if (destination.Team2.Value == team) destinationTeam = destination.Team2; else { destinationTeam = progressionAbove ? destination.Team2 : destination.Team1; if (destinationTeam.Value != null) destinationTeam = progressionAbove ? destination.Team1 : destination.Team2; } destinationTeam.Value = team; } private void updateWinConditions() { if (Match.Round.Value == null) return; int instaWinAmount = Match.Round.Value.BestOf.Value / 2; Match.Completed.Value = Match.Round.Value.BestOf.Value > 0 && (Match.Team1Score.Value + Match.Team2Score.Value >= Match.Round.Value.BestOf.Value || Match.Team1Score.Value > instaWinAmount || Match.Team2Score.Value > instaWinAmount); } protected override void LoadComplete() { base.LoadComplete(); updateTeams(); if (editorInfo != null) { globalSelection = editorInfo.Selected.GetBoundCopy(); globalSelection.BindValueChanged(s => { if (s.NewValue != Match) Selected = false; }); } } private void updateTeams() { if (LoadState != LoadState.Loaded) return; // todo: teams may need to be bindable for transitions at a later point. if (Match.Team1.Value == null || Match.Team2.Value == null) Match.CancelMatchStart(); if (Match.ConditionalMatches.Count > 0) { foreach (var conditional in Match.ConditionalMatches) { bool team1Match = conditional.Acronyms.Contains(Match.Team1Acronym); bool team2Match = conditional.Acronyms.Contains(Match.Team2Acronym); if (team1Match && team2Match) Match.Date.Value = conditional.Date.Value; } } Flow.Children = new[] { new DrawableMatchTeam(Match.Team1.Value, Match, Match.Losers.Value), new DrawableMatchTeam(Match.Team2.Value, Match, Match.Losers.Value) }; SchedulerAfterChildren.Add(() => Scheduler.Add(updateProgression)); updateWinConditions(); } protected override bool OnMouseDown(MouseDownEvent e) => e.Button == MouseButton.Left && editorInfo != null; protected override bool OnDragStart(DragStartEvent e) => editorInfo != null; protected override bool OnKeyDown(KeyDownEvent e) { if (Selected && editorInfo != null && e.Key == Key.Delete) { Remove(); return true; } return base.OnKeyDown(e); } protected override bool OnClick(ClickEvent e) { if (editorInfo == null || Match is ConditionalTournamentMatch) return false; Selected = true; return true; } protected override void OnDrag(DragEvent e) { base.OnDrag(e); Selected = true; this.MoveToOffset(e.Delta); var pos = Position; Match.Position.Value = new Point((int)pos.X, (int)pos.Y); } public void Remove() { Selected = false; Match.Progression.Value = null; Match.LosersProgression.Value = null; ladderInfo.Matches.Remove(Match); foreach (var m in ladderInfo.Matches) { if (m.Progression.Value == Match) m.Progression.Value = null; if (m.LosersProgression.Value == Match) m.LosersProgression.Value = 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. using System; using System.Text; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.InteropServices; using Internal.Cryptography; using Internal.Cryptography.Pal.Native; using FILETIME = Internal.Cryptography.Pal.Native.FILETIME; using System.Security.Cryptography; using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle; using System.Security.Cryptography.X509Certificates; using static Interop.Crypt32; namespace Internal.Cryptography.Pal { internal sealed partial class CertificatePal : IDisposable, ICertificatePal { private SafeCertContextHandle _certContext; public static ICertificatePal FromHandle(IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle)); SafeCertContextHandle safeCertContextHandle = Interop.crypt32.CertDuplicateCertificateContext(handle); if (safeCertContextHandle.IsInvalid) throw ErrorCode.HRESULT_INVALID_HANDLE.ToCryptographicException(); CRYPTOAPI_BLOB dataBlob; int cbData = 0; bool deleteKeyContainer = Interop.crypt32.CertGetCertificateContextProperty(safeCertContextHandle, CertContextPropId.CERT_DELETE_KEYSET_PROP_ID, out dataBlob, ref cbData); return new CertificatePal(safeCertContextHandle, deleteKeyContainer); } /// <summary> /// Returns the SafeCertContextHandle. Use this instead of FromHandle() when /// creating another X509Certificate object based on this one to ensure the underlying /// cert context is not released at the wrong time. /// </summary> public static ICertificatePal FromOtherCert(X509Certificate copyFrom) { CertificatePal pal = new CertificatePal((CertificatePal)copyFrom.Pal); return pal; } public IntPtr Handle { get { return _certContext.DangerousGetHandle(); } } public string Issuer { get { return GetIssuerOrSubject(issuer: true); } } public string Subject { get { return GetIssuerOrSubject(issuer: false); } } public byte[] Thumbprint { get { int cbData = 0; if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, null, ref cbData)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException(); byte[] thumbprint = new byte[cbData]; if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, thumbprint, ref cbData)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; return thumbprint; } } public string KeyAlgorithm { get { unsafe { CERT_CONTEXT* pCertContext = _certContext.CertContext; string keyAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId); GC.KeepAlive(this); return keyAlgorithm; } } } public byte[] KeyAlgorithmParameters { get { unsafe { CERT_CONTEXT* pCertContext = _certContext.CertContext; string keyAlgorithmOid = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId); int algId; if (keyAlgorithmOid == Oids.RsaRsa) algId = AlgId.CALG_RSA_KEYX; // Fast-path for the most common case. else algId = Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, keyAlgorithmOid, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId; unsafe { byte* NULL_ASN_TAG = (byte*)0x5; byte[] keyAlgorithmParameters; if (algId == AlgId.CALG_DSS_SIGN && pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.cbData == 0 && pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.pbData == NULL_ASN_TAG) { // // DSS certificates may not have the DSS parameters in the certificate. In this case, we try to build // the certificate chain and propagate the parameters down from the certificate chain. // keyAlgorithmParameters = PropagateKeyAlgorithmParametersFromChain(); } else { keyAlgorithmParameters = pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.ToByteArray(); } GC.KeepAlive(this); return keyAlgorithmParameters; } } } } private byte[] PropagateKeyAlgorithmParametersFromChain() { unsafe { SafeX509ChainHandle certChainContext = null; try { int cbData = 0; if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData)) { CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA(); chainPara.cbSize = sizeof(CERT_CHAIN_PARA); if (!Interop.crypt32.CertGetCertificateChain(ChainEngine.HCCE_CURRENT_USER, _certContext, (FILETIME*)null, SafeCertStoreHandle.InvalidHandle, ref chainPara, CertChainFlags.None, IntPtr.Zero, out certChainContext)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; } byte[] keyAlgorithmParameters = new byte[cbData]; if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, keyAlgorithmParameters, ref cbData)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; return keyAlgorithmParameters; } finally { if (certChainContext != null) certChainContext.Dispose(); } } } public byte[] PublicKeyValue { get { unsafe { CERT_CONTEXT* pCertContext = _certContext.CertContext; byte[] publicKey = pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.ToByteArray(); GC.KeepAlive(this); return publicKey; } } } public byte[] SerialNumber { get { unsafe { CERT_CONTEXT* pCertContext = _certContext.CertContext; byte[] serialNumber = pCertContext->pCertInfo->SerialNumber.ToByteArray(); GC.KeepAlive(this); return serialNumber; } } } public string SignatureAlgorithm { get { unsafe { CERT_CONTEXT* pCertContext = _certContext.CertContext; string signatureAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SignatureAlgorithm.pszObjId); GC.KeepAlive(this); return signatureAlgorithm; } } } public DateTime NotAfter { get { unsafe { CERT_CONTEXT* pCertContext = _certContext.CertContext; DateTime notAfter = pCertContext->pCertInfo->NotAfter.ToDateTime(); GC.KeepAlive(this); return notAfter; } } } public DateTime NotBefore { get { unsafe { CERT_CONTEXT* pCertContext = _certContext.CertContext; DateTime notBefore = pCertContext->pCertInfo->NotBefore.ToDateTime(); GC.KeepAlive(this); return notBefore; } } } public byte[] RawData { get { unsafe { CERT_CONTEXT* pCertContext = _certContext.CertContext; int count = pCertContext->cbCertEncoded; byte[] rawData = new byte[count]; Marshal.Copy((IntPtr)(pCertContext->pbCertEncoded), rawData, 0, count); GC.KeepAlive(this); return rawData; } } } public int Version { get { unsafe { CERT_CONTEXT* pCertContext = _certContext.CertContext; int version = pCertContext->pCertInfo->dwVersion + 1; GC.KeepAlive(this); return version; } } } public bool Archived { get { int uninteresting = 0; bool archivePropertyExists = Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, null, ref uninteresting); return archivePropertyExists; } set { unsafe { CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(0, (byte*)null); CRYPTOAPI_BLOB* pValue = value ? &blob : (CRYPTOAPI_BLOB*)null; if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, CertSetPropertyFlags.None, pValue)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } } } public string FriendlyName { get { int cbData = 0; if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, null, ref cbData)) return string.Empty; StringBuilder sb = new StringBuilder((cbData + 1) / 2); if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, sb, ref cbData)) return string.Empty; return sb.ToString(); } set { string friendlyName = (value == null) ? string.Empty : value; unsafe { IntPtr pFriendlyName = Marshal.StringToHGlobalUni(friendlyName); try { CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(checked(2 * (friendlyName.Length + 1)), (byte*)pFriendlyName); if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, CertSetPropertyFlags.None, &blob)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } finally { Marshal.FreeHGlobal(pFriendlyName); } } } } public X500DistinguishedName SubjectName { get { unsafe { byte[] encodedSubjectName = _certContext.CertContext->pCertInfo->Subject.ToByteArray(); X500DistinguishedName subjectName = new X500DistinguishedName(encodedSubjectName); GC.KeepAlive(this); return subjectName; } } } public X500DistinguishedName IssuerName { get { unsafe { byte[] encodedIssuerName = _certContext.CertContext->pCertInfo->Issuer.ToByteArray(); X500DistinguishedName issuerName = new X500DistinguishedName(encodedIssuerName); GC.KeepAlive(this); return issuerName; } } } public IEnumerable<X509Extension> Extensions { get { unsafe { CERT_INFO* pCertInfo = _certContext.CertContext->pCertInfo; int numExtensions = pCertInfo->cExtension; X509Extension[] extensions = new X509Extension[numExtensions]; for (int i = 0; i < numExtensions; i++) { CERT_EXTENSION* pCertExtension = pCertInfo->rgExtension + i; string oidValue = Marshal.PtrToStringAnsi(pCertExtension->pszObjId); Oid oid = new Oid(oidValue); bool critical = pCertExtension->fCritical != 0; byte[] rawData = pCertExtension->Value.ToByteArray(); extensions[i] = new X509Extension(oid, rawData, critical); } GC.KeepAlive(this); return extensions; } } } public string GetNameInfo(X509NameType nameType, bool forIssuer) { CertNameType certNameType = MapNameType(nameType); CertNameFlags certNameFlags = forIssuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None; CertNameStrTypeAndFlags strType = CertNameStrTypeAndFlags.CERT_X500_NAME_STR | CertNameStrTypeAndFlags.CERT_NAME_STR_REVERSE_FLAG; int cchCount = Interop.crypt32.CertGetNameString(_certContext, certNameType, certNameFlags, ref strType, null, 0); if (cchCount == 0) throw Marshal.GetLastWin32Error().ToCryptographicException(); StringBuilder sb = new StringBuilder(cchCount); if (Interop.crypt32.CertGetNameString(_certContext, certNameType, certNameFlags, ref strType, sb, cchCount) == 0) throw Marshal.GetLastWin32Error().ToCryptographicException(); return sb.ToString(); } public void AppendPrivateKeyInfo(StringBuilder sb) { if (!HasPrivateKey) { return; } // UWP, Windows CNG persisted, and Windows Ephemeral keys will all acknowledge that // a private key exists, but detailed printing is limited to Windows CAPI persisted. // (This is the same thing we do in Unix) sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Private Key]"); #if uap // Similar to the Unix implementation, in UWP merely acknowledge that there -is- a private key. #else CspKeyContainerInfo cspKeyContainerInfo = null; try { CspParameters parameters = GetPrivateKeyCsp(); if (parameters != null) { cspKeyContainerInfo = new CspKeyContainerInfo(parameters); } } // We could not access the key container. Just return. catch (CryptographicException) { } // Ephemeral keys will not have container information. if (cspKeyContainerInfo == null) return; sb.Append(Environment.NewLine + " Key Store: "); sb.Append(cspKeyContainerInfo.MachineKeyStore ? "Machine" : "User"); sb.Append(Environment.NewLine + " Provider Name: "); sb.Append(cspKeyContainerInfo.ProviderName); sb.Append(Environment.NewLine + " Provider type: "); sb.Append(cspKeyContainerInfo.ProviderType); sb.Append(Environment.NewLine + " Key Spec: "); sb.Append(cspKeyContainerInfo.KeyNumber); sb.Append(Environment.NewLine + " Key Container Name: "); sb.Append(cspKeyContainerInfo.KeyContainerName); try { string uniqueKeyContainer = cspKeyContainerInfo.UniqueKeyContainerName; sb.Append(Environment.NewLine + " Unique Key Container Name: "); sb.Append(uniqueKeyContainer); } catch (CryptographicException) { } catch (NotSupportedException) { } bool b = false; try { b = cspKeyContainerInfo.HardwareDevice; sb.Append(Environment.NewLine + " Hardware Device: "); sb.Append(b); } catch (CryptographicException) { } try { b = cspKeyContainerInfo.Removable; sb.Append(Environment.NewLine + " Removable: "); sb.Append(b); } catch (CryptographicException) { } try { b = cspKeyContainerInfo.Protected; sb.Append(Environment.NewLine + " Protected: "); sb.Append(b); } catch (CryptographicException) { } catch (NotSupportedException) { } #endif // #if uap / #else } public void Dispose() { SafeCertContextHandle certContext = _certContext; _certContext = null; if (certContext != null && !certContext.IsInvalid) { certContext.Dispose(); } } internal SafeCertContextHandle CertContext { get { SafeCertContextHandle certContext = Interop.crypt32.CertDuplicateCertificateContext(_certContext.DangerousGetHandle()); GC.KeepAlive(_certContext); return certContext; } } private static CertNameType MapNameType(X509NameType nameType) { switch (nameType) { case X509NameType.SimpleName: return CertNameType.CERT_NAME_SIMPLE_DISPLAY_TYPE; case X509NameType.EmailName: return CertNameType.CERT_NAME_EMAIL_TYPE; case X509NameType.UpnName: return CertNameType.CERT_NAME_UPN_TYPE; case X509NameType.DnsName: case X509NameType.DnsFromAlternativeName: return CertNameType.CERT_NAME_DNS_TYPE; case X509NameType.UrlName: return CertNameType.CERT_NAME_URL_TYPE; default: throw new ArgumentException(SR.Argument_InvalidNameType); } } private string GetIssuerOrSubject(bool issuer) { CertNameFlags flags = issuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None; CertNameStringType stringType = CertNameStringType.CERT_X500_NAME_STR | CertNameStringType.CERT_NAME_STR_REVERSE_FLAG; int cchCount = Interop.crypt32.CertGetNameString(_certContext, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, null, 0); if (cchCount == 0) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; StringBuilder sb = new StringBuilder(cchCount); cchCount = Interop.crypt32.CertGetNameString(_certContext, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, sb, cchCount); if (cchCount == 0) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; return sb.ToString(); } private CertificatePal(CertificatePal copyFrom) { // Use _certContext (instead of CertContext) to keep the original context handle from being // finalized until all cert copies are no longer referenced. _certContext = new SafeCertContextHandle(copyFrom._certContext); } private CertificatePal(SafeCertContextHandle certContext, bool deleteKeyContainer) { if (deleteKeyContainer) { // We need to delete any associated key container upon disposition. Thus, replace the safehandle we got with a safehandle whose // Release() method performs the key container deletion. SafeCertContextHandle oldCertContext = certContext; certContext = Interop.crypt32.CertDuplicateCertificateContextWithKeyContainerDeletion(oldCertContext.DangerousGetHandle()); GC.KeepAlive(oldCertContext); } _certContext = certContext; } } }
namespace Microsoft.Azure.Management.StorSimple8000Series { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Azure.OData; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for VolumesOperations. /// </summary> public static partial class VolumesOperationsExtensions { /// <summary> /// Retrieves all the volumes in a volume container. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static IEnumerable<Volume> ListByVolumeContainer(this IVolumesOperations operations, string deviceName, string volumeContainerName, string resourceGroupName, string managerName) { return operations.ListByVolumeContainerAsync(deviceName, volumeContainerName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Retrieves all the volumes in a volume container. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<Volume>> ListByVolumeContainerAsync(this IVolumesOperations operations, string deviceName, string volumeContainerName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByVolumeContainerWithHttpMessagesAsync(deviceName, volumeContainerName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns the properties of the specified volume name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static Volume Get(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName) { return operations.GetAsync(deviceName, volumeContainerName, volumeName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Returns the properties of the specified volume name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Volume> GetAsync(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(deviceName, volumeContainerName, volumeName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates the volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='parameters'> /// Volume to be created or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static Volume CreateOrUpdate(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, Volume parameters, string resourceGroupName, string managerName) { return operations.CreateOrUpdateAsync(deviceName, volumeContainerName, volumeName, parameters, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='parameters'> /// Volume to be created or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Volume> CreateOrUpdateAsync(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, Volume parameters, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(deviceName, volumeContainerName, volumeName, parameters, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static void Delete(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName) { operations.DeleteAsync(deviceName, volumeContainerName, volumeName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(deviceName, volumeContainerName, volumeName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the metrics for the specified volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static IEnumerable<Metrics> ListMetrics(this IVolumesOperations operations, ODataQuery<MetricFilter> odataQuery, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName) { return operations.ListMetricsAsync(odataQuery, deviceName, volumeContainerName, volumeName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Gets the metrics for the specified volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<Metrics>> ListMetricsAsync(this IVolumesOperations operations, ODataQuery<MetricFilter> odataQuery, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListMetricsWithHttpMessagesAsync(odataQuery, deviceName, volumeContainerName, volumeName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the metric definitions for the specified volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static IEnumerable<MetricDefinition> ListMetricDefinition(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName) { return operations.ListMetricDefinitionAsync(deviceName, volumeContainerName, volumeName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Gets the metric definitions for the specified volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<MetricDefinition>> ListMetricDefinitionAsync(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListMetricDefinitionWithHttpMessagesAsync(deviceName, volumeContainerName, volumeName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieves all the volumes in a device. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static IEnumerable<Volume> ListByDevice(this IVolumesOperations operations, string deviceName, string resourceGroupName, string managerName) { return operations.ListByDeviceAsync(deviceName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Retrieves all the volumes in a device. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<Volume>> ListByDeviceAsync(this IVolumesOperations operations, string deviceName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByDeviceWithHttpMessagesAsync(deviceName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates the volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='parameters'> /// Volume to be created or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static Volume BeginCreateOrUpdate(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, Volume parameters, string resourceGroupName, string managerName) { return operations.BeginCreateOrUpdateAsync(deviceName, volumeContainerName, volumeName, parameters, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='parameters'> /// Volume to be created or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Volume> BeginCreateOrUpdateAsync(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, Volume parameters, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(deviceName, volumeContainerName, volumeName, parameters, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static void BeginDelete(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName) { operations.BeginDeleteAsync(deviceName, volumeContainerName, volumeName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the volume. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='volumeContainerName'> /// The volume container name. /// </param> /// <param name='volumeName'> /// The volume name. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IVolumesOperations operations, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(deviceName, volumeContainerName, volumeName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false); } } }
using UnityEngine; /// <summary> /// The Fighter class is the wrapper which commands all other components /// to make the game object run. /// </summary> public class Fighter : AbstractFighter { enum Facing { Right, Left } #region Inspector fields [SerializeField] FighterInputs m_inputs; [SerializeField] float fwdSpeed = 5.0f; [SerializeField] float backSpeed = 5.0f; [SerializeField] float jumpForce = 100; [SerializeField] Rigidbody2D m_rigid; [SerializeField] AudioSource m_voice; [SerializeField] [Tooltip ("Optional")] AudioSource m_contact; [SerializeField] FighterSoundset m_sounds; [SerializeField] HitManager m_hitManager; [SerializeField] Abstract2DPlatformEngine m_engine; [SerializeField] Animator m_anim; [SerializeField] int m_team; [SerializeField] uint m_maxHealth; [SerializeField] HealthBar m_healthbar; [SerializeField] bool debug; #endregion #region Readonly public int Team { get { return m_team; } } public bool Grounded { get { return m_engine.Grounded; } } public Vector2 LaunchScaleVector { get { return (Vector2) gameObject.transform.right + Vector2.up; } } public int CurrentHealth { get { return m_health; } } Facing face { get { return (opponent.transform.position.x > gameObject.transform.position.x ? Facing.Right : Facing.Left); } } #endregion public bool SoftStun { get { return m_softStun; } set { m_softStun = value; } } public bool CanMove { get { return !(SoftStun || HardStun); } } /// <summary> /// Animator-friendly wrapper for the CanJump setter. /// Will set true for any positive value; false for 0 or negative. /// </summary> /// <param name="value">The value to set</param> public void SetSoftStun (int value) { SoftStun = (value > 0); } bool HardStun { get { return stunTimer > 0; } } int stunTimer; int m_health; bool m_softStun = true; bool hitFlag; bool jumpFlag; SoundGroup contactSounds; float movementInput; float verticalInput; [SerializeField] public GameObject opponent; #region Error messages string NoMovementEngineError { get { return "Could not find movement engine for Fighter script on " + gameObject.name; } } string NoAnimatorError { get { return "Could not find animator for Fighter script on " + gameObject.name; } } #endregion // Start is called just before any of the Update methods is called the first time public void Start () { if (!m_engine) { m_engine = GetComponent<Abstract2DPlatformEngine> (); #if UNITY_EDITOR if (!m_engine) Debug.LogError (NoMovementEngineError); #endif } if (!m_anim) { m_anim = GetComponent<Animator> (); #if UNITY_EDITOR if (!m_anim) Debug.LogError (NoAnimatorError); #endif } m_health = (int) m_maxHealth; } protected override void UpdateFacing () { var rot = gameObject.transform.rotation; if (face == Facing.Right) { rot.y = 0; } else { rot.y = 180; } gameObject.transform.rotation = rot; } protected override void UpdateAttacks () { while (m_hitManager.HasAttack) { var atk = m_hitManager.PullAttack; // If the attack can be jump-cancelled after hitting: // Add an on-connect call back to the attack that will // return CanJump to true if the attack wasn't blocked if (atk.kData.JumpCancelOnHit) { atk.onConnect += (obj, args) => { if (!args.kBlocked) this.SoftStun = true; }; } atk.Connect (this.gameObject); stunTimer = (int) atk.kData.Hitstun + 1; Vector2 scaler = Vector2.up + (face == Facing.Right ? Vector2.right : Vector2.left); m_rigid.velocity = Vector2.Scale (atk.TotalLaunch, scaler); if (atk.TotalDamage > 0) { hitFlag = true; m_health -= atk.TotalDamage; } contactSounds = atk.kData.ContactSounds; m_healthbar.SetHealth ((float) m_health / m_maxHealth); } } protected override void UpdateMovement () { if (CanMove) { movementInput = m_inputs.HorizontalInput; verticalInput = m_inputs.VerticalInput; m_engine.WalkMotion = movementInput * MoveMultiplier (movementInput); jumpFlag = (verticalInput > 0) && m_engine.Grounded; if (m_engine.Grounded && jumpFlag) { m_engine.Jump (jumpForce); } } } protected override void UpdateAnimator () { var fwd = MovingForward (movementInput); var bck = MovingBackward (movementInput); //Debug.Log (fwd ? "Moving forward" : (bck ? "Moving Backward" : "Not Moving")); m_anim.SetBool ("Stunned", HardStun); m_anim.SetBool ("Grounded", m_engine.Grounded); m_anim.SetBool ("MovingForward", fwd); m_anim.SetBool ("MovingBackward", bck); m_anim.SetBool ("Crouch", verticalInput < 0); m_anim.SetBool ("Jump", verticalInput > 0); if (m_inputs.LightInput) { m_anim.SetBool ("Light", true); } else if (m_inputs.MediumInput) { m_anim.SetBool ("Medium", true); } else if (m_inputs.HeavyInput) { m_anim.SetBool ("Heavy", true); } } protected override void UpdateAudio () { if (hitFlag && contactSounds && m_contact) { m_contact.clip = contactSounds.RandomClip; m_contact.pitch = Random.Range (0.95f, 1.2f); m_contact.Play (); } if (hitFlag) { m_voice.clip = m_sounds.randomHit; } else if (jumpFlag) { m_voice.clip = m_sounds.randomJump; } if (jumpFlag || hitFlag) { m_voice.pitch = Random.Range (0.95f, 1.2f); m_voice.Play (); } hitFlag = false; jumpFlag = false; } public void LateUpdate () { if (stunTimer > 0) { stunTimer--; } m_anim.SetBool ("Light", false); m_anim.SetBool ("Medium", false); m_anim.SetBool ("Heavy", false); } float MoveMultiplier (float direction) { if (MovingForward (direction)) { return fwdSpeed; } else if (MovingBackward (direction)) { return backSpeed; } else { return 0; } } bool MovingForward (float movement) { //Debug.Log ("Movement: " + movement); //Debug.Log ("Movement is " + (movement > 0 ? "Positive" : (movement < 0 ? "Negative" : "0"))); return (movement > 0 && face == Facing.Right) || (movement < 0 && face == Facing.Left); } bool MovingBackward (float movement) { return (movement > 0 && face == Facing.Left) || (movement < 0 && face == Facing.Right); } }
using Newtonsoft.Json; using Signum.Engine; using Signum.Engine.Basics; using Signum.Engine.Engine; using Signum.Engine.Maps; using Signum.Engine.PostgresCatalog; using Signum.Engine.SchemaInfoTables; using Signum.Entities; using Signum.Entities.Basics; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; namespace Signum.React.Maps { public static class SchemaMap { public static Func<MapColorProvider[]> GetColorProviders; internal static SchemaMapInfo GetMapInfo() { var getStats = GetRuntimeStats(); var s = Schema.Current; var nodes = (from t in s.Tables.Values where s.IsAllowed(t.Type, true) == null let type = EnumEntity.Extract(t.Type) ?? t.Type select new TableInfo { typeName = TypeLogic.GetCleanName(t.Type), niceName = type.NiceName(), tableName = t.Name.ToString(), columns = t.Columns.Count, entityData = EntityKindCache.GetEntityData(t.Type), entityKind = EntityKindCache.GetEntityKind(t.Type), entityBaseType = GetEntityBaseType(t.Type), @namespace = type.Namespace!, rows = getStats.TryGetC(t.Name)?.rows, total_size_kb = getStats.TryGetC(t.Name)?.total_size_kb, rows_history = t.SystemVersioned?.Let(sv => getStats.TryGetC(sv.TableName)?.rows), total_size_kb_history = t.SystemVersioned?.Let(sv => getStats.TryGetC(sv.TableName)?.total_size_kb), mlistTables = t.TablesMList().Select(ml => new MListTableInfo { niceName = ml.PropertyRoute.PropertyInfo!.NiceName(), tableName = ml.Name.ToString(), rows = getStats.TryGetC(ml.Name)?.rows, total_size_kb = getStats.TryGetC(ml.Name)?.total_size_kb, history_rows = ml.SystemVersioned?.Let(sv => getStats.TryGetC(sv.TableName)?.rows), history_total_size_kb = ml.SystemVersioned?.Let(sv => getStats.TryGetC(sv.TableName)?.total_size_kb), columns = ml.Columns.Count, }).ToList() }).ToList(); var providers = GetColorProviders.GetInvocationListTyped().SelectMany(f => f()).OrderBy(a => a.Order).ToList(); var extraActions = providers.Select(a => a.AddExtra).NotNull().ToList(); if (extraActions.Any()) { foreach (var n in nodes) { foreach (var action in extraActions) action(n); } } var normalEdges = (from t in s.Tables.Values where s.IsAllowed(t.Type, true) == null from kvp in t.DependentTables() where !kvp.Value.IsCollection where s.IsAllowed(kvp.Key.Type, true) == null select new RelationInfo { fromTable = t.Name.ToString(), toTable = kvp.Key.Name.ToString(), lite = kvp.Value.IsLite, nullable = kvp.Value.IsNullable, isVirtualMListBackReference = VirtualMList.RegisteredVirtualMLists.TryGetC(kvp.Key.Type)?.Values.Any(a => a.BackReferenceRoute.Equals(kvp.Value.PropertyRoute)) ?? false }).ToList(); var mlistEdges = (from t in s.Tables.Values where s.IsAllowed(t.Type, true) == null from tm in t.TablesMList() from kvp in tm.GetTables() where s.IsAllowed(kvp.Key.Type, true) == null select new RelationInfo { fromTable = tm.Name.ToString(), toTable = kvp.Key.Name.ToString(), lite = kvp.Value.IsLite, nullable = kvp.Value.IsNullable }).ToList(); return new SchemaMapInfo { tables = nodes, relations = normalEdges.Concat(mlistEdges).ToList(), providers = providers.Select(p => new MapColorProviderInfo { name = p.Name, niceName = p.NiceName }).ToList() }; } static EntityBaseType GetEntityBaseType(Type type) { if (type.IsEnumEntity()) return EntityBaseType.EnumEntity; if (typeof(Symbol).IsAssignableFrom(type)) return EntityBaseType.Symbol; if (typeof(SemiSymbol).IsAssignableFrom(type)) return EntityBaseType.SemiSymbol; if (EntityKindCache.GetEntityKind(type) == EntityKind.Part) return EntityBaseType.Part; return EntityBaseType.Entity; } static Dictionary<ObjectName, RuntimeStats> GetRuntimeStats() { var isPostgres = Schema.Current.Settings.IsPostgres; Dictionary<ObjectName, RuntimeStats> result = new Dictionary<ObjectName, RuntimeStats>(); foreach (var dbName in Schema.Current.DatabaseNames()) { using (Administrator.OverrideDatabaseInSysViews(dbName)) { if (isPostgres) { var dic = (from ns in Database.View<PgNamespace>() where !PostgresCatalogSchema.systemSchemas.Contains(ns.nspname) from t in ns.Tables() select KeyValuePair.Create(new ObjectName(new SchemaName(dbName, ns.nspname, isPostgres), t.relname, isPostgres), new RuntimeStats { rows = t.reltuples, total_size_kb = PostgresFunctions.pg_total_relation_size(t.oid) / 1024 })).ToDictionary(); result.AddRange(dic); } else { var dic = Database.View<SysTables>().Select(t => KeyValuePair.Create( new ObjectName(new SchemaName(dbName, t.Schema().name, isPostgres), t.name, isPostgres), new RuntimeStats { rows = ((int?)t.Indices().SingleOrDefault(a => a.type == (int)DiffIndexType.Clustered).Partition().rows) ?? 0, total_size_kb = t.Indices().SelectMany(i => i.Partition().AllocationUnits()).Sum(a => a.total_pages) * 8 })).ToDictionary(); result.AddRange(dic); } } } return result; } public class RuntimeStats { public int rows; public int total_size_kb; } } public class MapColorProvider { public string Name; public string NiceName; public Action<TableInfo> AddExtra; public decimal Order { get; set; } } public class TableInfo { public string typeName; public string niceName; public string tableName; public EntityKind entityKind; public EntityData entityData; public EntityBaseType entityBaseType; public string @namespace; public int columns; public int? rows; public int? total_size_kb; public int? rows_history; public int? total_size_kb_history; public Dictionary<string, object?> extra = new Dictionary<string, object?>(); public List<MListTableInfo> mlistTables; } public enum EntityBaseType { EnumEntity, Symbol, SemiSymbol, Entity, MList, Part, } public class MListTableInfo { public string niceName; public string tableName; public int columns; public int? rows; public int? total_size_kb; public int? history_rows; public int? history_total_size_kb; public Dictionary<string, object?> extra = new Dictionary<string, object?>(); } public class RelationInfo { public string fromTable; public string toTable; public bool nullable; public bool lite; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool isVirtualMListBackReference; } public class MapColorProviderInfo { public string name; public string niceName; } public class SchemaMapInfo { public List<TableInfo> tables; public List<RelationInfo> relations; public List<MapColorProviderInfo> providers; } }
using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Alexa.NET.Management.Api; using Alexa.NET.Management.Package; using Newtonsoft.Json; using Xunit; namespace Alexa.NET.Management.Tests { public class PackageTests { private const string UploadPath = "https://aws.amazon.com/someabsolutepath"; [Fact] public void PackageInClientNotNull() { var client = new ManagementApi("xxx"); Assert.NotNull(client.Package); } [Fact] public async Task UploadUrlWorksAsExpected() { var management = new ManagementApi("xxx", new ActionHandler(req => { Assert.Equal(HttpMethod.Post, req.Method); Assert.Equal("/v1/skills/uploads", req.RequestUri.PathAndQuery); },Utility.ExampleFileContent<PackageUploadMetadata>("PackageUpload.json"), HttpStatusCode.Created)); var response = await management.Package.CreateUpload(); Assert.Equal(UploadPath,response.UploadUri.ToString()); Assert.Equal("2018-10-11T19:28:34.5250000Z",response.ExpiresAt.ToUniversalTime().ToString("O")); } [Fact] public async Task UploadUrlThrowsOnNon201() { var management = new ManagementApi("xxx", new ActionHandler(req => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)))); await Assert.ThrowsAsync<InvalidOperationException>(() => management.Package.CreateUpload()); } [Fact] public async Task CreatePackageWorksAsExpected() { var management = new ManagementApi("xxx", new ActionHandler(async req => { Assert.Equal(HttpMethod.Post, req.Method); Assert.Equal("/v1/skills/imports", req.RequestUri.PathAndQuery); var requestObject = JsonConvert.DeserializeObject<CreatePackageRequest>(await req.Content.ReadAsStringAsync()); Assert.Equal("xxx",requestObject.VendorId); Assert.Equal(UploadPath, requestObject.Location); var message = new HttpResponseMessage(HttpStatusCode.Accepted); message.Headers.Location = new Uri("/v1/skills/imports/importId",UriKind.Relative); return message; })); var response = await management.Package.CreatePackage("xxx",UploadPath); Assert.NotNull(response); Assert.Equal("/v1/skills/imports/importId",response.ToString()); } [Fact] public async Task CreatePackageErrorsOnNon202() { var management = new ManagementApi("xxx", new ActionHandler(req => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)))); await Assert.ThrowsAsync<InvalidOperationException>(() => management.Package.CreatePackage("xxx",UploadPath)); } [Fact] public async Task CreatePackageThrowsOnNullVendorId() { var management = new ManagementApi("xxx"); await Assert.ThrowsAsync<ArgumentNullException>(() => management.Package.CreatePackage(null, "test")); } [Fact] public async Task CreatePackageThrowsOnNullLocation() { var management = new ManagementApi("xxx"); await Assert.ThrowsAsync<ArgumentNullException>(() => management.Package.CreatePackage("vendor", null)); } [Fact] public async Task CreatePackageThrowsOnNullRequest() { var management = new ManagementApi("xxx"); await Assert.ThrowsAsync<ArgumentNullException>(() => management.Package.CreatePackage(null)); } [Fact] public async Task CreateSkillPackageThrowsOnNullSkill() { var management = new ManagementApi("xxx"); await Assert.ThrowsAsync<ArgumentNullException>(() => management.Package.CreateSkillPackage(null,"location")); } [Fact] public async Task CreateSkillPackageThrowsOnNullLocation() { var management = new ManagementApi("xxx"); await Assert.ThrowsAsync<ArgumentNullException>(() => management.Package.CreateSkillPackage("skillid", "")); } [Fact] public async Task CreateSkillPackageCallsCorrectly() { var management = new ManagementApi("xxx", new ActionHandler(async req => { Assert.Equal(HttpMethod.Post, req.Method); Assert.Equal("/v1/skills/skillid/imports", req.RequestUri.PathAndQuery); var requestObject = JsonConvert.DeserializeObject<CreateSkillPackageRequest>(await req.Content.ReadAsStringAsync()); Assert.Equal(UploadPath, requestObject.Location); var message = new HttpResponseMessage(HttpStatusCode.Accepted); message.Headers.Location = new Uri("/v1/skills/skillid/imports/importId", UriKind.Relative); return message; })); var response = await management.Package.CreateSkillPackage("skillid", UploadPath); Assert.NotNull(response); Assert.Equal("/v1/skills/skillid/imports/importId", response.ToString()); } [Fact] public void ImportStatusDeserializesCorrectly() { var importStatus = Utility.ExampleFileContent<ImportStatusResponse>("ImportStatus.json"); Assert.True(Utility.CompareJson(importStatus, "ImportStatus.json")); Assert.Equal(ImportStatus.FAILED,importStatus.Status); Assert.NotNull(importStatus.Skill); var skill = importStatus.Skill; Assert.Equal("abc123",skill.SkillId); Assert.Equal("eTagAbc!23",skill.ETag); Assert.Single(skill.Resources); var resource = skill.Resources.First(); Assert.Equal("resourceId",resource.Name); Assert.Equal(ResourceStatus.SKIPPED,resource.Status); Assert.Single(resource.Errors); Assert.Single(resource.Warnings); Assert.Equal("error 1",resource.Errors.First().Message); Assert.Equal("warning 1",resource.Warnings.First().Message); } [Fact] public async Task ImportStatusThrowsOnNullImportId() { var managementApi = new ManagementApi("xxx"); await Assert.ThrowsAsync<ArgumentNullException>(() => managementApi.Package.SkillPackageStatus(null)); } [Fact] public async Task CreateExportRequestCallsCorrectly() { var management = new ManagementApi("xxx", new ActionHandler(req => { Assert.Equal(HttpMethod.Post, req.Method); Assert.Equal("/v1/skills/skillid/stages/development/exports", req.RequestUri.PathAndQuery); var message = new HttpResponseMessage(HttpStatusCode.Accepted); message.Headers.Location = new Uri("/v1/skills/skillid/imports/importId", UriKind.Relative); return Task.FromResult(message); })); var response = await management.Package.CreateExportRequest("skillid", SkillStage.Development); Assert.NotNull(response); Assert.Equal("/v1/skills/skillid/imports/importId", response.ToString()); } [Fact] public async Task CreateExportRequestThrowsNullSkillId() { var management = new ManagementApi("xxx"); await Assert.ThrowsAsync<ArgumentNullException>(() => management.Package.CreateExportRequest(null, SkillStage.Development)); } [Fact] public async Task ExportStatusCallsCorrectly() { var management = new ManagementApi("xxx", new ActionHandler(req => { Assert.Equal(HttpMethod.Get, req.Method); Assert.Equal("/v1/skills/exports/exportid", req.RequestUri.PathAndQuery); },Utility.ExampleFileContent<ExportStatusResponse>("ExportStatusResponse.json"))); var response = await management.Package.ExportStatus("exportid"); Assert.NotNull(response); Assert.Equal(ExportStatus.FAILED,response.Status); } [Fact] public async Task ExportStatusThrowsNullSkillId() { var management = new ManagementApi("xxx"); await Assert.ThrowsAsync<ArgumentNullException>(() => management.Package.ExportStatus(null)); } } }
// 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 System.Linq; using System.Threading.Tasks; using DotNetScaffolder.Domain.Services.WebApi.IdentityServer.Controllers.Consent; using IdentityServer4.Events; using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Quickstart.UI; using IdentityServer4.Services; using IdentityServer4.Stores; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace DotNetScaffolder.Domain.Services.WebApi.IdentityServer.Controllers.Device { [Authorize] [SecurityHeaders] public class DeviceController : Controller { private readonly IDeviceFlowInteractionService _interaction; private readonly IClientStore _clientStore; private readonly IResourceStore _resourceStore; private readonly IEventService _events; private readonly ILogger<DeviceController> _logger; public DeviceController( IDeviceFlowInteractionService interaction, IClientStore clientStore, IResourceStore resourceStore, IEventService eventService, ILogger<DeviceController> logger) { _interaction = interaction; _clientStore = clientStore; _resourceStore = resourceStore; _events = eventService; _logger = logger; } [HttpGet] public async Task<IActionResult> Index([FromQuery(Name = "user_code")] string userCode) { if (string.IsNullOrWhiteSpace(userCode)) return View("UserCodeCapture"); var vm = await BuildViewModelAsync(userCode); if (vm == null) return View("Error"); vm.ConfirmUserCode = true; return View("UserCodeConfirmation", vm); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> UserCodeCapture(string userCode) { var vm = await BuildViewModelAsync(userCode); if (vm == null) return View("Error"); return View("UserCodeConfirmation", vm); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Callback(DeviceAuthorizationInputModel model) { if (model == null) throw new ArgumentNullException(nameof(model)); var result = await ProcessConsent(model); if (result.HasValidationError) return View("Error"); return View("Success"); } private async Task<ProcessConsentResult> ProcessConsent(DeviceAuthorizationInputModel model) { var result = new ProcessConsentResult(); var request = await _interaction.GetAuthorizationContextAsync(model.UserCode); if (request == null) return result; ConsentResponse grantedConsent = null; // user clicked 'no' - send back the standard 'access_denied' response if (model.Button == "no") { grantedConsent = ConsentResponse.Denied; // emit event await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested)); } // user clicked 'yes' - validate the data else if (model.Button == "yes") { // if the user consented to some scope, build the response model if (model.ScopesConsented != null && model.ScopesConsented.Any()) { var scopes = model.ScopesConsented; if (ConsentOptions.EnableOfflineAccess == false) { scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess); } grantedConsent = new ConsentResponse { RememberConsent = model.RememberConsent, ScopesConsented = scopes.ToArray() }; // emit event await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent)); } else { result.ValidationError = ConsentOptions.MustChooseOneErrorMessage; } } else { result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage; } if (grantedConsent != null) { // communicate outcome of consent back to identityserver await _interaction.HandleRequestAsync(model.UserCode, grantedConsent); // indicate that's it ok to redirect back to authorization endpoint result.RedirectUri = model.ReturnUrl; result.ClientId = request.ClientId; } else { // we need to redisplay the consent UI result.ViewModel = await BuildViewModelAsync(model.UserCode, model); } return result; } private async Task<DeviceAuthorizationViewModel> BuildViewModelAsync(string userCode, DeviceAuthorizationInputModel model = null) { var request = await _interaction.GetAuthorizationContextAsync(userCode); if (request != null) { var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId); if (client != null) { var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested); if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any())) { return CreateConsentViewModel(userCode, model, client, resources); } else { _logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y)); } } else { _logger.LogError("Invalid client id: {0}", request.ClientId); } } return null; } private DeviceAuthorizationViewModel CreateConsentViewModel(string userCode, DeviceAuthorizationInputModel model, Client client, Resources resources) { var vm = new DeviceAuthorizationViewModel { UserCode = userCode, RememberConsent = model?.RememberConsent ?? true, ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(), ClientName = client.ClientName ?? client.ClientId, ClientUrl = client.ClientUri, ClientLogoUrl = client.LogoUri, AllowRememberConsent = client.AllowRememberConsent }; vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess) { vm.ResourceScopes = vm.ResourceScopes.Union(new[] { GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null) }); } return vm; } private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check) { return new ScopeViewModel { Name = identity.Name, DisplayName = identity.DisplayName, Description = identity.Description, Emphasize = identity.Emphasize, Required = identity.Required, Checked = check || identity.Required }; } public ScopeViewModel CreateScopeViewModel(Scope scope, bool check) { return new ScopeViewModel { Name = scope.Name, DisplayName = scope.DisplayName, Description = scope.Description, Emphasize = scope.Emphasize, Required = scope.Required, Checked = check || scope.Required }; } private ScopeViewModel GetOfflineAccessScope(bool check) { return new ScopeViewModel { Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess, DisplayName = ConsentOptions.OfflineAccessDisplayName, Description = ConsentOptions.OfflineAccessDescription, Emphasize = true, Checked = check }; } } }
#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; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Web; using MbUnit.Framework; using Moq; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Routing; using Subtext.Framework.Syndication; using Subtext.Framework.Web.HttpModules; using UnitTests.Subtext.Framework.Util; namespace UnitTests.Subtext.Framework.Syndication { /// <summary> /// Unit tests for the RSSWriter classes. /// </summary> [TestFixture] public class RssWriterTests : SyndicationTestBase { [RowTest] [Row("Subtext.Web", "", "http://localhost/Subtext.Web/images/RSS2Image.gif")] [Row("Subtext.Web", "blog", "http://localhost/Subtext.Web/images/RSS2Image.gif")] [Row("", "", "http://localhost/images/RSS2Image.gif")] [Row("", "blog", "http://localhost/images/RSS2Image.gif")] [RollBack2] public void RssImageUrlConcatenatedProperly(string application, string subfolder, string expected) { UnitTestHelper.SetHttpContextWithBlogRequest("localhost", subfolder, application); var blogInfo = new Blog(); BlogRequest.Current.Blog = blogInfo; blogInfo.Host = "localhost"; blogInfo.Subfolder = subfolder; blogInfo.Title = "My Blog Is Better Than Yours"; blogInfo.Email = "Subtext@example.com"; blogInfo.RFC3229DeltaEncodingEnabled = true; HttpContext.Current.Items.Add("BlogInfo-", blogInfo); var subtextContext = new Mock<ISubtextContext>(); subtextContext.FakeSyndicationContext(blogInfo, "/", application, null); Mock<HttpContextBase> httpContext = Mock.Get(subtextContext.Object.RequestContext.HttpContext); httpContext.Setup(h => h.Request.ApplicationPath).Returns(application); var writer = new RssWriter(new StringWriter(), new List<Entry>(), DateTime.UtcNow, false, subtextContext.Object); Uri rssImageUrl = writer.GetRssImage(); Assert.AreEqual(expected, rssImageUrl.ToString(), "not the expected url."); } /// <summary> /// Tests writing a simple RSS feed. /// </summary> [Test] [RollBack2] public void RssWriterProducesValidFeed() { UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "", "Subtext.Web"); var blogInfo = new Blog(); BlogRequest.Current.Blog = blogInfo; blogInfo.Host = "localhost"; blogInfo.Title = "My Blog Is Better Than Yours"; blogInfo.Email = "Subtext@example.com"; blogInfo.RFC3229DeltaEncodingEnabled = true; blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId; blogInfo.ShowEmailAddressInRss = true; blogInfo.TrackbacksEnabled = true; HttpContext.Current.Items.Add("BlogInfo-", blogInfo); var entries = new List<Entry>(CreateSomeEntries()); entries[0].Categories.AddRange(new[] { "Category1", "Category2" }); entries[0].Email = "nobody@example.com"; entries[2].Categories.Add("Category 3"); var enc = new Enclosure(); enc.Url = "http://perseus.franklins.net/hanselminutes_0107.mp3"; enc.Title = "<Digital Photography Explained (for Geeks) with Aaron Hockley/>"; enc.Size = 26707573; enc.MimeType = "audio/mp3"; enc.AddToFeed = true; entries[2].Enclosure = enc; var enc1 = new Enclosure(); enc1.Url = "http://perseus.franklins.net/hanselminutes_0107.mp3"; enc1.Title = "<Digital Photography Explained (for Geeks) with Aaron Hockley/>"; enc1.Size = 26707573; enc1.MimeType = "audio/mp3"; enc1.AddToFeed = false; entries[3].Enclosure = enc1; var subtextContext = new Mock<ISubtextContext>(); subtextContext.FakeSyndicationContext(blogInfo, "/", "Subtext.Web", null); Mock<BlogUrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper); urlHelper.Setup(u => u.BlogUrl()).Returns("/Subtext.Web/"); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns<Entry>( e => "/Subtext.Web/whatever/" + e.Id + ".aspx"); var writer = new RssWriter(new StringWriter(), entries, NullValue.NullDateTime, false, subtextContext.Object); string expected = @"<rss version=""2.0"" " + @"xmlns:dc=""http://purl.org/dc/elements/1.1/"" " + @"xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" " + @"xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" " + @"xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" " + @"xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" " + @"xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine + indent() + @"<channel>" + Environment.NewLine + indent(2) + @"<title>My Blog Is Better Than Yours</title>" + Environment.NewLine + indent(2) + @"<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(2) + @"<description />" + Environment.NewLine + indent(2) + @"<language>en-US</language>" + Environment.NewLine + indent(2) + @"<copyright>Subtext Weblog</copyright>" + Environment.NewLine + indent(2) + @"<managingEditor>Subtext@example.com</managingEditor>" + Environment.NewLine + indent(2) + @"<generator>{0}</generator>" + Environment.NewLine + indent(2) + @"<image>" + Environment.NewLine + indent(3) + @"<title>My Blog Is Better Than Yours</title>" + Environment.NewLine + indent(3) + @"<url>http://localhost/Subtext.Web/images/RSS2Image.gif</url>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(3) + @"<width>77</width>" + Environment.NewLine + indent(3) + @"<height>60</height>" + Environment.NewLine + indent(2) + @"</image>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>Title of 1001.</title>" + Environment.NewLine + indent(3) + @"<category>Category1</category>" + Environment.NewLine + indent(3) + @"<category>Category2</category>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever/1001.aspx</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1001&lt;img src=""http://localhost/Subtext.Web/aggbug/1001.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever/1001.aspx</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Sun, 23 Feb 1975 08:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever/1001.aspx#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1001.aspx</wfw:commentRss>" + Environment.NewLine + indent(3) + @"<trackback:ping>http://localhost/Subtext.Web/services/trackbacks/1001.aspx</trackback:ping>" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>Title of 1002.</title>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever/1002.aspx</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1002&lt;img src=""http://localhost/Subtext.Web/aggbug/1002.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever/1002.aspx</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Fri, 25 Jun 1976 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever/1002.aspx#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1002.aspx</wfw:commentRss>" + Environment.NewLine + indent(3) + @"<trackback:ping>http://localhost/Subtext.Web/services/trackbacks/1002.aspx</trackback:ping>" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>Title of 1003.</title>" + Environment.NewLine + indent(3) + @"<category>Category 3</category>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever/1003.aspx</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1003&lt;img src=""http://localhost/Subtext.Web/aggbug/1003.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever/1003.aspx</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Tue, 16 Oct 1979 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever/1003.aspx#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1003.aspx</wfw:commentRss>" + Environment.NewLine + indent(3) + @"<trackback:ping>http://localhost/Subtext.Web/services/trackbacks/1003.aspx</trackback:ping>" + Environment.NewLine + indent(3) + @"<enclosure url=""http://perseus.franklins.net/hanselminutes_0107.mp3"" length=""26707573"" type=""audio/mp3"" />" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>Title of 1004.</title>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever/1004.aspx</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1004&lt;img src=""http://localhost/Subtext.Web/aggbug/1004.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever/1004.aspx</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Mon, 14 Jul 2003 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever/1004.aspx#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1004.aspx</wfw:commentRss>" + Environment.NewLine + indent(3) + @"<trackback:ping>http://localhost/Subtext.Web/services/trackbacks/1004.aspx</trackback:ping>" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent() + @"</channel>" + Environment.NewLine + @"</rss>"; expected = string.Format(expected, VersionInfo.VersionDisplayText); UnitTestHelper.AssertStringsEqualCharacterByCharacter(expected, writer.Xml); } /// <summary> /// Makes sure the RSS Writer can write the delta of a feed based /// on the RFC3229 with feeds /// <see href="http://bobwyman.pubsub.com/main/2004/09/using_rfc3229_w.html"/>. /// </summary> [Test] [RollBack2] public void RssWriterHandlesRFC3229DeltaEncoding() { UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "", "Subtext.Web"); var blogInfo = new Blog(); BlogRequest.Current.Blog = blogInfo; blogInfo.Host = "localhost"; blogInfo.Subfolder = ""; blogInfo.Email = "Subtext@example.com"; blogInfo.RFC3229DeltaEncodingEnabled = true; blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId; HttpContext.Current.Items.Add("BlogInfo-", blogInfo); var entries = new List<Entry>(CreateSomeEntriesDescending()); var subtextContext = new Mock<ISubtextContext>(); subtextContext.FakeSyndicationContext(blogInfo, "/", "Subtext.Web", null); Mock<BlogUrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper); urlHelper.Setup(u => u.BlogUrl()).Returns("/Subtext.Web/"); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/Subtext.Web/whatever"); // Tell the write we already received 1002 published 6/25/1976. var writer = new RssWriter(new StringWriter(), entries, DateTime.ParseExact("06/25/1976", "MM/dd/yyyy", CultureInfo.InvariantCulture), true, subtextContext.Object); // We only expect 1003 and 1004 string expected = @"<rss version=""2.0"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine + indent() + "<channel>" + Environment.NewLine + indent(2) + "<title />" + Environment.NewLine + indent(2) + "<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(2) + "<description />" + Environment.NewLine + indent(2) + "<language>en-US</language>" + Environment.NewLine + indent(2) + "<copyright>Subtext Weblog</copyright>" + Environment.NewLine + indent(2) + "<generator>{0}</generator>" + Environment.NewLine + indent(2) + "<image>" + Environment.NewLine + indent(3) + "<title />" + Environment.NewLine + indent(3) + "<url>http://localhost/Subtext.Web/images/RSS2Image.gif</url>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(3) + "<width>77</width>" + Environment.NewLine + indent(3) + "<height>60</height>" + Environment.NewLine + indent(2) + "</image>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>Title of 1004.</title>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1004&lt;img src=""http://localhost/Subtext.Web/aggbug/1004.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Mon, 14 Jul 2003 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1004.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + "<title>Title of 1003.</title>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/whatever</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1003&lt;img src=""http://localhost/Subtext.Web/aggbug/1003.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/whatever</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Tue, 16 Oct 1979 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + @"<comments>http://localhost/Subtext.Web/whatever#feedback</comments>" + Environment.NewLine + indent(3) + @"<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1003.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + "</item>" + Environment.NewLine + indent() + "</channel>" + Environment.NewLine + "</rss>"; expected = string.Format(expected, VersionInfo.VersionDisplayText); Assert.AreEqual(expected, writer.Xml); Assert.AreEqual(DateTime.ParseExact("06/25/1976", "MM/dd/yyyy", CultureInfo.InvariantCulture), writer.DateLastViewedFeedItemPublishedUtc, "The Item ID Last Viewed (according to If-None-Since is wrong."); Assert.AreEqual(DateTime.ParseExact("07/14/2003", "MM/dd/yyyy", CultureInfo.InvariantCulture), writer.LatestPublishDateUtc, "The Latest Feed Item ID sent to the client is wrong."); } /// <summary> /// Tests writing a simple RSS feed. /// </summary> [Test] [RollBack2] public void RssWriterSendsWholeFeedWhenRFC3229Disabled() { UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "", "Subtext.Web"); var blogInfo = new Blog(); BlogRequest.Current.Blog = blogInfo; blogInfo.Host = "localhost"; blogInfo.Subfolder = ""; blogInfo.Email = "Subtext@example.com"; blogInfo.RFC3229DeltaEncodingEnabled = false; blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId; HttpContext.Current.Items.Add("BlogInfo-", blogInfo); var entries = new List<Entry>(CreateSomeEntriesDescending()); var subtextContext = new Mock<ISubtextContext>(); subtextContext.FakeSyndicationContext(blogInfo, "/Subtext.Web/", "Subtext.Web", null); Mock<BlogUrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper); urlHelper.Setup(u => u.BlogUrl()).Returns("/Subtext.Web/"); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns<Entry>(e => "/Subtext.Web/whatever/" + e.Id); var writer = new RssWriter(new StringWriter(), entries, DateTime.ParseExact("07/14/2003", "MM/dd/yyyy", CultureInfo.InvariantCulture), false, subtextContext.Object); string expected = @"<rss version=""2.0"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine + indent() + "<channel>" + Environment.NewLine + indent(2) + "<title />" + Environment.NewLine + indent(2) + "<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(2) + "<description />" + Environment.NewLine + indent(2) + "<language>en-US</language>" + Environment.NewLine + indent(2) + "<copyright>Subtext Weblog</copyright>" + Environment.NewLine + indent(2) + "<generator>{0}</generator>" + Environment.NewLine + indent(2) + "<image>" + Environment.NewLine + indent(3) + "<title />" + Environment.NewLine + indent(3) + "<url>http://localhost/Subtext.Web/images/RSS2Image.gif</url>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/Default.aspx</link>" + Environment.NewLine + indent(3) + "<width>77</width>" + Environment.NewLine + indent(3) + "<height>60</height>" + Environment.NewLine + indent(2) + "</image>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + "<title>Title of 1004.</title>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/whatever/1004</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1004&lt;img src=""http://localhost/Subtext.Web/aggbug/1004.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + "<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + "<guid>http://localhost/Subtext.Web/whatever/1004</guid>" + Environment.NewLine + indent(3) + "<pubDate>Mon, 14 Jul 2003 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + "<comments>http://localhost/Subtext.Web/whatever/1004#feedback</comments>" + Environment.NewLine + indent(3) + "<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1004.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + "</item>" + Environment.NewLine + indent(2) + "<item>" + Environment.NewLine + indent(3) + "<title>Title of 1003.</title>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/whatever/1003</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1003&lt;img src=""http://localhost/Subtext.Web/aggbug/1003.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + "<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + "<guid>http://localhost/Subtext.Web/whatever/1003</guid>" + Environment.NewLine + indent(3) + "<pubDate>Tue, 16 Oct 1979 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + "<comments>http://localhost/Subtext.Web/whatever/1003#feedback</comments>" + Environment.NewLine + indent(3) + "<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1003.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + "</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + "<title>Title of 1002.</title>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/whatever/1002</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1002&lt;img src=""http://localhost/Subtext.Web/aggbug/1002.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + "<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + "<guid>http://localhost/Subtext.Web/whatever/1002</guid>" + Environment.NewLine + indent(3) + "<pubDate>Fri, 25 Jun 1976 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + "<comments>http://localhost/Subtext.Web/whatever/1002#feedback</comments>" + Environment.NewLine + indent(3) + "<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1002.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + "</item>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + "<title>Title of 1001.</title>" + Environment.NewLine + indent(3) + "<link>http://localhost/Subtext.Web/whatever/1001</link>" + Environment.NewLine + indent(3) + @"<description>Body of 1001&lt;img src=""http://localhost/Subtext.Web/aggbug/1001.aspx"" width=""1"" height=""1"" /&gt;</description>" + Environment.NewLine + indent(3) + "<dc:creator>Phil Haack</dc:creator>" + Environment.NewLine + indent(3) + "<guid>http://localhost/Subtext.Web/whatever/1001</guid>" + Environment.NewLine + indent(3) + "<pubDate>Sun, 23 Feb 1975 08:00:00 GMT</pubDate>" + Environment.NewLine + indent(3) + "<comments>http://localhost/Subtext.Web/whatever/1001#feedback</comments>" + Environment.NewLine + indent(3) + "<wfw:commentRss>http://localhost/Subtext.Web/comments/commentRss/1001.aspx</wfw:commentRss>" + Environment.NewLine + indent(2) + "</item>" + Environment.NewLine + indent() + "</channel>" + Environment.NewLine + "</rss>"; expected = string.Format(expected, VersionInfo.VersionDisplayText); UnitTestHelper.AssertStringsEqualCharacterByCharacter(expected, writer.Xml); } Entry[] CreateSomeEntries() { return new[] { CreateEntry(1001, "Title of 1001.", "Body of 1001", DateTime.ParseExact("01/23/1975", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1002, "Title of 1002.", "Body of 1002", DateTime.ParseExact("05/25/1976", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1003, "Title of 1003.", "Body of 1003", DateTime.ParseExact("09/16/1979", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1004, "Title of 1004.", "Body of 1004", DateTime.ParseExact("06/14/2003", "MM/dd/yyyy", CultureInfo.InvariantCulture)) }; } Entry[] CreateSomeEntriesDescending() { return new[] { CreateEntry(1004, "Title of 1004.", "Body of 1004", DateTime.ParseExact("06/14/2003", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1003, "Title of 1003.", "Body of 1003", DateTime.ParseExact("09/16/1979", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1002, "Title of 1002.", "Body of 1002", DateTime.ParseExact("05/25/1976", "MM/dd/yyyy", CultureInfo.InvariantCulture)) , CreateEntry(1001, "Title of 1001.", "Body of 1001", DateTime.ParseExact("01/23/1975", "MM/dd/yyyy", CultureInfo.InvariantCulture)) }; } static Entry CreateEntry(int id, string title, string body, DateTime dateCreated) { var entry = new Entry(PostType.BlogPost) { DateCreatedUtc = dateCreated, Title = title, Author = "Phil Haack", Body = body, Id = id }; entry.DateModifiedUtc = entry.DateCreatedUtc; entry.DatePublishedUtc = entry.DateCreatedUtc.ToUniversalTime().AddMonths(1); return entry; } /// <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() { } [TearDown] public void TearDown() { } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERLevel { /// <summary> /// C09_Region_Child (editable child object).<br/> /// This is a generated base class of <see cref="C09_Region_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="C08_Region"/> collection. /// </remarks> [Serializable] public partial class C09_Region_Child : BusinessBase<C09_Region_Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name"); /// <summary> /// Gets or sets the Cities Child Name. /// </summary> /// <value>The Cities Child Name.</value> public string Region_Child_Name { get { return GetProperty(Region_Child_NameProperty); } set { SetProperty(Region_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C09_Region_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="C09_Region_Child"/> object.</returns> internal static C09_Region_Child NewC09_Region_Child() { return DataPortal.CreateChild<C09_Region_Child>(); } /// <summary> /// Factory method. Loads a <see cref="C09_Region_Child"/> object, based on given parameters. /// </summary> /// <param name="region_ID1">The Region_ID1 parameter of the C09_Region_Child to fetch.</param> /// <returns>A reference to the fetched <see cref="C09_Region_Child"/> object.</returns> internal static C09_Region_Child GetC09_Region_Child(int region_ID1) { return DataPortal.FetchChild<C09_Region_Child>(region_ID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C09_Region_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C09_Region_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="C09_Region_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="C09_Region_Child"/> object from the database, based on given criteria. /// </summary> /// <param name="region_ID1">The Region ID1.</param> protected void Child_Fetch(int region_ID1) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetC09_Region_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Region_ID1", region_ID1).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, region_ID1); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="C09_Region_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Region_Child_NameProperty, dr.GetString("Region_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="C09_Region_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(C08_Region parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddC09_Region_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Region_ID1", parent.Region_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Region_Child_Name", ReadProperty(Region_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="C09_Region_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(C08_Region parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateC09_Region_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Region_ID1", parent.Region_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Region_Child_Name", ReadProperty(Region_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="C09_Region_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(C08_Region parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteC09_Region_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Region_ID1", parent.Region_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace NinjaNye.SearchExtensions.Tests.SearchExtensionTests.IEnumerableTests { public class IntegerSearchTests : IDisposable { private List<TestData> _testData = new List<TestData>(); public IntegerSearchTests() { _testData = new List<TestData>(); BuildTestData(); } public void Dispose() { _testData.Clear(); } private void BuildTestData() { _testData.Add(new TestData { Number = 1, Age = 5 }); _testData.Add(new TestData { Number = 2, Age = 6 }); _testData.Add(new TestData { Number = 3, Age = 7 }); _testData.Add(new TestData { Number = 4, Age = 8 }); } [Fact] public void Search_SearchConditionNotSupplied_ReturnsAllData() { //Arrange //Act var result = _testData.Search(x => x.Number); //Assert Assert.Equal(_testData, result); } [Fact] public void IsEqual_SearchOnePropertyForMatchingNumber_ReturnsMatchingData() { //Arrange //Act var result = _testData.Search(x => x.Number).EqualTo(2); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number == 2)); } [Fact] public void IsEqual_SearchTwoValues_ReturnsMatchingDataOnly() { //Arrange //Act var result = _testData.Search(x => x.Number).EqualTo(2, 4); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number == 2 || x.Number == 4)); } [Fact] public void IsEqual_SearchTwoProperties_ReturnsMatchingDataOnly() { //Arrange //Act var result = _testData.Search(x => x.Number, x => x.Age).EqualTo(5); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number == 5 || x.Age == 5)); } [Fact] public void GreaterThan_SearchOneProperty_ReturnsOnlyDataWherePropertyIsGreaterThanValue() { //Arrange //Act var result = _testData.Search(x => x.Number).GreaterThan(2); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number > 2)); } [Fact] public void GreaterThan_SearchTwoProperties_ReturnsOnlyDataWherePropertyIsGreaterThanValue() { //Arrange //Act var result = _testData.Search(x => x.Number, x => x.Age).GreaterThan(2); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number > 2 || x.Age > 2)); } [Fact] public void LessThan_SearchOneProperty_ReturnsOnlyDataWherePropertyIsLessThanValue() { //Arrange //Act var result = _testData.Search(x => x.Number).LessThan(2); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number < 2)); } [Fact] public void LessThan_SearchTwoProperties_ReturnsOnlyDataWhereEitherPropertyIsLessThanValue() { //Arrange //Act var result = _testData.Search(x => x.Number, x => x.Age).LessThan(2); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number < 2 || x.Age < 2)); } [Fact] public void LessThanOrEqual_SearchOneProperty_ReturnsOnlyDataWherePropertyIsLessThanOrEqualToValue() { //Arrange //Act var result = _testData.Search(x => x.Number).LessThanOrEqualTo(2); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number <= 2)); } [Fact] public void LessThanOrEqual_SearchTwoProperties_ReturnsOnlyDataWhereEitherPropertyIsLessThanOrEqualToValue() { //Arrange //Act var result = _testData.Search(x => x.Number, x => x.Age).LessThanOrEqualTo(2); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number <= 2 || x.Age <= 2)); } [Fact] public void GreaterThanOrEqual_SearchOneProperty_ReturnsOnlyDataWherePropertyIsGreaterThanOrEqualToValue() { //Arrange //Act var result = _testData.Search(x => x.Number).GreaterThanOrEqualTo(2); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number >= 2)); } [Fact] public void GreaterThanOrEqual_SearchTwoProperties_ReturnsOnlyDataWhereEitherPropertyIsGreaterThanOrEqualToValue() { //Arrange //Act var result = _testData.Search(x => x.Number, x => x.Age).GreaterThanOrEqualTo(2); ////Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number >= 2 || x.Age >= 2)); } [Fact] public void GreaterThanOrLessThan_SearchOnePropertyBetweenTwoValues_OnlyRecordsBetweenValuesReturned() { //Arrange //Act var result = _testData.Search(x => x.Number) .GreaterThan(2) .LessThan(4); //Assert Assert.NotEmpty(result); Assert.True(result.All(x => x.Number > 2 && x.Number < 4)); } [Fact] public void Between_SearchTwoPropertiesBetweenTwoValues_OnlyRecordsBetweenValuesReturned() { //Arrange //Act var result = _testData.Search(x => x.Number, x => x.Age) .Between(2, 6); //Assert Assert.NotEmpty(result); Assert.True(result.All(x => (x.Number > 2 && x.Number < 6) || (x.Age > 2 && x.Age < 6))); } } }
// 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. /* * Ordered String/Object collection of name/value pairs with support for null key * * This class is intended to be used as a base class * */ using System.Globalization; namespace System.Collections.Specialized { /// <devdoc> /// <para>Provides the <see langword='abstract '/>base class for a sorted collection of associated <see cref='System.String' qualify='true'/> keys /// and <see cref='System.Object' qualify='true'/> values that can be accessed either with the hash code of /// the key or with the index.</para> /// </devdoc> public abstract class NameObjectCollectionBase : ICollection { private bool _readOnly = false; private ArrayList _entriesArray; private IEqualityComparer _keyComparer; private volatile Hashtable _entriesTable; private volatile NameObjectEntry _nullKeyEntry; private KeysCollection _keys; private int _version; private Object _syncRoot; private static readonly StringComparer s_defaultComparer = CultureInfo.InvariantCulture.CompareInfo.GetStringComparer(CompareOptions.IgnoreCase); /// <devdoc> /// <para> Creates an empty <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance with the default initial capacity and using the default case-insensitive hash /// code provider and the default case-insensitive comparer.</para> /// </devdoc> protected NameObjectCollectionBase() : this(s_defaultComparer) { } protected NameObjectCollectionBase(IEqualityComparer equalityComparer) { _keyComparer = (equalityComparer == null) ? s_defaultComparer : equalityComparer; Reset(); } protected NameObjectCollectionBase(Int32 capacity, IEqualityComparer equalityComparer) : this(equalityComparer) { Reset(capacity); } /// <devdoc> /// <para>Creates an empty <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance with the specified /// initial capacity and using the default case-insensitive hash code provider /// and the default case-insensitive comparer.</para> /// </devdoc> protected NameObjectCollectionBase(int capacity) { _keyComparer = s_defaultComparer; Reset(capacity); } // // Private helpers // private void Reset() { _entriesArray = new ArrayList(); _entriesTable = new Hashtable(_keyComparer); _nullKeyEntry = null; _version++; } private void Reset(int capacity) { _entriesArray = new ArrayList(capacity); _entriesTable = new Hashtable(capacity, _keyComparer); _nullKeyEntry = null; _version++; } private NameObjectEntry FindEntry(String key) { if (key != null) return (NameObjectEntry)_entriesTable[key]; else return _nullKeyEntry; } internal IEqualityComparer Comparer { get { return _keyComparer; } set { _keyComparer = value; } } /// <devdoc> /// <para>Gets or sets a value indicating whether the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance is read-only.</para> /// </devdoc> protected bool IsReadOnly { get { return _readOnly; } set { _readOnly = value; } } /// <devdoc> /// <para>Gets a value indicating whether the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance contains entries whose /// keys are not <see langword='null'/>.</para> /// </devdoc> protected bool BaseHasKeys() { return (_entriesTable.Count > 0); // any entries with keys? } // // Methods to add / remove entries // /// <devdoc> /// <para>Adds an entry with the specified key and value into the /// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> protected void BaseAdd(String name, Object value) { if (_readOnly) throw new NotSupportedException(SR.CollectionReadOnly); NameObjectEntry entry = new NameObjectEntry(name, value); // insert entry into hashtable if (name != null) { if (_entriesTable[name] == null) _entriesTable.Add(name, entry); } else { // null key -- special case -- hashtable doesn't like null keys if (_nullKeyEntry == null) _nullKeyEntry = entry; } // add entry to the list _entriesArray.Add(entry); _version++; } /// <devdoc> /// <para>Removes the entries with the specified key from the /// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> protected void BaseRemove(String name) { if (_readOnly) throw new NotSupportedException(SR.CollectionReadOnly); if (name != null) { // remove from hashtable _entriesTable.Remove(name); // remove from array for (int i = _entriesArray.Count - 1; i >= 0; i--) { if (_keyComparer.Equals(name, BaseGetKey(i))) _entriesArray.RemoveAt(i); } } else { // null key -- special case // null out special 'null key' entry _nullKeyEntry = null; // remove from array for (int i = _entriesArray.Count - 1; i >= 0; i--) { if (BaseGetKey(i) == null) _entriesArray.RemoveAt(i); } } _version++; } /// <devdoc> /// <para> Removes the entry at the specified index of the /// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> protected void BaseRemoveAt(int index) { if (_readOnly) throw new NotSupportedException(SR.CollectionReadOnly); String key = BaseGetKey(index); if (key != null) { // remove from hashtable _entriesTable.Remove(key); } else { // null key -- special case // null out special 'null key' entry _nullKeyEntry = null; } // remove from array _entriesArray.RemoveAt(index); _version++; } /// <devdoc> /// <para>Removes all entries from the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> protected void BaseClear() { if (_readOnly) throw new NotSupportedException(SR.CollectionReadOnly); Reset(); } // // Access by name // /// <devdoc> /// <para>Gets the value of the first entry with the specified key from /// the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> protected Object BaseGet(String name) { NameObjectEntry e = FindEntry(name); return (e != null) ? e.Value : null; } /// <devdoc> /// <para>Sets the value of the first entry with the specified key in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> /// instance, if found; otherwise, adds an entry with the specified key and value /// into the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> /// instance.</para> /// </devdoc> protected void BaseSet(String name, Object value) { if (_readOnly) throw new NotSupportedException(SR.CollectionReadOnly); NameObjectEntry entry = FindEntry(name); if (entry != null) { entry.Value = value; _version++; } else { BaseAdd(name, value); } } // // Access by index // /// <devdoc> /// <para>Gets the value of the entry at the specified index of /// the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> protected Object BaseGet(int index) { NameObjectEntry entry = (NameObjectEntry)_entriesArray[index]; return entry.Value; } /// <devdoc> /// <para>Gets the key of the entry at the specified index of the /// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> /// instance.</para> /// </devdoc> protected String BaseGetKey(int index) { NameObjectEntry entry = (NameObjectEntry)_entriesArray[index]; return entry.Key; } /// <devdoc> /// <para>Sets the value of the entry at the specified index of /// the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> protected void BaseSet(int index, Object value) { if (_readOnly) throw new NotSupportedException(SR.CollectionReadOnly); NameObjectEntry entry = (NameObjectEntry)_entriesArray[index]; entry.Value = value; _version++; } // // ICollection implementation // /// <devdoc> /// <para>Returns an enumerator that can iterate through the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/>.</para> /// </devdoc> public virtual IEnumerator GetEnumerator() { return new NameObjectKeysEnumerator(this); } /// <devdoc> /// <para>Gets the number of key-and-value pairs in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> public virtual int Count { get { return _entriesArray.Count; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_MultiRank, nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _entriesArray.Count) { throw new ArgumentException(SR.Arg_InsufficientSpace); } for (IEnumerator e = this.GetEnumerator(); e.MoveNext();) array.SetValue(e.Current, index++); } Object ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); } return _syncRoot; } } bool ICollection.IsSynchronized { get { return false; } } // // Helper methods to get arrays of keys and values // /// <devdoc> /// <para>Returns a <see cref='System.String' qualify='true'/> array containing all the keys in the /// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> protected String[] BaseGetAllKeys() { int n = _entriesArray.Count; String[] allKeys = new String[n]; for (int i = 0; i < n; i++) allKeys[i] = BaseGetKey(i); return allKeys; } /// <devdoc> /// <para>Returns an <see cref='System.Object' qualify='true'/> array containing all the values in the /// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> protected Object[] BaseGetAllValues() { int n = _entriesArray.Count; Object[] allValues = new Object[n]; for (int i = 0; i < n; i++) allValues[i] = BaseGet(i); return allValues; } /// <devdoc> /// <para>Returns an array of the specified type containing /// all the values in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> protected object[] BaseGetAllValues(Type type) { int n = _entriesArray.Count; if (type == null) { throw new ArgumentNullException(nameof(type)); } object[] allValues = (object[])Array.CreateInstance(type, n); for (int i = 0; i < n; i++) { allValues[i] = BaseGet(i); } return allValues; } // // Keys property // /// <devdoc> /// <para>Returns a <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/> instance containing /// all the keys in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> public virtual KeysCollection Keys { get { if (_keys == null) _keys = new KeysCollection(this); return _keys; } } // // Simple entry class to allow substitution of values and indexed access to keys // internal class NameObjectEntry { internal NameObjectEntry(String name, Object value) { Key = name; Value = value; } internal String Key; internal Object Value; } // // Enumerator over keys of NameObjectCollection // internal class NameObjectKeysEnumerator : IEnumerator { private int _pos; private NameObjectCollectionBase _coll; private int _version; internal NameObjectKeysEnumerator(NameObjectCollectionBase coll) { _coll = coll; _version = _coll._version; _pos = -1; } public bool MoveNext() { if (_version != _coll._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_pos < _coll.Count - 1) { _pos++; return true; } else { _pos = _coll.Count; return false; } } public void Reset() { if (_version != _coll._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _pos = -1; } public Object Current { get { if (_pos >= 0 && _pos < _coll.Count) { return _coll.BaseGetKey(_pos); } else { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } } } // // Keys collection // /// <devdoc> /// <para>Represents a collection of the <see cref='System.String' qualify='true'/> keys of a collection.</para> /// </devdoc> public class KeysCollection : ICollection { private NameObjectCollectionBase _coll; internal KeysCollection(NameObjectCollectionBase coll) { _coll = coll; } // Indexed access /// <devdoc> /// <para> Gets the key at the specified index of the collection.</para> /// </devdoc> public virtual String Get(int index) { return _coll.BaseGetKey(index); } /// <devdoc> /// <para>Represents the entry at the specified index of the collection.</para> /// </devdoc> public String this[int index] { get { return Get(index); } } // ICollection implementation /// <devdoc> /// <para>Returns an enumerator that can iterate through the /// <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/>.</para> /// </devdoc> public IEnumerator GetEnumerator() { return new NameObjectKeysEnumerator(_coll); } /// <devdoc> /// <para>Gets the number of keys in the <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/>.</para> /// </devdoc> public int Count { get { return _coll.Count; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_MultiRank, nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _coll.Count) { throw new ArgumentException(SR.Arg_InsufficientSpace); } for (IEnumerator e = this.GetEnumerator(); e.MoveNext();) array.SetValue(e.Current, index++); } Object ICollection.SyncRoot { get { return ((ICollection)_coll).SyncRoot; } } bool ICollection.IsSynchronized { get { return false; } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; using GraphQL.Language.AST; using GraphQL.Types; using GraphQL.Utilities; namespace GraphQL { public static class GraphQLExtensions { public static string TrimGraphQLTypes(this string name) { return Regex.Replace(name, "[\\[!\\]]", "").Trim(); } public static bool IsCompositeType(this IGraphType type) { return type is IObjectGraphType || type is IInterfaceGraphType || type is UnionGraphType; } public static bool IsLeafType(this IGraphType type) { var namedType = type.GetNamedType(); return namedType is ScalarGraphType || namedType is EnumerationGraphType; } public static bool IsInputType(this IGraphType type) { var namedType = type.GetNamedType(); return namedType is ScalarGraphType || namedType is EnumerationGraphType || namedType is InputObjectGraphType; } public static IGraphType GetNamedType(this IGraphType type) { IGraphType unmodifiedType = type; if (type is NonNullGraphType) { var nonNull = (NonNullGraphType) type; return GetNamedType(nonNull.ResolvedType); } if (type is ListGraphType) { var list = (ListGraphType) type; return GetNamedType(list.ResolvedType); } return unmodifiedType; } public static IGraphType BuildNamedType(this Type type, Func<Type, IGraphType> resolve = null) { if (resolve == null) { resolve = t => (IGraphType) Activator.CreateInstance(t); } if (type.GetTypeInfo().IsGenericType) { if (type.GetGenericTypeDefinition() == typeof(NonNullGraphType<>)) { var nonNull = (NonNullGraphType)Activator.CreateInstance(type); nonNull.ResolvedType = BuildNamedType(type.GenericTypeArguments[0], resolve); return nonNull; } if (type.GetGenericTypeDefinition() == typeof(ListGraphType<>)) { var list = (ListGraphType)Activator.CreateInstance(type); list.ResolvedType = BuildNamedType(type.GenericTypeArguments[0], resolve); return list; } } return resolve(type); } public static Type GetNamedType(this Type type) { if (type.GetTypeInfo().IsGenericType && (type.GetGenericTypeDefinition() == typeof(NonNullGraphType<>) || type.GetGenericTypeDefinition() == typeof(ListGraphType<>))) { return GetNamedType(type.GenericTypeArguments[0]); } return type; } public static IEnumerable<string> IsValidLiteralValue(this IGraphType type, IValue valueAst, ISchema schema) { if (type is NonNullGraphType) { var nonNull = (NonNullGraphType) type; var ofType = nonNull.ResolvedType; if (valueAst == null) { if (ofType != null) { return new[] { $"Expected \"{ofType.Name}!\", found null."}; } return new[] { "Expected non-null value, found null"}; } return IsValidLiteralValue(ofType, valueAst, schema); } if (valueAst == null) { return new string[] {}; } // This function only tests literals, and assumes variables will provide // values of the correct type. if (valueAst is VariableReference) { return new string[] {}; } if (type is ListGraphType) { var list = (ListGraphType)type; var ofType = list.ResolvedType; if (valueAst is ListValue) { var index = 0; return ((ListValue) valueAst).Values.Aggregate(new string[] {}, (acc, value) => { var errors = IsValidLiteralValue(ofType, value, schema); var result = acc.Concat(errors.Map(err => $"In element #{index}: {err}")).ToArray(); index++; return result; }); } return IsValidLiteralValue(ofType, valueAst, schema); } if (type is InputObjectGraphType) { if (!(valueAst is ObjectValue)) { return new[] {$"Expected \"{type.Name}\", found not an object."}; } var inputType = (InputObjectGraphType) type; var fields = inputType.Fields.ToList(); var fieldAsts = ((ObjectValue) valueAst).ObjectFields.ToList(); var errors = new List<string>(); // ensure every provided field is defined fieldAsts.Apply(providedFieldAst => { var found = fields.FirstOrDefault(x => x.Name == providedFieldAst.Name); if (found == null) { errors.Add($"In field \"{providedFieldAst.Name}\": Unknown field."); } }); // ensure every defined field is valid fields.Apply(field => { var fieldAst = fieldAsts.FirstOrDefault(x => x.Name == field.Name); var result = IsValidLiteralValue(field.ResolvedType, fieldAst?.Value, schema); errors.AddRange(result.Map(err=> $"In field \"{field.Name}\": {err}")); }); return errors; } var scalar = (ScalarGraphType) type; var parseResult = scalar.ParseLiteral(valueAst); if (parseResult == null) { return new [] {$"Expected type \"{type.Name}\", found {AstPrinter.Print(valueAst)}."}; } return new string[] {}; } public static string NameOf<T, P>(this Expression<Func<T, P>> expression) { var member = (MemberExpression) expression.Body; return member.Member.Name; } /// <summary> /// Provided a type and a super type, return true if the first type is either /// equal or a subset of the second super type (covariant). /// </summary> public static bool IsSubtypeOf(this IGraphType maybeSubType, IGraphType superType, ISchema schema) { if (maybeSubType.Equals(superType)) { return true; } // If superType is non-null, maybeSubType must also be nullable. if (superType is NonNullGraphType) { if (maybeSubType is NonNullGraphType) { var sub = (NonNullGraphType) maybeSubType; var sup = (NonNullGraphType) superType; return IsSubtypeOf(sub.ResolvedType, sup.ResolvedType, schema); } return false; } else if (maybeSubType is NonNullGraphType) { var sub = (NonNullGraphType) maybeSubType; return IsSubtypeOf(sub.ResolvedType, superType, schema); } // If superType type is a list, maybeSubType type must also be a list. if (superType is ListGraphType) { if (maybeSubType is ListGraphType) { var sub = (ListGraphType) maybeSubType; var sup = (ListGraphType) superType; return IsSubtypeOf(sub.ResolvedType, sup.ResolvedType, schema); } return false; } else if (maybeSubType is ListGraphType) { // If superType is not a list, maybeSubType must also be not a list. return false; } // If superType type is an abstract type, maybeSubType type may be a currently // possible object type. if (superType is IAbstractGraphType && maybeSubType is IObjectGraphType) { return ((IAbstractGraphType) superType).IsPossibleType(maybeSubType); } return false; } /// <summary> /// Provided two composite types, determine if they "overlap". Two composite /// types overlap when the Sets of possible concrete types for each intersect. /// /// This is often used to determine if a fragment of a given type could possibly /// be visited in a context of another type. /// /// This function is commutative. /// </summary> public static bool DoTypesOverlap(this ISchema schema, IGraphType typeA, IGraphType typeB) { if (typeA.Equals(typeB)) { return true; } var a = typeA as IAbstractGraphType; var b = typeB as IAbstractGraphType; if (a != null) { if (b != null) { return a.PossibleTypes.Any(type => b.IsPossibleType(type)); } return a.IsPossibleType(typeB); } if (b != null) { return b.IsPossibleType(typeA); } return false; } public static IValue AstFromValue(this object value, ISchema schema, IGraphType type) { if (type is NonNullGraphType) { var nonnull = (NonNullGraphType)type; return AstFromValue(value, schema, nonnull.ResolvedType); } if (value == null || type == null) { return null; } // Convert IEnumerable to GraphQL list. If the GraphQLType is a list, but // the value is not an IEnumerable, convert the value using the list's item type. if (type is ListGraphType) { var listType = (ListGraphType) type; var itemType = listType.ResolvedType; if (!(value is string) && value is IEnumerable) { var list = (IEnumerable)value; var values = list.Map(item => AstFromValue(item, schema, itemType)); return new ListValue(values); } return AstFromValue(value, schema, itemType); } // Populate the fields of the input object by creating ASTs from each value // in the dictionary according to the fields in the input type. if (type is InputObjectGraphType) { if (!(value is Dictionary<string, object>)) { return null; } var input = (InputObjectGraphType) type; var dict = (Dictionary<string, object>)value; var fields = dict .Select(pair => { var field = input.Fields.FirstOrDefault(x => x.Name == pair.Key); var fieldType = field?.ResolvedType; return new ObjectField(pair.Key, AstFromValue(pair.Value, schema, fieldType)); }) .ToList(); return new ObjectValue(fields); } Invariant.Check( type.IsInputType(), $"Must provide Input Type, cannot use: {type}"); var inputType = type as ScalarGraphType; // Since value is an internally represented value, it must be serialized // to an externally represented value before converting into an AST. var serialized = inputType.Serialize(value); if (serialized == null) { return null; } if (serialized is bool) { return new BooleanValue((bool)serialized); } if (serialized is int) { return new IntValue((int)serialized); } if (serialized is long) { return new LongValue((long)serialized); } if (serialized is decimal) { return new DecimalValue((decimal)serialized); } if (serialized is double) { return new FloatValue((double)serialized); } if (serialized is DateTime) { return new DateTimeValue((DateTime)serialized); } if (serialized is string) { if (type is EnumerationGraphType) { return new EnumValue(serialized.ToString()); } return new StringValue(serialized.ToString()); } throw new ExecutionError($"Cannot convert value to AST: {serialized}"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Threading; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; namespace Internal.Cryptography.Pal { internal sealed partial class StorePal { private static CollectionBackedStoreProvider s_machineRootStore; private static CollectionBackedStoreProvider s_machineIntermediateStore; private static readonly object s_machineLoadLock = new object(); public static IStorePal FromHandle(IntPtr storeHandle) { throw new PlatformNotSupportedException(); } public static ILoaderPal FromBlob(byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { Debug.Assert(password != null); ICertificatePal singleCert; if (CertificatePal.TryReadX509Der(rawData, out singleCert) || CertificatePal.TryReadX509Pem(rawData, out singleCert)) { // The single X509 structure methods shouldn't return true and out null, only empty // collections have that behavior. Debug.Assert(singleCert != null); return SingleCertToLoaderPal(singleCert); } List<ICertificatePal> certPals; if (PkcsFormatReader.TryReadPkcs7Der(rawData, out certPals) || PkcsFormatReader.TryReadPkcs7Pem(rawData, out certPals) || PkcsFormatReader.TryReadPkcs12(rawData, password, out certPals)) { Debug.Assert(certPals != null); return ListToLoaderPal(certPals); } throw Interop.Crypto.CreateOpenSslCryptographicException(); } public static ILoaderPal FromFile(string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { using (SafeBioHandle bio = Interop.Crypto.BioNewFile(fileName, "rb")) { Interop.Crypto.CheckValidOpenSslHandle(bio); return FromBio(bio, password); } } private static ILoaderPal FromBio(SafeBioHandle bio, SafePasswordHandle password) { int bioPosition = Interop.Crypto.BioTell(bio); Debug.Assert(bioPosition >= 0); ICertificatePal singleCert; if (CertificatePal.TryReadX509Pem(bio, out singleCert)) { return SingleCertToLoaderPal(singleCert); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); if (CertificatePal.TryReadX509Der(bio, out singleCert)) { return SingleCertToLoaderPal(singleCert); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); List<ICertificatePal> certPals; if (PkcsFormatReader.TryReadPkcs7Pem(bio, out certPals)) { return ListToLoaderPal(certPals); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); if (PkcsFormatReader.TryReadPkcs7Der(bio, out certPals)) { return ListToLoaderPal(certPals); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); if (PkcsFormatReader.TryReadPkcs12(bio, password, out certPals)) { return ListToLoaderPal(certPals); } // Since we aren't going to finish reading, leaving the buffer where it was when we got // it seems better than leaving it in some arbitrary other position. // // But, before seeking back to start, save the Exception representing the last reported // OpenSSL error in case the last BioSeek would change it. Exception openSslException = Interop.Crypto.CreateOpenSslCryptographicException(); // Use BioSeek directly for the last seek attempt, because any failure here should instead // report the already created (but not yet thrown) exception. Interop.Crypto.BioSeek(bio, bioPosition); throw openSslException; } public static IExportPal FromCertificate(ICertificatePal cert) { return new ExportProvider(cert); } public static IExportPal LinkFromCertificateCollection(X509Certificate2Collection certificates) { return new ExportProvider(certificates); } public static IStorePal FromSystemStore(string storeName, StoreLocation storeLocation, OpenFlags openFlags) { if (storeLocation != StoreLocation.LocalMachine) { return new DirectoryBasedStoreProvider(storeName, openFlags); } if ((openFlags & OpenFlags.ReadWrite) == OpenFlags.ReadWrite) { throw new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresReadOnly); } // The static store approach here is making an optimization based on not // having write support. Once writing is permitted the stores would need // to fresh-read whenever being requested. if (s_machineRootStore == null) { lock (s_machineLoadLock) { if (s_machineRootStore == null) { LoadMachineStores(); } } } if (StringComparer.Ordinal.Equals("Root", storeName)) { return s_machineRootStore; } if (StringComparer.Ordinal.Equals("CA", storeName)) { return s_machineIntermediateStore; } throw new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresRootOnly); } private static ILoaderPal SingleCertToLoaderPal(ICertificatePal singleCert) { return new SingleCertLoader(singleCert); } private static ILoaderPal ListToLoaderPal(List<ICertificatePal> certPals) { return new CertCollectionLoader(certPals); } private static void LoadMachineStores() { Debug.Assert( Monitor.IsEntered(s_machineLoadLock), "LoadMachineStores assumes a lock(s_machineLoadLock)"); var rootStore = new List<X509Certificate2>(); var intermedStore = new List<X509Certificate2>(); DirectoryInfo rootStorePath = null; IEnumerable<FileInfo> trustedCertFiles; try { rootStorePath = new DirectoryInfo(Interop.Crypto.GetX509RootStorePath()); } catch (ArgumentException) { // If SSL_CERT_DIR is set to the empty string, or anything else which gives // "The path is not of a legal form", then the GetX509RootStorePath value is ignored. } if (rootStorePath != null && rootStorePath.Exists) { trustedCertFiles = rootStorePath.EnumerateFiles(); } else { trustedCertFiles = Array.Empty<FileInfo>(); } FileInfo rootStoreFile = null; try { rootStoreFile = new FileInfo(Interop.Crypto.GetX509RootStoreFile()); } catch (ArgumentException) { // If SSL_CERT_FILE is set to the empty string, or anything else which gives // "The path is not of a legal form", then the GetX509RootStoreFile value is ignored. } if (rootStoreFile != null && rootStoreFile.Exists) { trustedCertFiles = Append(trustedCertFiles, rootStoreFile); } HashSet<X509Certificate2> uniqueRootCerts = new HashSet<X509Certificate2>(); HashSet<X509Certificate2> uniqueIntermediateCerts = new HashSet<X509Certificate2>(); foreach (FileInfo file in trustedCertFiles) { using (SafeBioHandle fileBio = Interop.Crypto.BioNewFile(file.FullName, "rb")) { ICertificatePal pal; while (CertificatePal.TryReadX509Pem(fileBio, out pal) || CertificatePal.TryReadX509Der(fileBio, out pal)) { X509Certificate2 cert = new X509Certificate2(pal); // The HashSets are just used for uniqueness filters, they do not survive this method. if (StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer)) { if (uniqueRootCerts.Add(cert)) { rootStore.Add(cert); continue; } } else { if (uniqueIntermediateCerts.Add(cert)) { intermedStore.Add(cert); continue; } } // There's a good chance we'll encounter duplicates on systems that have both one-cert-per-file // and one-big-file trusted certificate stores. Anything that wasn't unique will end up here. cert.Dispose(); } } } var rootStorePal = new CollectionBackedStoreProvider(rootStore); s_machineIntermediateStore = new CollectionBackedStoreProvider(intermedStore); // s_machineRootStore's nullarity is the loaded-state sentinel, so write it with Volatile. Debug.Assert(Monitor.IsEntered(s_machineLoadLock), "LoadMachineStores assumes a lock(s_machineLoadLock)"); Volatile.Write(ref s_machineRootStore, rootStorePal); } private static IEnumerable<T> Append<T>(IEnumerable<T> current, T addition) { foreach (T element in current) yield return element; yield return addition; } } }
// $Id: TOTAL.java,v 1.6 2004/07/05 14:17:16 belaban Exp $ using System; using Alachisoft.NGroups; using Alachisoft.NGroups.Protocols; using Alachisoft.NGroups.Util; using Alachisoft.NGroups.Protocols.pbcast; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Common; using System.Text; using Alachisoft.NCache.Common.Enum; using Alachisoft.NCache.Common.Util; using Alachisoft.NGroups.Stack; namespace Alachisoft.NGroups.Protocols { /// <summary> The TCPPING protocol layer retrieves the initial membership (used by the GMS when started /// by sending event FIND_INITIAL_MBRS down the stack). We do this by mcasting TCPPING /// requests to an IP MCAST address (or, if gossiping is enabled, by contacting the router). /// The responses should allow us to determine the coordinator whom we have to contact, /// e.g. in case we want to join the group. When we are a server (after having received the /// BECOME_SERVER event), we'll respond to TCPPING requests with a TCPPING response.<p> The /// FIND_INITIAL_MBRS event will eventually be answered with a FIND_INITIAL_MBRS_OK event up /// the stack. /// </summary> /// <author> Bela Ban /// </author> class TCPPING : Protocol { override public System.String Name { get { return "TCPPING"; } } internal System.Collections.ArrayList members = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)), initial_members = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // internal SetSupport members_set = new HashSetSupport(); //copy of the members vector for fast random access internal Address local_addr = null; internal string group_addr = null; internal string subGroup_addr = null; internal System.String groupname = null; internal long timeout = 5000; internal long num_initial_members = 20; internal bool twoPhaseConnect; //muds: 24-06-08 //as per iqbal sb. decision changing the default port-range to '1' internal int port_range = 1; // number of ports to be probed for initial membership internal ThreadClass mcast_receiver = null; internal String discovery_addr = "228.8.8.8"; internal int discovery_port = 7700; internal int tcpServerPort = 7500; internal MPingBroadcast broadcaster = null; internal MPingReceiver receiver = null; internal bool hasStarted = false; internal bool isStatic = false; internal bool mbrDiscoveryInProcess = false; /// <summary> /// These two values are used to authorize a user so that he can not join /// to other nodes where he is not allowed to. /// </summary> /// private const string DEFAULT_USERID = "Ncache-Default-UserId"; private const string DEFAULT_PASSWORD = "Ncache-Default-Password"; internal string userId = DEFAULT_USERID; internal string password = DEFAULT_PASSWORD; internal byte[] secureUid = null; internal byte[] securePwd = null; /// <summary>List<Address> </summary> internal System.Collections.ArrayList initial_hosts = null; // hosts to be contacted for the initial membership internal bool is_server = false; public override bool setProperties(System.Collections.Hashtable props) { base.setProperties(props); if (stack.StackType == ProtocolStackType.TCP) { this.up_thread = false; this.down_thread = false; if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info(Name + ".setProperties", "part of TCP stack"); } if (props.Contains("timeout")) // max time to wait for initial members { timeout = Convert.ToInt64(props["timeout"]); props.Remove("timeout"); } if (props.Contains("port_range")) // if member cannot be contacted on base port, { // how many times can we increment the port port_range = Convert.ToInt32(props["port_range"]); if (port_range < 1) { port_range = 1; } props.Remove("port_range"); } if (props.Contains("static")) { isStatic = Convert.ToBoolean(props["static"]); props.Remove("static"); } if (props.Contains("num_initial_members")) // wait for at most n members { num_initial_members = Convert.ToInt32(props["num_initial_members"]); props.Remove("num_initial_members"); } if (props.Contains("initial_hosts")) { String tmp = (String)props["initial_hosts"]; if (tmp != null && tmp.Length > 0) { initial_hosts = createInitialHosts(Convert.ToString(tmp)); } if (initial_hosts != null) { if (num_initial_members != initial_hosts.Count) num_initial_members = initial_hosts.Count; } if (num_initial_members > 5) { //We estimate the time for finding initital members //for every member we add 1 sec timeout. long temp = num_initial_members - 5; timeout += (temp * 1000); } props.Remove("initial_hosts"); } if (props.Contains("discovery_addr")) { discovery_addr = Convert.ToString(props["discovery_addr"]); if (discovery_addr != null && discovery_addr.Length > 0) isStatic = false; else isStatic = true; props.Remove("discovery_addr"); } if (props.Contains("discovery_port")) { discovery_port = Convert.ToInt32(props["discovery_port"]); props.Remove("discovery_port"); } if (props.Contains("user-id")) { userId = Convert.ToString(props["user-id"]); secureUid = EncryptionUtil.Encrypt(userId); props.Remove("user-id"); } if (props.Contains("password")) { password = Convert.ToString(props["password"]); securePwd = EncryptionUtil.Encrypt(password); props.Remove("password"); } if (props.Count > 0) { return true; } return true; } public bool IsStatic { get { return isStatic; } } public override void up(Event evt) { Message msg, rsp_msg; System.Object obj; PingHeader hdr, rsp_hdr; PingRsp rsp; Address coord; switch (evt.Type) { case Event.MSG: msg = (Message)evt.Arg; obj = msg.getHeader(HeaderType.TCPPING); if (obj == null || !(obj is PingHeader)) { passUp(evt); return; } hdr = (PingHeader)msg.removeHeader(HeaderType.TCPPING); switch (hdr.type) { case PingHeader.GET_MBRS_REQ: // return Rsp(local_addr, coord) if (!hdr.group_addr.Equals(group_addr)) { if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.up()", "GET_MBRS_REQ from different group , so discarded"); return; } Address src = (Address)hdr.arg; msg.Src = src; if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "GET_MBRS_REQ from " + msg.Src.ToString()); //determine whether security is required at this level. //we require security only in case of inproc initialization of cache. bool authorized = true; byte[] secureUid = hdr.userId; byte[] securePwd = hdr.password; string uid = EncryptionUtil.Decrypt(secureUid); string pwd = EncryptionUtil.Decrypt(securePwd); if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", " before authorizing. I have received these credentials user-id = " + userId + ", password = " + password); if (!authorized || Stack.DisableOperationOnMerge) { rsp_msg = new Message(msg.Src, null, null); rsp_hdr = new PingHeader(PingHeader.GET_MBRS_RSP, new PingRsp(null, null, false, true)); rsp_msg.putHeader(HeaderType.TCPPING, rsp_hdr); if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "responding to GET_MBRS_REQ back to " + msg.Src.ToString() + " with empty response"); if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "some un-authorized user has tried to connect to the cluster"); passDown(new Event(Event.MSG, rsp_msg, Priority.High)); } else { lock (members.SyncRoot) { coord = members.Count > 0 ? (Address)members[0] : local_addr; } if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "my coordinator is " + coord.ToString()); rsp_msg = new Message(msg.Src, null, null); rsp_hdr = new PingHeader(PingHeader.GET_MBRS_RSP, new PingRsp(local_addr, coord, Stack.IsOperational, Stack.IsOperational)); rsp_msg.putHeader(HeaderType.TCPPING, rsp_hdr); if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "responding to GET_MBRS_REQ back to " + msg.Src.ToString()); if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info(local_addr + " - [FIND_INITIAL_MBRS] replying PING request to " + rsp_msg.Dest); passDown(new Event(Event.MSG, rsp_msg, Priority.High)); } return; case PingHeader.GET_MBRS_RSP: // add response to vector and notify waiting thread if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "GET_MBRS_RSP from " + msg.Src.ToString()); rsp = (PingRsp)hdr.arg; //check if the received response is valid i.e. successful security authorization //at other end. if (rsp.OwnAddress == null && rsp.CoordAddress == null && rsp.HasJoined == false) { lock (initial_members.SyncRoot) { if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "I am not authorized to join to " + msg.Src.ToString()); System.Threading.Monitor.PulseAll(initial_members.SyncRoot); } } else { if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "Before Adding initial members response"); lock (initial_members.SyncRoot) { if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "Adding initial members response"); if (!initial_members.Contains(rsp)) { initial_members.Add(rsp); if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "Adding initial members response for " + rsp.OwnAddress); } else if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.up()", "response already received"); System.Threading.Monitor.PulseAll(initial_members.SyncRoot); } } return; default: Stack.NCacheLog.Warn("got TCPPING header with unknown type (" + hdr.type + ')'); return; } case Event.SET_LOCAL_ADDRESS: passUp(evt); local_addr = (Address)evt.Arg; // Add own address to initial_hosts if not present: we must always be able to ping ourself ! if (initial_hosts != null && local_addr != null) { if (!initial_hosts.Contains(local_addr)) { Stack.NCacheLog.Debug("[SET_LOCAL_ADDRESS]: adding my own address (" + local_addr + ") to initial_hosts; initial_hosts=" + Global.CollectionToString(initial_hosts)); initial_hosts.Add(local_addr); } } break; case Event.CONNECT_OK: obj = evt.Arg; if (obj != null && obj is Address) { tcpServerPort = ((Address)obj).Port; } passUp(evt); break; case Event.CONNECTION_NOT_OPENED: if (mbrDiscoveryInProcess) { Address node = evt.Arg as Address; PingRsp response = new PingRsp(node, node, true, false); lock (initial_members.SyncRoot) { initial_members.Add(response); System.Threading.Monitor.PulseAll(initial_members.SyncRoot); } if (Stack != null && Stack.NCacheLog != null && Stack.NCacheLog.IsDebugEnabled) Stack.NCacheLog.Debug(Name + ".up", "connection failure with " + node); } break; // end services default: passUp(evt); // Pass up to the layer above us break; } } public override void down(Event evt) { Message msg; long time_to_wait, start_time; switch (evt.Type) { case Event.FIND_INITIAL_MBRS: // sent by GMS layer, pass up a GET_MBRS_OK event //We pass this event down to tcp so that it can take some measures. passDown(evt); initial_members.Clear(); msg = new Message(null, null, null); msg.putHeader(HeaderType.TCPPING, new PingHeader(PingHeader.GET_MBRS_REQ, (System.Object)local_addr, group_addr, secureUid, securePwd)); // if intitial nodes have been specified and static is true, then only those // members will form the cluster, otherwise, nodes having the same IP Multicast and port // will form the cluster dyanamically. mbrDiscoveryInProcess = true; lock (members.SyncRoot) { if (initial_hosts != null) { for (System.Collections.IEnumerator it = initial_hosts.GetEnumerator(); it.MoveNext(); ) { Address addr = (Address)it.Current; msg.Dest = addr; if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("[FIND_INITIAL_MBRS] sending PING request to " + msg.Dest); passDown(new Event(Event.MSG_URGENT, msg.copy(), Priority.High)); } } } // 2. Wait 'timeout' ms or until 'num_initial_members' have been retrieved if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()", "[FIND_INITIAL_MBRS] waiting for results..............."); lock (initial_members.SyncRoot) { start_time = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; time_to_wait = timeout; while (initial_members.Count < num_initial_members && time_to_wait > 0) { try { if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()", "initial_members Count: " + initial_members.Count + "initialHosts Count: " + num_initial_members); if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()", "Time to wait for next response: " + time_to_wait); ///initial members will be pulsed in case connection is not available. ///so here we dont have to wait till each member is timed out. ///this significantly improves time for initial member discovery. bool timeExpire = System.Threading.Monitor.Wait(initial_members.SyncRoot, TimeSpan.FromMilliseconds(time_to_wait)); } catch (System.Exception e) { Stack.NCacheLog.Error("TCPPing.down(FIND_INITIAL_MBRS)", e.ToString()); } time_to_wait = timeout - ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - start_time); } mbrDiscoveryInProcess = false; } if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()", "[FIND_INITIAL_MBRS] initial members are " + Global.CollectionToString(initial_members)); if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()", "[FIND_INITIAL_MBRS] initial members count " + initial_members.Count); //remove those which are not functional due to twoPhaseConnect for (int i = initial_members.Count - 1; i >= 0; i--) { PingRsp rsp = initial_members[i] as PingRsp; if (!rsp.IsStarted) initial_members.RemoveAt(i); } // 3. Send response passUp(new Event(Event.FIND_INITIAL_MBRS_OK, initial_members)); break; case Event.TMP_VIEW: case Event.VIEW_CHANGE: System.Collections.ArrayList tmp; if ((tmp = ((View)evt.Arg).Members) != null) { lock (members.SyncRoot) { members.Clear(); members.AddRange(tmp); } } passDown(evt); break; /****************************After removal of NackAck *********************************/ //TCPPING emulates a GET_DIGEST call, which is required by GMS. This is needed //since we have now removed NAKACK from the stack! case Event.GET_DIGEST: pbcast.Digest digest = new pbcast.Digest(members.Count); for (int i = 0; i < members.Count; i++) { Address sender = (Address)members[i]; digest.add(sender, 0, 0); } passUp(new Event(Event.GET_DIGEST_OK, digest)); return; case Event.SET_DIGEST: // Not needed! Just here to let you know that it is needed by GMS! return; /********************************************************************************/ case Event.BECOME_SERVER: // called after client has joined and is fully working group member if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()", "received BECOME_SERVER event"); passDown(evt); is_server = true; break; case Event.CONNECT: object[] addrs = ((object[])evt.Arg); group_addr = (string)addrs[0]; subGroup_addr = (string)addrs[1]; twoPhaseConnect = (bool)addrs[3]; if (twoPhaseConnect) timeout = 1000; passDown(evt); break; case Event.DISCONNECT: passDown(evt); break; case Event.HAS_STARTED: hasStarted = true; passDown(evt); break; default: passDown(evt); // Pass on to the layer below us break; } } public override System.Collections.ArrayList providedUpServices() { System.Collections.ArrayList retval = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(6)); retval.Add((System.Int32)Event.FIND_INITIAL_MBRS); retval.Add((System.Int32)Event.GET_DIGEST); retval.Add((System.Int32)Event.SET_DIGEST); return retval; } /* -------------------------- Private methods ---------------------------- */ /// <summary> Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of IpAddresses</summary> private System.Collections.ArrayList createInitialHosts(System.String l) { Tokenizer tok = new Tokenizer(l, ","); System.String t; Address addr; int port; System.Collections.ArrayList retval = new System.Collections.ArrayList(); System.Collections.Hashtable hosts = new System.Collections.Hashtable(); //to be removed later on while (tok.HasMoreTokens()) { try { t = tok.NextToken(); System.String host = t.Substring(0, (t.IndexOf((System.Char)'[')) - (0)); host = host.Trim(); port = System.Int32.Parse(t.Substring(t.IndexOf((System.Char)'[') + 1, (t.IndexOf((System.Char)']')) - (t.IndexOf((System.Char)'[') + 1))); hosts.Add(host, port); } catch (System.FormatException e) { Stack.NCacheLog.Error("exeption is " + e); } catch (Exception e) { Stack.NCacheLog.Error("TcpPing.createInitialHosts", "Error: " + e.ToString()); throw new Exception("Invalid initial members list"); } } try { System.Collections.IDictionaryEnumerator ide; for (int i = 0; i < port_range; i++) { ide = hosts.GetEnumerator(); while (ide.MoveNext()) { port = Convert.ToInt32(ide.Value); addr = new Address((String)ide.Key, port+i); retval.Add(addr); } } } catch (Exception ex) { Stack.NCacheLog.Error("TcpPing.CreateInitialHosts()", "Error :" + ex); throw new Exception("Invalid initial memebers list"); } return retval; } } }
// Runtime.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Linq.Expressions; using System.Reflection; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace System { [AttributeUsage(AttributeTargets.Enum, Inherited = false, AllowMultiple = false)] [NonScriptable] public sealed class FlagsAttribute : Attribute { } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public abstract class MarshalByRefObject { } [EditorBrowsable(EditorBrowsableState.Never)] [Imported] [IgnoreNamespace] [ScriptName("Object")] public abstract class ValueType { [ScriptSkip] protected ValueType() { } } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public struct IntPtr { } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public struct UIntPtr { } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public struct RuntimeTypeHandle { } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public struct RuntimeFieldHandle { } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public struct RuntimeMethodHandle { } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class ParamArrayAttribute : Attribute { } [AttributeUsage(AttributeTargets.Delegate | AttributeTargets.Interface | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Class, Inherited = false)] [NonScriptable] public sealed class ObsoleteAttribute : Attribute { private bool _error; private string _message; public ObsoleteAttribute() { } public ObsoleteAttribute(string message) { _message = message; } public ObsoleteAttribute(string message, bool error) { _message = message; _error = error; } public bool IsError { get { return _error; } } public string Message { get { return _message; } } } [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class CLSCompliantAttribute : Attribute { private bool _isCompliant; public CLSCompliantAttribute(bool isCompliant) { _isCompliant = isCompliant; } public bool IsCompliant { get { return _isCompliant; } } } } namespace System.CodeDom.Compiler { [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)] [NonScriptable] public sealed class GeneratedCodeAttribute : Attribute { private string _tool; private string _version; public GeneratedCodeAttribute(string tool, string version) { _tool = tool; _version = version; } public string Tool { get { return _tool; } } public string Version { get { return _version; } } } } namespace System.ComponentModel { /// <summary> /// This attribute marks a field, property, event or method as /// "browsable", i.e. present in the type descriptor associated with /// the type. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class BrowsableAttribute : Attribute { } [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Interface)] [NonScriptable] public sealed class EditorBrowsableAttribute : Attribute { private EditorBrowsableState _browsableState; public EditorBrowsableAttribute(EditorBrowsableState state) { _browsableState = state; } public EditorBrowsableState State { get { return _browsableState; } } } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public enum EditorBrowsableState { Always = 0, Never = 1, Advanced = 2 } } namespace System.Reflection { [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class DefaultMemberAttribute { private string _memberName; public DefaultMemberAttribute(string memberName) { _memberName = memberName; } public string MemberName { get { return _memberName; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyCopyrightAttribute : Attribute { private string _copyright; public AssemblyCopyrightAttribute(string copyright) { _copyright = copyright; } public string Copyright { get { return _copyright; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyTrademarkAttribute : Attribute { private string _trademark; public AssemblyTrademarkAttribute(string trademark) { _trademark = trademark; } public string Trademark { get { return _trademark; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyProductAttribute : Attribute { private string _product; public AssemblyProductAttribute(string product) { _product = product; } public string Product { get { return _product; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyCompanyAttribute : Attribute { private string _company; public AssemblyCompanyAttribute(string company) { _company = company; } public string Company { get { return _company; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyDescriptionAttribute : Attribute { private string _description; public AssemblyDescriptionAttribute(string description) { _description = description; } public string Description { get { return _description; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyTitleAttribute : Attribute { private string _title; public AssemblyTitleAttribute(string title) { _title = title; } public string Title { get { return _title; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyConfigurationAttribute : Attribute { private string _configuration; public AssemblyConfigurationAttribute(string configuration) { _configuration = configuration; } public string Configuration { get { return _configuration; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyFileVersionAttribute : Attribute { private string _version; public AssemblyFileVersionAttribute(string version) { _version = version; } public string Version { get { return _version; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyInformationalVersionAttribute : Attribute { private string _informationalVersion; public AssemblyInformationalVersionAttribute(string informationalVersion) { _informationalVersion = informationalVersion; } public string InformationalVersion { get { return _informationalVersion; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyCultureAttribute : Attribute { private string _culture; public AssemblyCultureAttribute(string culture) { _culture = culture; } public string Culture { get { return _culture; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyVersionAttribute : Attribute { private string _version; public AssemblyVersionAttribute(string version) { _version = version; } public string Version { get { return _version; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyKeyFileAttribute : Attribute { private string _keyFile; public AssemblyKeyFileAttribute(string keyFile) { _keyFile = keyFile; } public string KeyFile { get { return _keyFile; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [NonScriptable] public sealed class AssemblyDelaySignAttribute : Attribute { private bool _delaySign; public AssemblyDelaySignAttribute(bool delaySign) { _delaySign = delaySign; } public bool DelaySign { get { return _delaySign; } } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All, Inherited = true)] [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class CompilerGeneratedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class DecimalConstantAttribute : Attribute { public DecimalConstantAttribute(byte scale, byte sign, int hi, int mid, int low) { } public DecimalConstantAttribute(byte scale, byte sign, uint hi, uint mid, uint low) { } public decimal Value { get { return 0m; } } } [AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Class|AttributeTargets.Method)] [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class ExtensionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class DynamicAttribute : Attribute { public IList<bool> TransformFlags { get { return null; } } public DynamicAttribute() {} public DynamicAttribute(bool[] transformFlags) {} } [AttributeUsage(AttributeTargets.Field, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class FixedBufferAttribute : Attribute { public Type ElementType { get { return null; } } public int Length { get { return 0; } } public FixedBufferAttribute(Type elementType, int length) {} } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class RuntimeCompatibilityAttribute : Attribute { public bool WrapNonExceptionThrows { get; set; } } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public class CallSite { public CallSiteBinder Binder { get { return null; } } public static CallSite Create(Type delegateType, CallSiteBinder binder) { return null; } } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class CallSite<T> : CallSite where T : class { public T Update { get { return null; } } public T Target; public static CallSite<T> Create(CallSiteBinder binder) { return null; } } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public abstract class CallSiteBinder { public static LabelTarget UpdateLabel { get { return null; } } public virtual T BindDelegate<T>(CallSite<T> site, object[] args) where T : class { return null; } } [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Property)] public class IndexerNameAttribute : Attribute { public IndexerNameAttribute(string indexerName) { this.Value = indexerName; } public string Value { get; private set; } } [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] public struct AsyncVoidMethodBuilder { public static AsyncVoidMethodBuilder Create(){ return default(AsyncVoidMethodBuilder); } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public void SetResult() { } public void SetException(Exception exception) { } } [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] public struct AsyncTaskMethodBuilder { public Task Task { get { return null; } } public static AsyncTaskMethodBuilder Create() { return default(AsyncTaskMethodBuilder); } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public void SetResult() { } public void SetException(Exception exception) { } } [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] public struct AsyncTaskMethodBuilder<TResult> { public Task<TResult> Task { get { return null; } } public static AsyncTaskMethodBuilder<TResult> Create() { return default(AsyncTaskMethodBuilder<TResult>); } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public void SetResult(TResult result) { } public void SetException(Exception exception) { } } [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] public interface IAsyncStateMachine { void MoveNext(); void SetStateMachine(IAsyncStateMachine stateMachine); } [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] public interface INotifyCompletion { void OnCompleted(Action continuation); } [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] public interface ICriticalNotifyCompletion : INotifyCompletion { void UnsafeOnCompleted(Action continuation); } [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] public class CompilationRelaxationsAttribute : Attribute { public CompilationRelaxationsAttribute(int relaxations) { CompilationRelaxations = relaxations; } public CompilationRelaxationsAttribute(CompilationRelaxations relaxations) { CompilationRelaxations = (int)relaxations; } public int CompilationRelaxations { get; private set; } } [Flags] [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] public enum CompilationRelaxations : int { NoStringInterning = 0x0008, // Start in 0x0008, we had other non public flags in this enum before, // so we'll start here just in case somebody used them. This flag is only // valid when set for Assemblies. }; } namespace System.Runtime.InteropServices { [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public class OutAttribute { } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class StructLayoutAttribute : Attribute { public int Pack; public int Size; public CharSet CharSet; public LayoutKind Value { get { return LayoutKind.Auto; } } public StructLayoutAttribute(LayoutKind layoutKind) {} public StructLayoutAttribute(short layoutKind) {} } /// <summary> /// Dummy ComVisible attribute, used to prevent errors caused by the presence of a ComVisibleAttribute in the default AssemblyInfo.cs. /// <para>Applying this attribute to an assembly has no effect on the generated code.</para> /// </summary> [AttributeUsage(AttributeTargets.Assembly)] [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class ComVisibleAttribute : Attribute { private readonly bool _val; public bool Value { get { return _val; } } public ComVisibleAttribute(bool visibility) { _val = visibility; } } /// <summary> /// Dummy Guid attribute, used to prevent errors caused by the presence of a GuidAttribute in the default AssemblyInfo.cs. /// <para>Applying this attribute to an assembly has no effect on the generated code.</para> /// </summary> [AttributeUsage(AttributeTargets.Assembly)] [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class GuidAttribute : Attribute { private readonly string _val; public string Value { get { return _val; } } public GuidAttribute(string guid) { _val = guid; } } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public enum CharSet { None = 1, Ansi = 2, Unicode = 3, Auto = 4, } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public enum LayoutKind { Sequential = 0, Explicit = 2, Auto = 3, } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] [NonScriptable] public sealed class TargetFrameworkAttribute : Attribute { private string _frameworkName; private string _frameworkDisplayName; public TargetFrameworkAttribute(string frameworkName) { _frameworkName = frameworkName; } public string FrameworkDisplayName { get { return _frameworkDisplayName; } set { _frameworkDisplayName = value; } } public string FrameworkName { get { return _frameworkName; } } } } namespace System.Threading { public static class Interlocked { [InlineCode("++({location1}.$)")] public static int Increment(ref int location1) { return 0; } [InlineCode("{location1}.$ === {comparand} ? {location1}.$ = {value} : {location1}.$")] public static int CompareExchange(ref int location1, int value, int comparand) { return 0; } [InlineCode("{location1}.$ === {comparand} ? {location1}.$ = {value} : {location1}.$")] public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class { return null; } public static T Exchange<T>(ref T location1, T value) where T : class { var r = location1; location1 = value; return r; } } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public static class Monitor { public static void Enter(object obj) { } public static void Enter(object obj, ref bool b) { } public static void Exit(object obj) { } } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public class Thread { public int ManagedThreadId { get { return 0; } } public static Thread CurrentThread { get { return null; } } } } namespace System.Security.Permissions { [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public enum SecurityAction { Demand = 2, Assert = 3, Deny = 4, PermitOnly = 5, LinkDemand = 6, InheritanceDemand = 7, RequestMinimum = 8, RequestOptional = 9, RequestRefuse = 10, } } namespace Microsoft.CSharp.RuntimeBinder { [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public static class Binder { public static CallSiteBinder BinaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return null; } public static CallSiteBinder Convert(CSharpBinderFlags flags, Type type, Type context) { return null; } public static CallSiteBinder GetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return null; } public static CallSiteBinder GetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return null; } public static CallSiteBinder Invoke(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return null; } public static CallSiteBinder InvokeMember(CSharpBinderFlags flags, string name, IEnumerable<Type> typeArguments, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return null; } public static CallSiteBinder InvokeConstructor(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return null; } public static CallSiteBinder IsEvent(CSharpBinderFlags flags, string name, Type context) { return null; } public static CallSiteBinder SetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return null; } public static CallSiteBinder SetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return null; } public static CallSiteBinder UnaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo) { return null; } } [Flags] [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public enum CSharpBinderFlags { None = 0, CheckedContext = 1, InvokeSimpleName = 2, InvokeSpecialName = 4, BinaryOperationLogical = 8, ConvertExplicit = 16, ConvertArrayIndex = 32, ResultIndexed = 64, ValueFromCompoundAssignment = 128, ResultDiscarded = 256, } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public sealed class CSharpArgumentInfo { public static CSharpArgumentInfo Create(CSharpArgumentInfoFlags flags, string name) { return null; } } [Flags] [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public enum CSharpArgumentInfoFlags { None = 0, UseCompileTimeType = 1, Constant = 2, NamedArgument = 4, IsRef = 8, IsOut = 16, IsStaticType = 32, } } namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] public sealed class DebuggerStepThroughAttribute : Attribute { } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Nuke.Common; using Nuke.Common.CI; using Nuke.Common.CI.AppVeyor; using Nuke.Common.CI.GitHubActions; using Nuke.Common.Git; using Nuke.Common.IO; using Nuke.Common.ProjectModel; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.MSBuild; using Nuke.Common.Utilities.Collections; using static Nuke.Common.IO.FileSystemTasks; using static Nuke.Common.Tooling.ProcessTasks; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Common.Tools.MSBuild.MSBuildTasks; [ShutdownDotNetAfterServerBuild] partial class Build : NukeBuild { /// Support plugins are available for: /// - JetBrains ReSharper https://nuke.build/resharper /// - JetBrains Rider https://nuke.build/rider /// - Microsoft VisualStudio https://nuke.build/visualstudio /// - Microsoft VSCode https://nuke.build/vscode public static int Main () => Execute<Build>(x => x.Compile); [Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")] readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release; [Parameter("Build EMS")] readonly bool BuildEms = false; [Parameter("Version")] readonly string ProjectVersion = "3.0.0"; [Solution] readonly Solution Solution; [GitRepository] readonly GitRepository GitRepository; [CI] readonly AppVeyor AppVeyor; [CI] readonly GitHubActions GitHubActions; AbsolutePath SourceDirectory => RootDirectory / "src"; AbsolutePath TestsDirectory => RootDirectory / "test"; AbsolutePath BuildDirectory => RootDirectory / "build"; AbsolutePath ExamplesDirectory => RootDirectory / "examples"; AbsolutePath ArtifactsDirectory => RootDirectory / "artifacts"; Target Clean => _ => _ .Before(Restore) .Executes(() => { SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(DeleteDirectory); TestsDirectory.GlobDirectories("**/bin", "**/obj").ForEach(DeleteDirectory); EnsureCleanDirectory(ArtifactsDirectory); EnsureCleanDirectory(BuildDirectory); }); Target Restore => _ => _ .Executes(() => { DotNetRestore(s => s .SetProjectFile(Solution)); }); Target Compile => _ => _ .DependsOn(CompileSolution, CompileExamples); Target CompileSolution => _ => _ .DependsOn(Restore) .Executes(() => { DotNetBuild(s => s .SetProjectFile(Solution) .SetConfiguration(Configuration) .EnableNoRestore() ); }); Target CompileExamples => _ => _ .OnlyWhenStatic(() => EnvironmentInfo.IsWin) .DependsOn(CompileSolution, PackBinaries) .Executes(() => { foreach (var solutionFile in ExamplesDirectory.GlobFiles("**/*.sln")) { if (solutionFile.ToString().Contains("Spring.EmsQuickStart") && !BuildEms || solutionFile.ToString().Contains("Spring.Examples.Pool") || solutionFile.ToString().Contains("SpringAir") || solutionFile.ToString().Contains("Spring.Web.Extensions.Example") || solutionFile.ToString().Contains("Spring.WebQuickStart")) { continue; } MSBuild(s => s .SetTargets("Restore", "Rebuild") .SetConfiguration(Configuration) .SetTargetPath(solutionFile) .SetNodeReuse(false) .SetVerbosity(MSBuildVerbosity.Minimal) ); } }); Target Antlr => _ => _ .Executes(() => { var projectDir = Solution.GetProject("Spring.Core"); var expressionsDir = Path.Combine(projectDir.Directory, "Expressions"); var antlrExecutable = Path.Combine(Solution.Directory, "build-support/tools/antlr-2.7.6/antlr-2.7.6.exe"); var process = StartProcess( toolPath: antlrExecutable, arguments: $"-o {expressionsDir}/Parser {expressionsDir}/Expression.g" ); process.WaitForExit(); }); Target Pack => _ => _ .After(Test) .DependsOn(Restore) .Executes(() => { var packTargets = GetActiveProjects() .Where(x => !x.Name.EndsWith(".Tests")); var version = TagVersion; var suffix = ""; if (string.IsNullOrWhiteSpace(version)) { version = ProjectVersion; suffix = "develop-" + DateTime.UtcNow.ToString("yyyyMMddHHmm"); } foreach (var project in packTargets) { DotNetPack(s => s .SetProject(project.Path) .SetVersion(version) .SetVersionSuffix(suffix) .SetConfiguration(Configuration.Release) .EnableNoRestore() .SetOutputDirectory(ArtifactsDirectory) ); } }); Target PackBinaries => _ => _ .DependsOn(CompileSolution) .Executes(() => { var binDirectory = RootDirectory / "bin"; EnsureCleanDirectory(binDirectory); var moduleNames = new[] { "Common.Logging", "Common.Logging.Core", "Spring.Core", "Spring.Aop", "Spring.Data", "Spring.Data.NHibernate*", "Spring.Web", "Spring.Web.Mvc5", "Spring.Web.Extensions", "Spring.Services", "Spring.Testing.NUnit", "Spring.Testing.Microsoft", "Spring.Messaging.Ems", "Spring.Messaging.Nms", "Spring.Messaging", "Spring.Scheduling.Quartz3", "Spring.Template.Velocity", "Spring.Web.Conversation.NHibernate5", }; var patterns = moduleNames .SelectMany(x => new [] { "**/" + Configuration + "/**/" + x + ".dll", "**/" + Configuration + "/**/" + x + ".xml", "**/" + Configuration + "/**/" + x + ".pdb" }) .ToArray(); foreach (var file in BuildDirectory.GlobFiles(patterns)) { CopyFileToDirectory(file, binDirectory / "net", FileExistsPolicy.OverwriteIfNewer); } }); IEnumerable<Project> GetActiveProjects() { var packTargets = Solution.GetProjects("*") .Where(x => x.Name != "Spring.Messaging.Ems" || BuildEms) .Where(x => !x.Name.Contains("_build")); return packTargets; } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace Mandrill.Model { public class MandrillMessage { private List<MandrillAttachment> _attachments; private List<MandrillMergeVar> _globalMergeVars; private List<string> _googleAnalyticsDomains; private Dictionary<string, object> _headers; private List<MandrillImage> _images; private List<MandrillRcptMergeVar> _mergeVars; private Dictionary<string, string> _metadata; private List<MandrillRcptMetadata> _recipientMetadata; private List<string> _tags; private List<MandrillMailAddress> _to; public MandrillMessage() { } public MandrillMessage(MandrillMailAddress from, MandrillMailAddress to) { FromEmail = from.Email; FromName = from.Name; To.Add(to); } public MandrillMessage(string from, string to) : this(new MandrillMailAddress(from), new MandrillMailAddress(to)) { } public MandrillMessage(string from, string to, string subject, string body) : this(from, to) { Subject = subject; if (body != null) { if (body.StartsWith("<")) { Html = body; } else { Text = body; } } } public string Html { get; set; } public string Text { get; set; } public string Subject { get; set; } public string FromEmail { get; set; } public string FromName { get; set; } public List<MandrillMailAddress> To { get { return _to ?? (_to = new List<MandrillMailAddress>()); } set { _to = value; } } public Dictionary<string, object> Headers { get { return _headers ?? (_headers = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)); } set { _headers = value; } } public bool? Important { get; set; } public bool? TrackOpens { get; set; } public bool? TrackClicks { get; set; } public bool? AutoText { get; set; } public bool? AutoHtml { get; set; } public bool? InlineCss { get; set; } public bool? UrlStripQs { get; set; } public bool? PreserveRecipients { get; set; } public bool? ViewContentLink { get; set; } public string BccAddress { get; set; } public string TrackingDomain { get; set; } public string SigningDomain { get; set; } public string ReturnPathDomain { get; set; } public bool? Merge { get; set; } public MandrillMessageMergeLanguage? MergeLanguage { get; set; } public List<MandrillMergeVar> GlobalMergeVars { get { return _globalMergeVars ?? (_globalMergeVars = new List<MandrillMergeVar>()); } set { _globalMergeVars = value; } } public List<MandrillRcptMergeVar> MergeVars { get { return _mergeVars ?? (_mergeVars = new List<MandrillRcptMergeVar>()); } set { _mergeVars = value; } } public List<string> Tags { get { return _tags ?? (_tags = new List<string>()); } set { _tags = value; } } public string Subaccount { get; set; } public List<string> GoogleAnalyticsDomains { get { return _googleAnalyticsDomains ?? (_googleAnalyticsDomains = new List<string>()); } set { _googleAnalyticsDomains = value; } } public string GoogleAnalyticsCampaign { get; set; } public Dictionary<string, string> Metadata { get { return _metadata ?? (_metadata = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)); } set { _metadata = value; } } public List<MandrillRcptMetadata> RecipientMetadata { get { return _recipientMetadata ?? (_recipientMetadata = new List<MandrillRcptMetadata>()); } set { _recipientMetadata = value; } } public List<MandrillAttachment> Attachments { get { return _attachments ?? (_attachments = new List<MandrillAttachment>()); } set { _attachments = value; } } public List<MandrillImage> Images { get { return _images ?? (_images = new List<MandrillImage>()); } set { _images = value; } } [JsonIgnore] public string ReplyTo { get { object value; if (Headers.TryGetValue("Reply-To", out value)) { return value as string; } return null; } set { Headers["Reply-To"] = value; } } public void AddTo(string email) { AddTo(email, null, null); } public void AddTo(string email, string name) { AddTo(email, name, null); } public void AddTo(string email, string name, MandrillMailAddressType? type) { To.Add(new MandrillMailAddress(email, name) {Type = type}); } public void AddGlobalMergeVars(string name, string content) { GlobalMergeVars.Add(new MandrillMergeVar {Name = name, Content = content}); } public void AddGlobalMergeVars(string name, dynamic content) { GlobalMergeVars.Add(new MandrillMergeVar { Name = name, Content = content }); } public void AddRcptMergeVars(string rcptEmail, string name, string content) { var mergeVar = MergeVars.FirstOrDefault(x => x.Rcpt == rcptEmail); if (mergeVar == null) { MergeVars.Add(mergeVar = new MandrillRcptMergeVar {Rcpt = rcptEmail}); } mergeVar.Vars.Add(new MandrillMergeVar { Name = name, Content = content }); } public void AddRcptMergeVars(string rcptEmail, string name, dynamic content) { var mergeVar = MergeVars.FirstOrDefault(x => x.Rcpt == rcptEmail); if (mergeVar == null) { MergeVars.Add(mergeVar = new MandrillRcptMergeVar {Rcpt = rcptEmail}); } mergeVar.Vars.Add(new MandrillMergeVar { Name = name, Content = content }); } public void AddMetadata(string key, string value) { Metadata[key] = value; } public void AddRecipientMetadata(string rcptEmail, string key, string value) { var metadata = RecipientMetadata.FirstOrDefault(x => x.Rcpt == rcptEmail); if (metadata == null) { RecipientMetadata.Add(metadata = new MandrillRcptMetadata {Rcpt = rcptEmail}); } metadata.Values[key] = value; } public void AddHeader(string key, string value) { Headers[key] = value; } public void AddHeader(string key, IEnumerable<string> values) { Headers[key] = values.ToArray(); } } }
/*- * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * See the file LICENSE for license information. * */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class RecnoDatabaseTest : DatabaseTest { [TestFixtureSetUp] public void SetUpTestFixture() { testFixtureName = "RecnoDatabaseTest"; base.SetUpTestfixture(); } [Test] public void TestOpenExistingRecnoDB() { testName = "TestOpenExistingRecnoDB"; SetUpTest(true); string recnoDBFileName = testHome + "/" + testName + ".db"; RecnoDatabaseConfig recConfig = new RecnoDatabaseConfig(); recConfig.Creation = CreatePolicy.ALWAYS; RecnoDatabase recDB = RecnoDatabase.Open( recnoDBFileName, recConfig); recDB.Close(); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); string backingFile = testHome + "/backingFile"; File.Copy(recnoDBFileName, backingFile); dbConfig.BackingFile = backingFile; RecnoDatabase db = RecnoDatabase.Open(recnoDBFileName, dbConfig); Assert.AreEqual(db.Type, DatabaseType.RECNO); db.Close(); } [Test] public void TestOpenNewRecnoDB() { RecnoDatabase recnoDB; RecnoDatabaseConfig recnoConfig; testName = "TestOpenNewRecnoDB"; SetUpTest(true); string recnoDBFileName = testHome + "/" + testName + ".db"; XmlElement xmlElem = Configuration.TestSetUp( testFixtureName, testName); recnoConfig = new RecnoDatabaseConfig(); RecnoDatabaseConfigTest.Config(xmlElem, ref recnoConfig, true); recnoDB = RecnoDatabase.Open(recnoDBFileName, recnoConfig); Confirm(xmlElem, recnoDB, true); recnoDB.Close(); } [Test] public void TestAppendWithoutTxn() { testName = "TestAppendWithoutTxn"; SetUpTest(true); string recnoDBFileName = testHome + "/" + testName + ".db"; RecnoDatabaseConfig recnoConfig = new RecnoDatabaseConfig(); recnoConfig.Creation = CreatePolicy.ALWAYS; RecnoDatabase recnoDB = RecnoDatabase.Open( recnoDBFileName, recnoConfig); DatabaseEntry data = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("data")); uint num = recnoDB.Append(data); DatabaseEntry key = new DatabaseEntry( BitConverter.GetBytes(num)); Assert.IsTrue(recnoDB.Exists(key)); KeyValuePair<DatabaseEntry, DatabaseEntry> record = recnoDB.Get(key); Assert.IsTrue(data.Data.Length == record.Value.Data.Length); for (int i = 0; i < data.Data.Length; i++) Assert.IsTrue(data.Data[i] == record.Value.Data[i]); recnoDB.Close(); } [Test] public void TestCompact() { testName = "TestCompact"; SetUpTest(true); string recnoDBFileName = testHome + "/" + testName + ".db"; RecnoDatabaseConfig recnoConfig = new RecnoDatabaseConfig(); recnoConfig.Creation = CreatePolicy.ALWAYS; recnoConfig.Length = 512; DatabaseEntry key, data; RecnoDatabase recnoDB; using (recnoDB = RecnoDatabase.Open( recnoDBFileName, recnoConfig)) { for (int i = 1; i <= 5000; i++) { data = new DatabaseEntry( BitConverter.GetBytes(i)); recnoDB.Append(data); } for (int i = 1; i <= 5000; i++) { if (i > 500 && (i % 5 != 0)) { key = new DatabaseEntry( BitConverter.GetBytes(i)); recnoDB.Delete(key); } } int startInt = 1; int stopInt = 2500; DatabaseEntry start, stop; start = new DatabaseEntry( BitConverter.GetBytes(startInt)); stop = new DatabaseEntry( BitConverter.GetBytes(stopInt)); Assert.IsTrue(recnoDB.Exists(start)); Assert.IsTrue(recnoDB.Exists(stop)); CompactConfig cCfg = new CompactConfig(); cCfg.start = start; cCfg.stop = stop; cCfg.FillPercentage = 30; cCfg.Pages = 1; cCfg.returnEnd = true; cCfg.Timeout = 5000; cCfg.TruncatePages = true; CompactData compactData = recnoDB.Compact(cCfg); Assert.IsNotNull(compactData.End); Assert.AreNotEqual(0, compactData.PagesExamined); } } [Test] public void TestMessageFile() { testName = "TestMessageFile"; SetUpTest(true); // Configure and open an environment. DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseMPool = true; DatabaseEnvironment env = DatabaseEnvironment.Open( testHome, envConfig); // Configure and open a database. RecnoDatabaseConfig DBConfig = new RecnoDatabaseConfig(); DBConfig.Env = env; DBConfig.Creation = CreatePolicy.IF_NEEDED; string DBFileName = testName + ".db"; RecnoDatabase db = RecnoDatabase.Open( DBFileName, DBConfig); // Confirm message file does not exist. string messageFile = testHome + "/" + "msgfile"; Assert.AreEqual(false, File.Exists(messageFile)); // Call set_msgfile() of db. db.Msgfile = messageFile; // Print db statistic to message file. db.PrintStats(true); // Confirm message file exists now. Assert.AreEqual(true, File.Exists(messageFile)); db.Msgfile = ""; string line = null; // Read the third line of message file. System.IO.StreamReader file = new System.IO.StreamReader(@"" + messageFile); line = file.ReadLine(); line = file.ReadLine(); line = file.ReadLine(); // Confirm the message file is not empty. Assert.AreEqual(line, "DB handle information:"); file.Close(); // Close database and environment. db.Close(); env.Close(); } [Test] public void TestStats() { testName = "TestStats"; SetUpTest(true); string dbFileName = testHome + "/" + testName + ".db"; RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); ConfigCase1(dbConfig); RecnoDatabase db = RecnoDatabase.Open(dbFileName, dbConfig); RecnoStats stats = db.Stats(); ConfirmStatsPart1Case1(stats); // Put 1000 records into the database. PutRecordCase1(db, null); stats = db.Stats(); ConfirmStatsPart2Case1(stats); // Delete 500 records. for (int i = 250; i <= 750; i++) db.Delete(new DatabaseEntry(BitConverter.GetBytes(i))); stats = db.Stats(); ConfirmStatsPart3Case1(stats); db.Close(); } [Test] public void TestStatsInTxn() { testName = "TestStatsInTxn"; SetUpTest(true); StatsInTxn(testHome, testName, false); } [Test] public void TestStatsWithIsolation() { testName = "TestStatsWithIsolation"; SetUpTest(true); StatsInTxn(testHome, testName, true); } public void StatsInTxn(string home, string name, bool ifIsolation) { DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); EnvConfigCase1(envConfig); DatabaseEnvironment env = DatabaseEnvironment.Open( home, envConfig); Transaction openTxn = env.BeginTransaction(); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); ConfigCase1(dbConfig); dbConfig.Env = env; RecnoDatabase db = RecnoDatabase.Open(name + ".db", dbConfig, openTxn); openTxn.Commit(); Transaction statsTxn = env.BeginTransaction(); RecnoStats stats; RecnoStats fastStats; if (ifIsolation == false) { stats = db.Stats(statsTxn); fastStats = db.FastStats(statsTxn); } else { stats = db.Stats(statsTxn, Isolation.DEGREE_ONE); fastStats = db.FastStats(statsTxn, Isolation.DEGREE_ONE); } ConfirmStatsPart1Case1(stats); // Put 1000 records into the database. PutRecordCase1(db, statsTxn); if (ifIsolation == false) { stats = db.Stats(statsTxn); fastStats = db.FastStats(statsTxn); } else { stats = db.Stats(statsTxn, Isolation.DEGREE_TWO); fastStats = db.FastStats(statsTxn, Isolation.DEGREE_TWO); } ConfirmStatsPart2Case1(stats); // Delete 500 records. for (int i = 250; i <= 750; i++) db.Delete(new DatabaseEntry(BitConverter.GetBytes(i)), statsTxn); if (ifIsolation == false) { stats = db.Stats(statsTxn); fastStats = db.FastStats(statsTxn); } else { stats = db.Stats(statsTxn, Isolation.DEGREE_THREE); fastStats = db.FastStats(statsTxn, Isolation.DEGREE_THREE); } ConfirmStatsPart3Case1(stats); statsTxn.Commit(); db.Close(); env.Close(); } public void EnvConfigCase1(DatabaseEnvironmentConfig cfg) { cfg.Create = true; cfg.UseTxns = true; cfg.UseMPool = true; cfg.UseLogging = true; } public void ConfigCase1(RecnoDatabaseConfig dbConfig) { dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.PageSize = 4096; dbConfig.Length = 4000; dbConfig.PadByte = 256; } public void PutRecordCase1(RecnoDatabase db, Transaction txn) { for (int i = 1; i <= 1000; i++) { if (txn == null) db.Put(new DatabaseEntry( BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i))); else db.Put(new DatabaseEntry( BitConverter.GetBytes(i)), new DatabaseEntry( BitConverter.GetBytes(i)), txn); } } public void ConfirmStatsPart1Case1(RecnoStats stats) { Assert.AreEqual(1, stats.EmptyPages); Assert.AreEqual(1, stats.Levels); Assert.AreNotEqual(0, stats.MagicNumber); Assert.AreEqual(10, stats.MetadataFlags); Assert.AreEqual(2, stats.MinKey); Assert.AreEqual(2, stats.nPages); Assert.AreEqual(4096, stats.PageSize); Assert.AreEqual(4000, stats.RecordLength); Assert.AreEqual(256, stats.RecordPadByte); Assert.AreEqual(10, stats.Version); } public void ConfirmStatsPart2Case1(RecnoStats stats) { Assert.AreEqual(0, stats.DuplicatePages); Assert.AreEqual(0, stats.DuplicatePagesFreeBytes); Assert.AreNotEqual(0, stats.InternalPages); Assert.AreNotEqual(0, stats.InternalPagesFreeBytes); Assert.AreNotEqual(0, stats.LeafPages); Assert.AreNotEqual(0, stats.LeafPagesFreeBytes); Assert.AreEqual(1000, stats.nData); Assert.AreEqual(1000, stats.nKeys); Assert.AreNotEqual(0, stats.OverflowPages); Assert.AreNotEqual(0, stats.OverflowPagesFreeBytes); } public void ConfirmStatsPart3Case1(RecnoStats stats) { Assert.AreNotEqual(0, stats.FreePages); } [Test] public void TestTruncateUnusedPages() { testName = "TestTruncateUnusedPages"; SetUpTest(true); DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseCDB = true; envConfig.UseMPool = true; DatabaseEnvironment env = DatabaseEnvironment.Open( testHome, envConfig); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; dbConfig.PageSize = 512; RecnoDatabase db = RecnoDatabase.Open( testName + ".db", dbConfig); ModifyRecordsInDB(db, null); Assert.Less(0, db.TruncateUnusedPages()); db.Close(); env.Close(); } [Test] public void TestTruncateUnusedPagesInTxn() { testName = "TestTruncateUnusedPagesInTxn"; SetUpTest(true); DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseLogging = true; envConfig.UseMPool = true; envConfig.UseTxns = true; DatabaseEnvironment env = DatabaseEnvironment.Open( testHome, envConfig); Transaction openTxn = env.BeginTransaction(); RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; dbConfig.PageSize = 512; RecnoDatabase db = RecnoDatabase.Open( testName + ".db", dbConfig, openTxn); openTxn.Commit(); Transaction modifyTxn = env.BeginTransaction(); ModifyRecordsInDB(db, modifyTxn); Assert.Less(0, db.TruncateUnusedPages(modifyTxn)); modifyTxn.Commit(); db.Close(); env.Close(); } public void ModifyRecordsInDB(RecnoDatabase db, Transaction txn) { uint[] recnos = new uint[100]; if (txn == null) { // Add a lot of records into database. for (int i = 0; i < 100; i++) recnos[i] = db.Append(new DatabaseEntry( new byte[10240])); // Remove some records from database. for (int i = 30; i < 100; i++) db.Delete(new DatabaseEntry( BitConverter.GetBytes(recnos[i]))); } else { // Add a lot of records into database in txn. for (int i = 0; i < 100; i++) recnos[i] = db.Append(new DatabaseEntry( new byte[10240]), txn); // Remove some records from database in txn. for (int i = 30; i < 100; i++) db.Delete(new DatabaseEntry( BitConverter.GetBytes(recnos[i])), txn); } } public static void Confirm(XmlElement xmlElem, RecnoDatabase recnoDB, bool compulsory) { DatabaseTest.Confirm(xmlElem, recnoDB, compulsory); // Confirm recno database specific field/property Configuration.ConfirmInt(xmlElem, "Delimiter", recnoDB.RecordDelimiter, compulsory); Configuration.ConfirmUint(xmlElem, "Length", recnoDB.RecordLength, compulsory); Configuration.ConfirmInt(xmlElem, "PadByte", recnoDB.RecordPad, compulsory); Configuration.ConfirmBool(xmlElem, "Renumber", recnoDB.Renumber, compulsory); Configuration.ConfirmBool(xmlElem, "Snapshot", recnoDB.Snapshot, compulsory); Assert.AreEqual(DatabaseType.RECNO, recnoDB.Type); string type = recnoDB.Type.ToString(); Assert.IsNotNull(type); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management; using Microsoft.WindowsAzure.Management.Models; namespace Microsoft.WindowsAzure.Management { /// <summary> /// Operations for managing affinity groups beneath your subscription. /// (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460798.aspx /// for more information) /// </summary> public static partial class AffinityGroupOperationsExtensions { /// <summary> /// The Create Affinity Group operation creates a new affinity group /// for the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Affinity Group operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Create(this IAffinityGroupOperations operations, AffinityGroupCreateParameters parameters) { try { return operations.CreateAsync(parameters).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The Create Affinity Group operation creates a new affinity group /// for the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Affinity Group operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> CreateAsync(this IAffinityGroupOperations operations, AffinityGroupCreateParameters parameters) { return operations.CreateAsync(parameters, CancellationToken.None); } /// <summary> /// The Delete Affinity Group operation deletes an affinity group in /// the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations. /// </param> /// <param name='affinityGroupName'> /// The name of your affinity group. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Delete(this IAffinityGroupOperations operations, string affinityGroupName) { try { return operations.DeleteAsync(affinityGroupName).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The Delete Affinity Group operation deletes an affinity group in /// the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations. /// </param> /// <param name='affinityGroupName'> /// The name of your affinity group. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> DeleteAsync(this IAffinityGroupOperations operations, string affinityGroupName) { return operations.DeleteAsync(affinityGroupName, CancellationToken.None); } /// <summary> /// The Get Affinity Group Properties operation returns the system /// properties associated with the specified affinity group. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations. /// </param> /// <param name='affinityGroupName'> /// The name of the desired affinity group as returned by the name /// element of the List Affinity Groups operation. /// </param> /// <returns> /// The Get Affinity Group operation response. /// </returns> public static AffinityGroupGetResponse Get(this IAffinityGroupOperations operations, string affinityGroupName) { try { return operations.GetAsync(affinityGroupName).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The Get Affinity Group Properties operation returns the system /// properties associated with the specified affinity group. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations. /// </param> /// <param name='affinityGroupName'> /// The name of the desired affinity group as returned by the name /// element of the List Affinity Groups operation. /// </param> /// <returns> /// The Get Affinity Group operation response. /// </returns> public static Task<AffinityGroupGetResponse> GetAsync(this IAffinityGroupOperations operations, string affinityGroupName) { return operations.GetAsync(affinityGroupName, CancellationToken.None); } /// <summary> /// The List Affinity Groups operation lists the affinity groups /// associated with the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations. /// </param> /// <returns> /// The List Affinity Groups operation response. /// </returns> public static AffinityGroupListResponse List(this IAffinityGroupOperations operations) { try { return operations.ListAsync().Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The List Affinity Groups operation lists the affinity groups /// associated with the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations. /// </param> /// <returns> /// The List Affinity Groups operation response. /// </returns> public static Task<AffinityGroupListResponse> ListAsync(this IAffinityGroupOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// The Update Affinity Group operation updates the label and/or the /// description for an affinity group for the specified subscription. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations. /// </param> /// <param name='affinityGroupName'> /// The name of your affinity group. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Affinity Group operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Update(this IAffinityGroupOperations operations, string affinityGroupName, AffinityGroupUpdateParameters parameters) { try { return operations.UpdateAsync(affinityGroupName, parameters).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The Update Affinity Group operation updates the label and/or the /// description for an affinity group for the specified subscription. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations. /// </param> /// <param name='affinityGroupName'> /// The name of your affinity group. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Affinity Group operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> UpdateAsync(this IAffinityGroupOperations operations, string affinityGroupName, AffinityGroupUpdateParameters parameters) { return operations.UpdateAsync(affinityGroupName, parameters, CancellationToken.None); } } }