context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // 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 System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Store; namespace Microsoft.WindowsAzure.Management.Store { /// <summary> /// The Windows Azure Store API is a REST API for managing Windows Azure /// Store add-ins. /// </summary> public partial class StoreManagementClient : ServiceClient<StoreManagementClient>, Microsoft.WindowsAzure.Management.Store.IStoreManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } 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 IAddOnOperations _addOns; /// <summary> /// Provides REST operations for working with Store add-ins from the /// Windows Azure store service. /// </summary> public virtual IAddOnOperations AddOns { get { return this._addOns; } } private ICloudServiceOperations _cloudServices; /// <summary> /// Provides REST operations for working with cloud services from the /// Windows Azure store service. /// </summary> public virtual ICloudServiceOperations CloudServices { get { return this._cloudServices; } } /// <summary> /// Initializes a new instance of the StoreManagementClient class. /// </summary> private StoreManagementClient() : base() { this._addOns = new AddOnOperations(this); this._cloudServices = new CloudServiceOperations(this); this._apiVersion = "2013-06-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the StoreManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public StoreManagementClient(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 StoreManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public StoreManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the StoreManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> private StoreManagementClient(HttpClient httpClient) : base(httpClient) { this._addOns = new AddOnOperations(this); this._cloudServices = new CloudServiceOperations(this); this._apiVersion = "2013-06-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the StoreManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public StoreManagementClient(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 StoreManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public StoreManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// StoreManagementClient instance /// </summary> /// <param name='client'> /// Instance of StoreManagementClient to clone to /// </param> protected override void Clone(ServiceClient<StoreManagementClient> client) { base.Clone(client); if (client is StoreManagementClient) { StoreManagementClient clonedClient = ((StoreManagementClient)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 /// thespecified 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. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx /// for more information) /// </summary> /// <param name='requestId'> /// Required. The request ID for the request you wish to track. The /// request ID is returned in the x-ms-request-id response header for /// every request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken) { // Validate if (requestId == null) { throw new ArgumentNullException("requestId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("requestId", requestId); Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/operations/" + requestId.Trim(); string baseUrl = this.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure")); if (operationElement != null) { XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.SqlClient; using System.Text; using Xunit; namespace System.Data.Odbc.Tests { public static class OdbcParameterTests { [CheckConnStrSetupFact] public static void RunTest() { string str1000 = null; string str2000 = null; string str4000 = null; string str5000 = null; string str8000 = ""; for (int i = 0; i < 800; i++) { str8000 += "0123456789"; if (i == 99) { str1000 = str8000; } else if (i == 199) { str2000 = str8000; } else if (i == 399) { str4000 = str8000; } else if (i == 499) { str5000 = str8000; } } byte[] byte1000 = Encoding.ASCII.GetBytes(str1000); byte[] byte2000 = Encoding.ASCII.GetBytes(str2000); byte[] byte4000 = Encoding.ASCII.GetBytes(str4000); byte[] byte5000 = Encoding.ASCII.GetBytes(str5000); byte[] byte8000 = Encoding.ASCII.GetBytes(str8000); object output = null; int inputLength = 0; int outputLength = 0; RunTestProcedure("VARBINARY", 8000, byte8000, out output, out inputLength, out outputLength); string outputStr = Encoding.ASCII.GetString(output as byte[]); Assert.Equal(str8000, outputStr); Assert.Equal(byte8000.Length, inputLength); Assert.Equal(byte8000.Length, outputLength); RunTestProcedure("VARBINARY", 8000, byte5000, out output, out inputLength, out outputLength); outputStr = Encoding.ASCII.GetString(output as byte[]); Assert.Equal(str8000, outputStr); Assert.Equal(byte5000.Length, inputLength); Assert.Equal(byte8000.Length, outputLength); RunTestProcedure("VARBINARY", 8000, byte4000, out output, out inputLength, out outputLength); outputStr = Encoding.ASCII.GetString(output as byte[]); Assert.Equal(str8000, outputStr); Assert.Equal(byte4000.Length, inputLength); Assert.Equal(str8000.Length, outputLength); RunTestProcedure("VARBINARY", 8000, byte2000, out output, out inputLength, out outputLength); outputStr = Encoding.ASCII.GetString(output as byte[]); Assert.Equal(str4000, outputStr); Assert.Equal(byte2000.Length, inputLength); Assert.Equal(str4000.Length, outputLength); RunTestProcedure("VARBINARY", 8000, byte1000, out output, out inputLength, out outputLength); outputStr = Encoding.ASCII.GetString(output as byte[]); Assert.Equal(str2000, outputStr); Assert.Equal(byte1000.Length, inputLength); Assert.Equal(byte2000.Length, outputLength); RunTestProcedure("VARCHAR", 8000, str8000, out output, out inputLength, out outputLength); outputStr = output as string; Assert.Equal(str8000, outputStr); Assert.Equal(str8000.Length, inputLength); Assert.Equal(str8000.Length, outputLength); RunTestProcedure("VARCHAR", 8000, str5000, out output, out inputLength, out outputLength); outputStr = output as string; Assert.Equal(str8000, outputStr); Assert.Equal(str5000.Length, inputLength); Assert.Equal(str8000.Length, outputLength); RunTestProcedure("VARCHAR", 8000, str4000, out output, out inputLength, out outputLength); outputStr = output as string; Assert.Equal(str8000, outputStr); Assert.Equal(str4000.Length, inputLength); Assert.Equal(str8000.Length, outputLength); RunTestProcedure("VARCHAR", 8000, str2000, out output, out inputLength, out outputLength); outputStr = output as string; Assert.Equal(str4000, outputStr); Assert.Equal(str2000.Length, inputLength); Assert.Equal(str4000.Length, outputLength); RunTestProcedure("VARCHAR", 8000, str1000, out output, out inputLength, out outputLength); outputStr = output as string; Assert.Equal(str2000, outputStr); Assert.Equal(str1000.Length, inputLength); Assert.Equal(str2000.Length, outputLength); RunTestProcedure("NVARCHAR", 4000, str8000, out output, out inputLength, out outputLength); outputStr = output as string; Assert.Equal(str4000, outputStr); Assert.Equal(str4000.Length * 2, inputLength); // since NVARCHAR takes 2 bytes per character Assert.Equal(str4000.Length * 2, outputLength); RunTestProcedure("NVARCHAR", 4000, str5000, out output, out inputLength, out outputLength); outputStr = output as string; Assert.Equal(str4000, outputStr); Assert.Equal(str4000.Length * 2, inputLength); Assert.Equal(str4000.Length * 2, outputLength); RunTestProcedure("NVARCHAR", 4000, str4000, out output, out inputLength, out outputLength); outputStr = output as string; Assert.Equal(str4000, outputStr); Assert.Equal(str4000.Length * 2, inputLength); Assert.Equal(str4000.Length * 2, outputLength); RunTestProcedure("NVARCHAR", 4000, str2000, out output, out inputLength, out outputLength); outputStr = output as string; Assert.Equal(str4000, outputStr); Assert.Equal(str2000.Length * 2, inputLength); Assert.Equal(str4000.Length * 2, outputLength); RunTestProcedure("NVARCHAR", 4000, str1000, out output, out inputLength, out outputLength); outputStr = output as string; Assert.Equal(str2000, outputStr); Assert.Equal(str1000.Length * 2, inputLength); Assert.Equal(str2000.Length * 2, outputLength); } private static void RunTestProcedure(string procDataType, int procDataSize, object v1, out object v2, out int v3, out int v4) { string procName = DataTestUtility.GetUniqueName("ODBCTEST", "", ""); string removeExistingStoredProcSql = $"IF OBJECT_ID('{procName}', 'P') IS NOT NULL " + $"DROP PROCEDURE {procName};"; string createTestStoredProcSql = $"CREATE PROCEDURE {procName} (" + $"@v1 {procDataType}({procDataSize}), " + $"@v2 {procDataType}({procDataSize}) OUT, " + "@v3 INTEGER OUT, " + "@v4 INTEGER OUT) " + "AS BEGIN " + "SET @v2 = @v1 + @v1; " + "SET @v3 = datalength(@v1); " + "SET @v4 = datalength(@v2); " + "END;"; try { DataTestUtility.RunNonQuery(DataTestUtility.OdbcConnStr, removeExistingStoredProcSql); DataTestUtility.RunNonQuery(DataTestUtility.OdbcConnStr, createTestStoredProcSql); DbAccessor dbAccessUtil = new DbAccessor(); dbAccessUtil.connectSqlServer(DataTestUtility.OdbcConnStr); dbAccessUtil.callProc("{ call "+ procName+"(?,?,?,?) }", procDataType, procDataSize, v1, out v2, out v3, out v4); dbAccessUtil.commit(); dbAccessUtil.disconnect(); } finally { DataTestUtility.RunNonQuery(DataTestUtility.OdbcConnStr, removeExistingStoredProcSql); } } private class DbAccessor { private OdbcConnection con = null; private OdbcTransaction trn = null; public bool connectSqlServer(string connStr) { if (con == null) { con = new OdbcConnection(connStr); } con.Open(); trn = con.BeginTransaction(); return true; } public void disconnect() { if (trn != null) { trn.Rollback(); trn.Dispose(); trn = null; } if (con != null) { con.Close(); con.Dispose(); con = null; } } public void callProc(string sql, string procDataType, int procDataSize, object v1, out object v2, out int v3, out int v4) { using (OdbcCommand command = new OdbcCommand(sql, con, trn)) { command.Parameters.Clear(); command.CommandType = CommandType.StoredProcedure; OdbcType dataType = OdbcType.NVarChar; switch (procDataType.ToUpper()) { case "VARBINARY": dataType = OdbcType.VarBinary; break; case "VARCHAR": dataType = OdbcType.VarChar; break; } command.Parameters.Add("@v1", dataType, procDataSize); command.Parameters.Add("@v2", dataType, procDataSize); command.Parameters.Add("@v3", OdbcType.Int); command.Parameters.Add("@v4", OdbcType.Int); command.Parameters["@v1"].Direction = ParameterDirection.Input; command.Parameters["@v2"].Direction = ParameterDirection.Output; command.Parameters["@v3"].Direction = ParameterDirection.Output; command.Parameters["@v4"].Direction = ParameterDirection.Output; command.Parameters["@v1"].Value = v1; command.ExecuteNonQuery(); v2 = command.Parameters["@v2"].Value; v3 = Int32.Parse(command.Parameters["@v3"].Value.ToString()); v4 = Int32.Parse(command.Parameters["@v4"].Value.ToString()); } } public bool commit() { if (trn == null) { return false; } trn.Commit(); trn = null; return true; } public bool rollback() { if (trn == null) { return false; } trn.Rollback(); trn = null; return true; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.IO { using System; using System.Runtime.CompilerServices; /// <summary> /// Helper methods for encoding and decoding integer values. /// </summary> internal static class IntegerHelper { public const int MaxBytesVarInt16 = 3; public const int MaxBytesVarInt32 = 5; public const int MaxBytesVarInt64 = 10; public static int EncodeVarUInt16(byte[] data, ushort value, int index) { // byte 0 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 1 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; } } // byte 2 data[index++] = (byte)value; return index; } public static int EncodeVarUInt32(byte[] data, uint value, int index) { // byte 0 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 1 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 2 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 3 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; } } } } // last byte data[index++] = (byte)value; return index; } public static int EncodeVarUInt64(byte[] data, ulong value, int index) { // byte 0 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 1 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 2 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 3 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 4 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 5 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 6 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 7 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 8 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; } } } } } } } } } // last byte data[index++] = (byte)value; return index; } public static ushort DecodeVarUInt16(byte[] data, ref int index) { var i = index; // byte 0 uint result = data[i++]; if (0x80u <= result) { // byte 1 uint raw = data[i++]; result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = data[i++]; result |= raw << 14; } } index = i; return (ushort) result; } public static uint DecodeVarUInt32(byte[] data, ref int index) { var i = index; // byte 0 uint result = data[i++]; if (0x80u <= result) { // byte 1 uint raw = data[i++]; result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = data[i++]; result |= (raw & 0x7Fu) << 14; if (0x80u <= raw) { // byte 3 raw = data[i++]; result |= (raw & 0x7Fu) << 21; if (0x80u <= raw) { // byte 4 raw = data[i++]; result |= raw << 28; } } } } index = i; return result; } public static ulong DecodeVarUInt64(byte[] data, ref int index) { var i = index; // byte 0 ulong result = data[i++]; if (0x80u <= result) { // byte 1 ulong raw = data[i++]; result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = data[i++]; result |= (raw & 0x7Fu) << 14; if (0x80u <= raw) { // byte 3 raw = data[i++]; result |= (raw & 0x7Fu) << 21; if (0x80u <= raw) { // byte 4 raw = data[i++]; result |= (raw & 0x7Fu) << 28; if (0x80u <= raw) { // byte 5 raw = data[i++]; result |= (raw & 0x7Fu) << 35; if (0x80u <= raw) { // byte 6 raw = data[i++]; result |= (raw & 0x7Fu) << 42; if (0x80u <= raw) { // byte 7 raw = data[i++]; result |= (raw & 0x7Fu) << 49; if (0x80u <= raw) { // byte 8 raw = data[i++]; result |= raw << 56; if (0x80u <= raw) { // byte 9 i++; } } } } } } } } } index = i; return result; } #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static UInt16 EncodeZigzag16(Int16 value) { return (UInt16)((value << 1) ^ (value >> (sizeof(Int16) * 8 - 1))); } #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static UInt32 EncodeZigzag32(Int32 value) { return (UInt32)((value << 1) ^ (value >> (sizeof(Int32) * 8 - 1))); } #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static UInt64 EncodeZigzag64(Int64 value) { return (UInt64)((value << 1) ^ (value >> (sizeof(Int64) * 8 - 1))); } #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static Int16 DecodeZigzag16(UInt16 value) { return (Int16)((value >> 1) ^ (-(value & 1))); } #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static Int32 DecodeZigzag32(UInt32 value) { return (Int32)((value >> 1) ^ (-(value & 1))); } #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static Int64 DecodeZigzag64(UInt64 value) { return (Int64)((value >> 1) ^ (UInt64)(-(Int64)(value & 1))); } } }
// jQueryAjaxOptions.cs // Script#/Libraries/jQuery/Core // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections.Generic; using System.Html; using System.Runtime.CompilerServices; namespace jQueryApi { /// <summary> /// Represents Ajax request settings or options. /// </summary> [ScriptImport] [ScriptIgnoreNamespace] [ScriptName("Object")] public sealed class jQueryAjaxOptions { /// <summary> /// Initializes an empty instance of a jQueryAjaxOptions object. /// </summary> public jQueryAjaxOptions() { } /// <summary> /// Initializes an instance of a jQueryAjaxOptions object with the /// specified name/value pair list of fields. /// </summary> /// <param name="nameValuePairs">An alternating set of string names and object values.</param> public jQueryAjaxOptions(params object[] nameValuePairs) { } /// <summary> /// Gets or sets the content type sent in the request header that tells the server what kind of response it will accept in return. /// </summary> [ScriptField] public Dictionary<string, string> Accepts { get { return null; } set { } } /// <summary> /// Gets or sets whether the request is async. /// </summary> [ScriptField] public bool Async { get { return false; } set { } } /// <summary> /// Gets or sets the callback to invoke before the request is sent. /// </summary> [ScriptField] public AjaxSendingCallback BeforeSend { get { return null; } set { } } /// <summary> /// Gets or sets whether the request can be cached. /// </summary> [ScriptField] public bool Cache { get { return false; } set { } } /// <summary> /// Gets or sets the callback invoked after the request is completed /// and success or error callbacks have been invoked. /// </summary> [ScriptField] public AjaxCompletedCallback Complete { get { return null; } set { } } /// <summary> /// Gets or sets a map of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. /// </summary> [ScriptField] public Dictionary<string, RegExp> Contents { get { return null; } set { } } /// <summary> /// Gets or sets the content type of the data sent to the server. /// </summary> [ScriptField] public string ContentType { get { return null; } set { } } /// <summary> /// Gets or sets the object that will be the context for the request. /// </summary> [ScriptField] public object Context { get { return null; } set { } } /// <summary> /// Gets or sets a map of dataType-to-dataType converters. /// </summary> [ScriptField] public Dictionary<string, Func<string, object>> Converters { get { return null; } set { } } /// <summary> /// Gets or sets if you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true /// </summary> [ScriptField] public bool CrossDomain { get { return false; } set { } } /// <summary> /// Gets or sets the data to be sent to the server. /// </summary> [ScriptField] public object Data { get { return null; } set { } } /// <summary> /// Gets or sets the data type expected in response from the server. /// </summary> [ScriptField] public string DataType { get { return null; } set { } } /// <summary> /// Gets or sets the callback to be invoked if the request fails. /// </summary> [ScriptField] public AjaxErrorCallback Error { get { return null; } set { } } /// <summary> /// Gets or sets whether to trigger global event handlers for this Ajax request. /// </summary> [ScriptField] public bool Global { get { return false; } set { } } /// <summary> /// Gets or sets if a map of additional header key/value pairs to send along with the request. /// </summary> [ScriptField] public Dictionary<string, string> Headers { get { return null; } set { } } /// <summary> /// Gets or sets whether the request is successful only if its been modified since /// the last request. /// </summary> [ScriptField] public bool IfModified { get { return false; } set { } } /// <summary> /// Gets or sets whether the current environment should be treated as a local /// environment (eg. when the page is loaded using file:///). /// </summary> [ScriptField] public bool IsLocal { get { return false; } set { } } /// <summary> /// Gets or sets the callback parameter name to use for JSONP requests. /// </summary> [ScriptField] public string Jsonp { get { return null; } set { } } /// <summary> /// Gets or sets the callback name to use for JSONP requests. /// </summary> [ScriptField] public string JsonpCallback { get { return null; } set { } } /// <summary> /// Gets or sets the mime type of the request. /// </summary> [ScriptField] public string MimeType { get { return null; } set { } } /// <summary> /// Gets or sets the password to be used for an HTTP authentication request. /// </summary> [ScriptField] public string Password { get { return null; } set { } } /// <summary> /// Gets or sets whether the data passed in will be processed. /// </summary> [ScriptField] public bool ProcessData { get { return false; } set { } } /// <summary> /// Gets or sets how to handle character sets for script and JSONP requests. /// </summary> [ScriptField] public string ScriptCharset { get { return null; } set { } } /// <summary> /// Gets or sets a map of numeric HTTP codes and functions to be called when the response has the corresponding code. /// </summary> [ScriptField] public Dictionary<int, Action> StatusCode { get { return null; } set { } } /// <summary> /// Gets or sets the function to invoke upon successful completion of the request. /// </summary> [ScriptField] public AjaxRequestCallback Success { get { return null; } set { } } /// <summary> /// Gets or sets the timeout in milliseconds for the request. /// </summary> [ScriptField] public int Timeout { get { return 0; } set { } } /// <summary> /// Gets or sets if you want to use traditional parameter serialization. /// </summary> [ScriptField] public bool Traditional { get { return false; } set { } } /// <summary> /// Gets or sets the type or HTTP verb associated with the request. /// </summary> [ScriptField] public string Type { get { return null; } set { } } /// <summary> /// Gets or sets the URL to be requested. /// </summary> [ScriptField] public string Url { get { return null; } set { } } /// <summary> /// Gets or sets the name of the user to use in a HTTP authentication request. /// </summary> [ScriptField] public string Username { get { return null; } set { } } /// <summary> /// Gets or sets the function creating the XmlHttpRequest instance. /// </summary> [ScriptField] [ScriptName("xhr")] public XmlHttpRequestCreator XmlHttpRequestCreator { get { return null; } set { } } /// <summary> /// Gets or sets a set of additional name/value pairs set of the XmlHttpRequest /// object. /// </summary> [ScriptField] public Dictionary<string, object> XhrFields { get { return null; } set { } } } }
using NUnit.Framework; using VkNet.Enums.Filters; namespace VkNet.Tests.Enum.Filters { [TestFixture] public class MultivaluedFilterTest { [Test] public void AccountFieldsTest() { // get test Assert.That(AccountFields.Country.ToString(), Is.EqualTo("country")); Assert.That(AccountFields.HttpsRequired.ToString(), Is.EqualTo("https_required")); Assert.That(AccountFields.OwnPostsDefault.ToString(), Is.EqualTo("own_posts_default")); Assert.That(AccountFields.NoWallReplies.ToString(), Is.EqualTo("no_wall_replies")); Assert.That(AccountFields.Intro.ToString(), Is.EqualTo("intro")); Assert.That(AccountFields.Language.ToString(), Is.EqualTo("lang")); // parse test Assert.That(AccountFields.FromJsonString("country"), Is.EqualTo(AccountFields.Country)); Assert.That(AccountFields.FromJsonString("https_required") , Is.EqualTo(AccountFields.HttpsRequired)); Assert.That(AccountFields.FromJsonString("own_posts_default") , Is.EqualTo(AccountFields.OwnPostsDefault)); Assert.That(AccountFields.FromJsonString("no_wall_replies") , Is.EqualTo(AccountFields.NoWallReplies)); Assert.That(AccountFields.FromJsonString("intro"), Is.EqualTo(AccountFields.Intro)); Assert.That(AccountFields.FromJsonString("lang"), Is.EqualTo(AccountFields.Language)); } [Test] public void CountersFilterTest() { // get test Assert.That(CountersFilter.Friends.ToString(), Is.EqualTo("friends")); Assert.That(CountersFilter.Messages.ToString(), Is.EqualTo("messages")); Assert.That(CountersFilter.Photos.ToString(), Is.EqualTo("photos")); Assert.That(CountersFilter.Videos.ToString(), Is.EqualTo("videos")); Assert.That(CountersFilter.Gifts.ToString(), Is.EqualTo("gifts")); Assert.That(CountersFilter.Events.ToString(), Is.EqualTo("events")); Assert.That(CountersFilter.Groups.ToString(), Is.EqualTo("groups")); Assert.That(CountersFilter.Notifications.ToString(), Is.EqualTo("notifications")); Assert.That(CountersFilter.All.ToString() , Is.EqualTo("app_requests,events,friends,friends_suggestions,gifts,groups,messages,notifications,photos,sdk,videos")); // parse test Assert.That(CountersFilter.FromJsonString("friends"), Is.EqualTo(CountersFilter.Friends)); Assert.That(CountersFilter.FromJsonString("messages"), Is.EqualTo(CountersFilter.Messages)); Assert.That(CountersFilter.FromJsonString("photos"), Is.EqualTo(CountersFilter.Photos)); Assert.That(CountersFilter.FromJsonString("videos"), Is.EqualTo(CountersFilter.Videos)); Assert.That(CountersFilter.FromJsonString("gifts"), Is.EqualTo(CountersFilter.Gifts)); Assert.That(CountersFilter.FromJsonString("events"), Is.EqualTo(CountersFilter.Events)); Assert.That(CountersFilter.FromJsonString("groups"), Is.EqualTo(CountersFilter.Groups)); Assert.That(CountersFilter.FromJsonString("notifications") , Is.EqualTo(CountersFilter.Notifications)); Assert.That(CountersFilter.FromJsonString( "app_requests,events,friends,friends_suggestions,gifts,groups,messages,notifications,photos,sdk,videos") , Is.EqualTo(CountersFilter.All)); } [Test] public void GroupsFieldsTest() { // get test Assert.That(GroupsFields.CityId.ToString(), Is.EqualTo("city")); Assert.That(GroupsFields.CountryId.ToString(), Is.EqualTo("country")); Assert.That(GroupsFields.Place.ToString(), Is.EqualTo("place")); Assert.That(GroupsFields.Description.ToString(), Is.EqualTo("description")); Assert.That(GroupsFields.WikiPage.ToString(), Is.EqualTo("wiki_page")); Assert.That(GroupsFields.MembersCount.ToString(), Is.EqualTo("members_count")); Assert.That(GroupsFields.Counters.ToString(), Is.EqualTo("counters")); Assert.That(GroupsFields.StartDate.ToString(), Is.EqualTo("start_date")); Assert.That(GroupsFields.EndDate.ToString(), Is.EqualTo("finish_date")); Assert.That(GroupsFields.CanPost.ToString(), Is.EqualTo("can_post")); Assert.That(GroupsFields.CanSeelAllPosts.ToString(), Is.EqualTo("can_see_all_posts")); Assert.That(GroupsFields.CanUploadDocuments.ToString(), Is.EqualTo("can_upload_doc")); Assert.That(GroupsFields.CanCreateTopic.ToString(), Is.EqualTo("can_create_topic")); Assert.That(GroupsFields.Activity.ToString(), Is.EqualTo("activity")); Assert.That(GroupsFields.Status.ToString(), Is.EqualTo("status")); Assert.That(GroupsFields.Contacts.ToString(), Is.EqualTo("contacts")); Assert.That(GroupsFields.Links.ToString(), Is.EqualTo("links")); Assert.That(GroupsFields.FixedPostId.ToString(), Is.EqualTo("fixed_post")); Assert.That(GroupsFields.IsVerified.ToString(), Is.EqualTo("verified")); Assert.That(GroupsFields.Site.ToString(), Is.EqualTo("site")); Assert.That(GroupsFields.BanInfo.ToString(), Is.EqualTo("ban_info")); Assert.That(GroupsFields.All.ToString() , Is.EqualTo("activity,ban_info,can_create_topic,can_post,can_see_all_posts,city,contacts,counters,country,description,finish_date,fixed_post,links,members_count,place,site,start_date,status,verified,wiki_page")); Assert.That(GroupsFields.AllUndocumented.ToString() , Is.EqualTo("activity,ban_info,can_create_topic,can_post,can_see_all_posts,can_upload_doc,city,contacts,counters,country,description,finish_date,fixed_post,links,members_count,place,site,start_date,status,verified,wiki_page")); // parse test Assert.That(GroupsFields.FromJsonString("city"), Is.EqualTo(GroupsFields.CityId)); Assert.That(GroupsFields.FromJsonString("country"), Is.EqualTo(GroupsFields.CountryId)); Assert.That(GroupsFields.FromJsonString("place"), Is.EqualTo(GroupsFields.Place)); Assert.That(GroupsFields.FromJsonString("description") , Is.EqualTo(GroupsFields.Description)); Assert.That(GroupsFields.FromJsonString("wiki_page"), Is.EqualTo(GroupsFields.WikiPage)); Assert.That(GroupsFields.FromJsonString("members_count") , Is.EqualTo(GroupsFields.MembersCount)); Assert.That(GroupsFields.FromJsonString("counters"), Is.EqualTo(GroupsFields.Counters)); Assert.That(GroupsFields.FromJsonString("start_date"), Is.EqualTo(GroupsFields.StartDate)); Assert.That(GroupsFields.FromJsonString("finish_date"), Is.EqualTo(GroupsFields.EndDate)); Assert.That(GroupsFields.FromJsonString("can_post"), Is.EqualTo(GroupsFields.CanPost)); Assert.That(GroupsFields.FromJsonString("can_see_all_posts") , Is.EqualTo(GroupsFields.CanSeelAllPosts)); Assert.That(GroupsFields.FromJsonString("can_upload_doc") , Is.EqualTo(GroupsFields.CanUploadDocuments)); Assert.That(GroupsFields.FromJsonString("can_create_topic") , Is.EqualTo(GroupsFields.CanCreateTopic)); Assert.That(GroupsFields.FromJsonString("activity"), Is.EqualTo(GroupsFields.Activity)); Assert.That(GroupsFields.FromJsonString("status"), Is.EqualTo(GroupsFields.Status)); Assert.That(GroupsFields.FromJsonString("contacts"), Is.EqualTo(GroupsFields.Contacts)); Assert.That(GroupsFields.FromJsonString("links"), Is.EqualTo(GroupsFields.Links)); Assert.That(GroupsFields.FromJsonString("fixed_post"), Is.EqualTo(GroupsFields.FixedPostId)); Assert.That(GroupsFields.FromJsonString("verified"), Is.EqualTo(GroupsFields.IsVerified)); Assert.That(GroupsFields.FromJsonString("site"), Is.EqualTo(GroupsFields.Site)); Assert.That(GroupsFields.FromJsonString("ban_info"), Is.EqualTo(GroupsFields.BanInfo)); Assert.That(GroupsFields.FromJsonString("activity,ban_info,can_create_topic,can_post,can_see_all_posts,city,contacts,counters,country,description,finish_date,fixed_post,links,members_count,place,site,start_date,status,verified,wiki_page") , Is.EqualTo(GroupsFields.All)); Assert.That(GroupsFields.FromJsonString("activity,ban_info,can_create_topic,can_post,can_see_all_posts,can_upload_doc,city,contacts,counters,country,description,finish_date,fixed_post,links,members_count,place,site,start_date,status,verified,wiki_page") , Is.EqualTo(GroupsFields.AllUndocumented)); } [Test] public void GroupsFiltersTest() { // get test Assert.That(GroupsFilters.Administrator.ToString(), Is.EqualTo("admin")); Assert.That(GroupsFilters.Editor.ToString(), Is.EqualTo("editor")); Assert.That(GroupsFilters.Moderator.ToString(), Is.EqualTo("moder")); Assert.That(GroupsFilters.Groups.ToString(), Is.EqualTo("groups")); Assert.That(GroupsFilters.Publics.ToString(), Is.EqualTo("publics")); Assert.That(GroupsFilters.Events.ToString(), Is.EqualTo("events")); Assert.That(GroupsFilters.All.ToString(), Is.EqualTo("admin,editor,events,groups,moder,publics")); // parse test Assert.That(GroupsFilters.FromJsonString("admin"), Is.EqualTo(GroupsFilters.Administrator)); Assert.That(GroupsFilters.FromJsonString("editor"), Is.EqualTo(GroupsFilters.Editor)); Assert.That(GroupsFilters.FromJsonString("moder"), Is.EqualTo(GroupsFilters.Moderator)); Assert.That(GroupsFilters.FromJsonString("groups"), Is.EqualTo(GroupsFilters.Groups)); Assert.That(GroupsFilters.FromJsonString("publics"), Is.EqualTo(GroupsFilters.Publics)); Assert.That(GroupsFilters.FromJsonString("events"), Is.EqualTo(GroupsFilters.Events)); Assert.That(GroupsFilters.FromJsonString("admin,editor,moder,groups,publics,events") , Is.EqualTo(GroupsFilters.All)); } [Test] public void SubscribeFilterTest() { // get test Assert.That(SubscribeFilter.Message.ToString(), Is.EqualTo("msg")); Assert.That(SubscribeFilter.Friend.ToString(), Is.EqualTo("friend")); Assert.That(SubscribeFilter.Call.ToString(), Is.EqualTo("call")); Assert.That(SubscribeFilter.Reply.ToString(), Is.EqualTo("reply")); Assert.That(SubscribeFilter.Mention.ToString(), Is.EqualTo("mention")); Assert.That(SubscribeFilter.Group.ToString(), Is.EqualTo("group")); Assert.That(SubscribeFilter.Like.ToString(), Is.EqualTo("like")); Assert.That(SubscribeFilter.All.ToString() , Is.EqualTo("call,friend,group,like,mention,msg,reply")); // parse test Assert.That(SubscribeFilter.FromJsonString("msg"), Is.EqualTo(SubscribeFilter.Message)); Assert.That(SubscribeFilter.FromJsonString("friend"), Is.EqualTo(SubscribeFilter.Friend)); Assert.That(SubscribeFilter.FromJsonString("call"), Is.EqualTo(SubscribeFilter.Call)); Assert.That(SubscribeFilter.FromJsonString("reply"), Is.EqualTo(SubscribeFilter.Reply)); Assert.That(SubscribeFilter.FromJsonString("mention"), Is.EqualTo(SubscribeFilter.Mention)); Assert.That(SubscribeFilter.FromJsonString("group"), Is.EqualTo(SubscribeFilter.Group)); Assert.That(SubscribeFilter.FromJsonString("like"), Is.EqualTo(SubscribeFilter.Like)); Assert.That(SubscribeFilter.FromJsonString("msg,friend,call,reply,mention,group,like") , Is.EqualTo(SubscribeFilter.All)); } [Test] public void UsersFieldsTest() { // get test Assert.That(UsersFields.Nickname.ToString(), Is.EqualTo("nickname")); Assert.That(UsersFields.Domain.ToString(), Is.EqualTo("domain")); Assert.That(UsersFields.Sex.ToString(), Is.EqualTo("sex")); Assert.That(UsersFields.BirthDate.ToString(), Is.EqualTo("bdate")); Assert.That(UsersFields.City.ToString(), Is.EqualTo("city")); Assert.That(UsersFields.Country.ToString(), Is.EqualTo("country")); Assert.That(UsersFields.Timezone.ToString(), Is.EqualTo("timezone")); Assert.That(UsersFields.Photo50.ToString(), Is.EqualTo("photo_50")); Assert.That(UsersFields.Photo100.ToString(), Is.EqualTo("photo_100")); Assert.That(UsersFields.Photo200Orig.ToString(), Is.EqualTo("photo_200_orig")); Assert.That(UsersFields.Photo200.ToString(), Is.EqualTo("photo_200")); Assert.That(UsersFields.Photo400Orig.ToString(), Is.EqualTo("photo_400_orig")); Assert.That(UsersFields.PhotoMax.ToString(), Is.EqualTo("photo_max")); Assert.That(UsersFields.PhotoMaxOrig.ToString(), Is.EqualTo("photo_max_orig")); Assert.That(UsersFields.HasMobile.ToString(), Is.EqualTo("has_mobile")); Assert.That(UsersFields.Contacts.ToString(), Is.EqualTo("contacts")); Assert.That(UsersFields.Education.ToString(), Is.EqualTo("education")); Assert.That(UsersFields.Online.ToString(), Is.EqualTo("online")); Assert.That(UsersFields.OnlineMobile.ToString(), Is.EqualTo("online_mobile")); Assert.That(UsersFields.FriendLists.ToString(), Is.EqualTo("lists")); Assert.That(UsersFields.Relation.ToString(), Is.EqualTo("relation")); Assert.That(UsersFields.LastSeen.ToString(), Is.EqualTo("last_seen")); Assert.That(UsersFields.Status.ToString(), Is.EqualTo("status")); Assert.That(UsersFields.CanWritePrivateMessage.ToString() , Is.EqualTo("can_write_private_message")); Assert.That(UsersFields.CanSeeAllPosts.ToString(), Is.EqualTo("can_see_all_posts")); Assert.That(UsersFields.CanPost.ToString(), Is.EqualTo("can_post")); Assert.That(UsersFields.Universities.ToString(), Is.EqualTo("universities")); Assert.That(UsersFields.Connections.ToString(), Is.EqualTo("connections")); Assert.That(UsersFields.Site.ToString(), Is.EqualTo("site")); Assert.That(UsersFields.Schools.ToString(), Is.EqualTo("schools")); Assert.That(UsersFields.CanSeeAudio.ToString(), Is.EqualTo("can_see_audio")); Assert.That(UsersFields.CommonCount.ToString(), Is.EqualTo("common_count")); Assert.That(UsersFields.Relatives.ToString(), Is.EqualTo("relatives")); Assert.That(UsersFields.Counters.ToString(), Is.EqualTo("counters")); Assert.That(UsersFields.CanAccessClosed.ToString(), Is.EqualTo("can_access_closed")); Assert.That(UsersFields.IsClosed.ToString(), Is.EqualTo("is_closed")); Assert.That(UsersFields.FirstNameNom.ToString(), Is.EqualTo("first_name_nom")); Assert.That(UsersFields.FirstNameGen.ToString(), Is.EqualTo("first_name_gen")); Assert.That(UsersFields.FirstNameDat.ToString(), Is.EqualTo("first_name_dat")); Assert.That(UsersFields.FirstNameAcc.ToString(), Is.EqualTo("first_name_acc")); Assert.That(UsersFields.FirstNameIns.ToString(), Is.EqualTo("first_name_ins")); Assert.That(UsersFields.FirstNameAbl.ToString(), Is.EqualTo("first_name_abl")); Assert.That(UsersFields.LastNameNom.ToString(), Is.EqualTo("last_name_nom")); Assert.That(UsersFields.LastNameGen.ToString(), Is.EqualTo("last_name_gen")); Assert.That(UsersFields.LastNameDat.ToString(), Is.EqualTo("last_name_dat")); Assert.That(UsersFields.LastNameAcc.ToString(), Is.EqualTo("last_name_acc")); Assert.That(UsersFields.LastNameIns.ToString(), Is.EqualTo("last_name_ins")); Assert.That(UsersFields.LastNameAbl.ToString(), Is.EqualTo("last_name_abl")); Assert.That(UsersFields.All.ToString() , Is.EqualTo("bdate,can_access_closed,can_post,can_see_all_posts,can_see_audio,can_write_private_message,city,common_count,connections,contacts,counters,country,domain,education,first_name_abl,first_name_acc,first_name_dat,first_name_gen,first_name_ins,first_name_nom,has_mobile,is_closed,last_name_abl,last_name_acc,last_name_dat,last_name_gen,last_name_ins,last_name_nom,last_seen,lists,nickname,online,online_mobile,photo_100,photo_200,photo_200_orig,photo_400_orig,photo_50,photo_max,photo_max_orig,relation,relatives,schools,sex,site,status,timezone,universities")); // parse test Assert.That(UsersFields.FromJsonString("nickname"), Is.EqualTo(UsersFields.Nickname)); Assert.That(UsersFields.FromJsonString("domain"), Is.EqualTo(UsersFields.Domain)); Assert.That(UsersFields.FromJsonString("sex"), Is.EqualTo(UsersFields.Sex)); Assert.That(UsersFields.FromJsonString("bdate"), Is.EqualTo(UsersFields.BirthDate)); Assert.That(UsersFields.FromJsonString("city"), Is.EqualTo(UsersFields.City)); Assert.That(UsersFields.FromJsonString("country"), Is.EqualTo(UsersFields.Country)); Assert.That(UsersFields.FromJsonString("timezone"), Is.EqualTo(UsersFields.Timezone)); Assert.That(UsersFields.FromJsonString("photo_50"), Is.EqualTo(UsersFields.Photo50)); Assert.That(UsersFields.FromJsonString("photo_100"), Is.EqualTo(UsersFields.Photo100)); Assert.That(UsersFields.FromJsonString("photo_200_orig") , Is.EqualTo(UsersFields.Photo200Orig)); Assert.That(UsersFields.FromJsonString("photo_200"), Is.EqualTo(UsersFields.Photo200)); Assert.That(UsersFields.FromJsonString("photo_400_orig") , Is.EqualTo(UsersFields.Photo400Orig)); Assert.That(UsersFields.FromJsonString("photo_max"), Is.EqualTo(UsersFields.PhotoMax)); Assert.That(UsersFields.FromJsonString("photo_max_orig") , Is.EqualTo(UsersFields.PhotoMaxOrig)); Assert.That(UsersFields.FromJsonString("has_mobile"), Is.EqualTo(UsersFields.HasMobile)); Assert.That(UsersFields.FromJsonString("contacts"), Is.EqualTo(UsersFields.Contacts)); Assert.That(UsersFields.FromJsonString("education"), Is.EqualTo(UsersFields.Education)); Assert.That(UsersFields.FromJsonString("online"), Is.EqualTo(UsersFields.Online)); Assert.That(UsersFields.FromJsonString("online_mobile") , Is.EqualTo(UsersFields.OnlineMobile)); Assert.That(UsersFields.FromJsonString("lists"), Is.EqualTo(UsersFields.FriendLists)); Assert.That(UsersFields.FromJsonString("relation"), Is.EqualTo(UsersFields.Relation)); Assert.That(UsersFields.FromJsonString("last_seen"), Is.EqualTo(UsersFields.LastSeen)); Assert.That(UsersFields.FromJsonString("status"), Is.EqualTo(UsersFields.Status)); Assert.That(UsersFields.FromJsonString("can_write_private_message") , Is.EqualTo(UsersFields.CanWritePrivateMessage)); Assert.That(UsersFields.FromJsonString("can_see_all_posts") , Is.EqualTo(UsersFields.CanSeeAllPosts)); Assert.That(UsersFields.FromJsonString("can_post"), Is.EqualTo(UsersFields.CanPost)); Assert.That(UsersFields.FromJsonString("universities") , Is.EqualTo(UsersFields.Universities)); Assert.That(UsersFields.FromJsonString("connections"), Is.EqualTo(UsersFields.Connections)); Assert.That(UsersFields.FromJsonString("site"), Is.EqualTo(UsersFields.Site)); Assert.That(UsersFields.FromJsonString("schools"), Is.EqualTo(UsersFields.Schools)); Assert.That(UsersFields.FromJsonString("can_see_audio") , Is.EqualTo(UsersFields.CanSeeAudio)); Assert.That(UsersFields.FromJsonString("common_count"), Is.EqualTo(UsersFields.CommonCount)); Assert.That(UsersFields.FromJsonString("relatives"), Is.EqualTo(UsersFields.Relatives)); Assert.That(UsersFields.FromJsonString("counters"), Is.EqualTo(UsersFields.Counters)); Assert.That(UsersFields.FromJsonString("can_access_closed"), Is.EqualTo(UsersFields.CanAccessClosed)); Assert.That(UsersFields.FromJsonString("is_closed"), Is.EqualTo(UsersFields.IsClosed)); Assert.That(UsersFields.FromJsonString("first_name_nom"), Is.EqualTo(UsersFields.FirstNameNom)); Assert.That(UsersFields.FromJsonString("first_name_gen"), Is.EqualTo(UsersFields.FirstNameGen)); Assert.That(UsersFields.FromJsonString("first_name_dat"), Is.EqualTo(UsersFields.FirstNameDat)); Assert.That(UsersFields.FromJsonString("first_name_acc"), Is.EqualTo(UsersFields.FirstNameAcc)); Assert.That(UsersFields.FromJsonString("first_name_ins"), Is.EqualTo(UsersFields.FirstNameIns)); Assert.That(UsersFields.FromJsonString("first_name_abl"), Is.EqualTo(UsersFields.FirstNameAbl)); Assert.That(UsersFields.FromJsonString("last_name_nom"), Is.EqualTo(UsersFields.LastNameNom)); Assert.That(UsersFields.FromJsonString("last_name_gen"), Is.EqualTo(UsersFields.LastNameGen)); Assert.That(UsersFields.FromJsonString("last_name_dat"), Is.EqualTo(UsersFields.LastNameDat)); Assert.That(UsersFields.FromJsonString("last_name_acc"), Is.EqualTo(UsersFields.LastNameAcc)); Assert.That(UsersFields.FromJsonString("last_name_ins"), Is.EqualTo(UsersFields.LastNameIns)); Assert.That(UsersFields.FromJsonString("last_name_abl"), Is.EqualTo(UsersFields.LastNameAbl)); Assert.That(UsersFields.FromJsonString("bdate,can_access_closed,can_post,can_see_all_posts,can_see_audio,can_write_private_message,city,common_count,connections,contacts,counters,country,domain,education,first_name_abl,first_name_acc,first_name_dat,first_name_gen,first_name_ins,first_name_nom,has_mobile,is_closed,last_name_abl,last_name_acc,last_name_dat,last_name_gen,last_name_ins,last_name_nom,last_seen,lists,nickname,online,online_mobile,photo_100,photo_200,photo_200_orig,photo_400_orig,photo_50,photo_max,photo_max_orig,relation,relatives,schools,sex,site,status,timezone,universities") , Is.EqualTo(UsersFields.All)); } [Test] public void VideoFiltersTest() { // get test Assert.That(VideoFilters.Mp4.ToString(), Is.EqualTo("mp4")); Assert.That(VideoFilters.Youtube.ToString(), Is.EqualTo("youtube")); Assert.That(VideoFilters.Vimeo.ToString(), Is.EqualTo("vimeo")); Assert.That(VideoFilters.Short.ToString(), Is.EqualTo("short")); Assert.That(VideoFilters.Long.ToString(), Is.EqualTo("long")); Assert.That(VideoFilters.All.ToString(), Is.EqualTo("long,mp4,short,vimeo,youtube")); // parse test Assert.That(VideoFilters.FromJsonString("mp4"), Is.EqualTo(VideoFilters.Mp4)); Assert.That(VideoFilters.FromJsonString("youtube"), Is.EqualTo(VideoFilters.Youtube)); Assert.That(VideoFilters.FromJsonString("vimeo"), Is.EqualTo(VideoFilters.Vimeo)); Assert.That(VideoFilters.FromJsonString("short"), Is.EqualTo(VideoFilters.Short)); Assert.That(VideoFilters.FromJsonString("long"), Is.EqualTo(VideoFilters.Long)); Assert.That(VideoFilters.FromJsonString("mp4,youtube,vimeo,short,long") , Is.EqualTo(VideoFilters.All)); } [Test] public void AudioBroadcastFilterTest() { // get test Assert.That(actual: AudioBroadcastFilter.All.ToString(), expression: Is.EqualTo(expected: "all")); Assert.That(actual: AudioBroadcastFilter.Friends.ToString(), expression: Is.EqualTo(expected: "friends")); Assert.That(actual: AudioBroadcastFilter.Groups.ToString(), expression: Is.EqualTo(expected: "groups")); // parse test Assert.That(actual: AudioBroadcastFilter.FromJsonString(val: "all"), expression: Is.EqualTo(expected: AudioBroadcastFilter.All)); Assert.That(actual: AudioBroadcastFilter.FromJsonString(val: "friends"), expression: Is.EqualTo(expected: AudioBroadcastFilter.Friends)); Assert.That(actual: AudioBroadcastFilter.FromJsonString(val: "groups"), expression: Is.EqualTo(expected: AudioBroadcastFilter.Groups)); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: __Error ** ** ** Purpose: Centralized error methods for the IO package. ** Mostly useful for translating Win32 HRESULTs into meaningful ** error strings & exceptions. ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; //using Win32Native = Microsoft.Win32.Win32Native; using System.Text; //using System.Globalization; //using System.Security; //using System.Security.Permissions; namespace System.IO { // Only static data no need to serialize internal static class __Error { internal static void EndOfFile() { #if EXCEPTION_STRINGS throw new EndOfStreamException( Environment.GetResourceString( "IO.EOF_ReadBeyondEOF" ) ); #else throw new EndOfStreamException(); #endif } internal static void FileNotOpen() { #if EXCEPTION_STRINGS throw new ObjectDisposedException( null, Environment.GetResourceString( "ObjectDisposed_FileClosed" ) ); #else throw new ObjectDisposedException( null ); #endif } internal static void StreamIsClosed() { #if EXCEPTION_STRINGS throw new ObjectDisposedException( null, Environment.GetResourceString( "ObjectDisposed_StreamClosed" ) ); #else throw new ObjectDisposedException( null ); #endif } internal static void MemoryStreamNotExpandable() { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_MemStreamNotExpandable" ) ); #else throw new NotSupportedException(); #endif } internal static void ReaderClosed() { #if EXCEPTION_STRINGS throw new ObjectDisposedException( null, Environment.GetResourceString( "ObjectDisposed_ReaderClosed" ) ); #else throw new ObjectDisposedException( null ); #endif } internal static void ReadNotSupported() { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_UnreadableStream" ) ); #else throw new NotSupportedException(); #endif } internal static void SeekNotSupported() { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_UnseekableStream" ) ); #else throw new NotSupportedException(); #endif } internal static void WrongAsyncResult() { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_WrongAsyncResult" ) ); #else throw new ArgumentException(); #endif } internal static void EndReadCalledTwice() { // Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "InvalidOperation_EndReadCalledMultiple" ) ); #else throw new ArgumentException(); #endif } internal static void EndWriteCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "InvalidOperation_EndWriteCalledMultiple" ) ); #else throw new ArgumentException(); #endif } //// // Given a possible fully qualified path, ensure that we have path //// // discovery permission to that path. If we do not, return just the //// // file name. If we know it is a directory, then don't return the //// // directory name. //// internal static String GetDisplayablePath( String path, bool isInvalidPath ) //// { //// if(String.IsNullOrEmpty( path )) //// return path; //// //// // Is it a fully qualified path? //// bool isFullyQualified = false; //// if(path.Length < 2) //// return path; //// if(Path.IsDirectorySeparator( path[0] ) && Path.IsDirectorySeparator( path[1] )) //// isFullyQualified = true; //// else if(path[1] == Path.VolumeSeparatorChar) //// { //// isFullyQualified = true; //// } //// //// if(!isFullyQualified && !isInvalidPath) //// return path; //// //// bool safeToReturn = false; //// try //// { //// if(!isInvalidPath) //// { //// new FileIOPermission( FileIOPermissionAccess.PathDiscovery, new String[] { path }, false, false ).Demand(); //// safeToReturn = true; //// } //// } //// catch(SecurityException) //// { //// } //// catch(ArgumentException) //// { //// // ? and * characters cause ArgumentException to be thrown from HasIllegalCharacters //// // inside FileIOPermission.AddPathList //// } //// catch(NotSupportedException) //// { //// // paths like "!Bogus\\dir:with/junk_.in it" can cause NotSupportedException to be thrown //// // from Security.Util.StringExpressionSet.CanonicalizePath when ':' is found in the path //// // beyond string index position 1. //// } //// //// if(!safeToReturn) //// { //// if(Path.IsDirectorySeparator( path[path.Length - 1] )) //// path = Environment.GetResourceString( "IO.IO_NoPermissionToDirectoryName" ); //// else //// path = Path.GetFileName( path ); //// } //// //// return path; //// } //// //// internal static void WinIOError() //// { //// int errorCode = Marshal.GetLastWin32Error(); //// WinIOError( errorCode, String.Empty ); //// } //// //// // After calling GetLastWin32Error(), it clears the last error field, //// // so you must save the HResult and pass it to this method. This method //// // will determine the appropriate exception to throw dependent on your //// // error, and depending on the error, insert a string into the message //// // gotten from the ResourceManager. //// internal static void WinIOError( int errorCode, String maybeFullPath ) //// { //// // This doesn't have to be perfect, but is a perf optimization. //// bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME; //// String str = GetDisplayablePath( maybeFullPath, isInvalidPath ); //// //// switch(errorCode) //// { //// case Win32Native.ERROR_FILE_NOT_FOUND: //// if(str.Length == 0) //// throw new FileNotFoundException( Environment.GetResourceString( "IO.FileNotFound" ) ); //// else //// throw new FileNotFoundException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.FileNotFound_FileName" ), str ), str ); //// //// case Win32Native.ERROR_PATH_NOT_FOUND: //// if(str.Length == 0) //// throw new DirectoryNotFoundException( Environment.GetResourceString( "IO.PathNotFound_NoPathName" ) ); //// else //// throw new DirectoryNotFoundException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.PathNotFound_Path" ), str ) ); //// //// case Win32Native.ERROR_ACCESS_DENIED: //// if(str.Length == 0) //// throw new UnauthorizedAccessException( Environment.GetResourceString( "UnauthorizedAccess_IODenied_NoPathName" ) ); //// else //// throw new UnauthorizedAccessException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "UnauthorizedAccess_IODenied_Path" ), str ) ); //// //// case Win32Native.ERROR_ALREADY_EXISTS: //// if(str.Length == 0) //// goto default; //// throw new IOException( Environment.GetResourceString( "IO.IO_AlreadyExists_Name", str ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// //// case Win32Native.ERROR_FILENAME_EXCED_RANGE: //// throw new PathTooLongException( Environment.GetResourceString( "IO.PathTooLong" ) ); //// //// case Win32Native.ERROR_INVALID_DRIVE: //// throw new DriveNotFoundException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.DriveNotFound_Drive" ), str ) ); //// //// case Win32Native.ERROR_INVALID_PARAMETER: //// throw new IOException( Win32Native.GetMessage( errorCode ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// //// case Win32Native.ERROR_SHARING_VIOLATION: //// if(str.Length == 0) //// throw new IOException( Environment.GetResourceString( "IO.IO_SharingViolation_NoFileName" ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// else //// throw new IOException( Environment.GetResourceString( "IO.IO_SharingViolation_File", str ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// //// case Win32Native.ERROR_FILE_EXISTS: //// if(str.Length == 0) //// goto default; //// throw new IOException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.IO_FileExists_Name" ), str ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// //// case Win32Native.ERROR_OPERATION_ABORTED: //// throw new OperationCanceledException(); //// //// default: //// throw new IOException( Win32Native.GetMessage( errorCode ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// } //// } //// //// // An alternative to WinIOError with friendlier messages for drives //// internal static void WinIODriveError( String driveName ) //// { //// int errorCode = Marshal.GetLastWin32Error(); //// WinIODriveError( driveName, errorCode ); //// } //// //// internal static void WinIODriveError( String driveName, int errorCode ) //// { //// switch(errorCode) //// { //// case Win32Native.ERROR_PATH_NOT_FOUND: //// case Win32Native.ERROR_INVALID_DRIVE: //// throw new DriveNotFoundException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.DriveNotFound_Drive" ), driveName ) ); //// //// default: //// WinIOError( errorCode, driveName ); //// break; //// } //// } internal static void WriteNotSupported() { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_UnwritableStream" ) ); #else throw new NotSupportedException(); #endif } internal static void WriterClosed() { #if EXCEPTION_STRINGS throw new ObjectDisposedException( null, Environment.GetResourceString( "ObjectDisposed_WriterClosed" ) ); #else throw new ObjectDisposedException( null ); #endif } //// // From WinError.h //// internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND; //// internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND; //// internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED; //// internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER; } }
// 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; /// <summary> /// System.Math.Log10(System.Double) /// </summary> public class MathLog10 { public static int Main(string[] args) { MathLog10 log10 = new MathLog10(); TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Log10(System.Double)..."); if (log10.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify the monotonicity of Log10(var)..."); try { double var1 = 100.1 * TestLibrary.Generator.GetDouble(-55); double var2 = 100.1 * TestLibrary.Generator.GetDouble(-55); if (var1 < var2) { if (Math.Log10(var1) >= Math.Log10(var2)) { TestLibrary.TestFramework.LogError("001", "The value of Log10(var1) should be less than In(var2)..."); retVal = false; } } else if (var1 > var2) { if (Math.Log10(var1) <= Math.Log10(var2)) { TestLibrary.TestFramework.LogError("002", "The value of Log10(var1) should be larger than In(var2)..."); retVal = false; } } else { if (Math.Log10(var1) != Math.Log10(var2)) { TestLibrary.TestFramework.LogError("003", "The value of Log10(var1) should be equal to In(var2)..."); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the value is negative when var is between o and 1..."); try { double var = 0; while (var <= 0 && var >= 1) { var = TestLibrary.Generator.GetDouble(-55); } if (Math.Log10(var) >= 0) { TestLibrary.TestFramework.LogError("005", "The value should be negative!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Verify the value of Log10(1) is 0..."); try { double var = 1; if (Math.Log10(var) != 0) { TestLibrary.TestFramework.LogError("007", "The value of Log10(1) should be zero!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Verify the value of Log10(var) is larger than zero..."); try { double var = TestLibrary.Generator.GetDouble(-55); while (var <= 1) { var *= 10; } if (Math.Log10(var) < 0) { TestLibrary.TestFramework.LogError("009", "The value should be larger than zero!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Verify the value of Log10(0)..."); try { double var = 0; if (!double.IsNegativeInfinity(Math.Log10(var))) { TestLibrary.TestFramework.LogError("011", "the value of Log10(0) should be negativeInfinity!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the value of Log10(var) when var is negative..."); try { double var = -TestLibrary.Generator.GetDouble(-55); while (var >= 0) { var = TestLibrary.Generator.GetDouble(-55); } if (!double.IsNaN(Math.Log10(var))) { TestLibrary.TestFramework.LogError("013", "The value should be NaN!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the value of Log10(10)..."); try { double var = 10; if (Math.Log10(var) != 1) { TestLibrary.TestFramework.LogError("015","the value should be equal to 1!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
// 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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.RefLocalsReturns)] public class RefLocalTests : CompilingTestBase { [Fact] public void RefAssignArrayAccess() { var text = @" class Program { static void M() { ref int rl = ref (new int[1])[0]; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr ""int"" IL_0007: ldc.i4.0 IL_0008: ldelema ""int"" IL_000d: stloc.0 IL_000e: ret }"); } [Fact] public void RefAssignRefParameter() { var text = @" class Program { static void M(ref int i) { ref int rl = ref i; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(ref int)", @" { // Code size 4 (0x4) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ret }"); } [Fact] public void RefAssignOutParameter() { var text = @" class Program { static void M(out int i) { i = 0; ref int rl = ref i; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(out int)", @" { // Code size 7 (0x7) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: stind.i4 IL_0004: ldarg.0 IL_0005: stloc.0 IL_0006: ret }"); } [Fact] public void RefAssignRefLocal() { var text = @" class Program { static void M(ref int i) { ref int local = ref i; ref int rl = ref local; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(ref int)", @" { // Code size 6 (0x6) .maxstack 1 .locals init (int& V_0, //local int& V_1) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ret }"); } [Fact] public void RefAssignStaticProperty() { var text = @" class Program { static int field = 0; static ref int P { get { return ref field; } } static void M() { ref int rl = ref P; } } "; CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: call ""ref int Program.P.get"" IL_0006: stloc.0 IL_0007: ret }"); } [Fact] public void RefAssignClassInstanceProperty() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } void M() { ref int rl = ref P; } void M1() { ref int rl = ref new Program().P; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 9 (0x9) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""ref int Program.P.get"" IL_0007: stloc.0 IL_0008: ret }"); comp.VerifyIL("Program.M1()", @" { // Code size 13 (0xd) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: call ""ref int Program.P.get"" IL_000b: stloc.0 IL_000c: ret }"); } [Fact] public void RefAssignStructInstanceProperty() { var text = @" struct Program { public ref int P { get { return ref (new int[1])[0]; } } void M() { ref int rl = ref P; } void M1(ref Program program) { ref int rl = ref program.P; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } void M() { ref int rl = ref program.P; } } class Program3 { Program program = default(Program); void M() { ref int rl = ref program.P; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 9 (0x9) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""ref int Program.P.get"" IL_0007: stloc.0 IL_0008: ret }"); comp.VerifyIL("Program.M1(ref Program)", @" { // Code size 9 (0x9) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.1 IL_0002: call ""ref int Program.P.get"" IL_0007: stloc.0 IL_0008: ret }"); comp.VerifyIL("Program2.M()", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program2.program"" IL_0007: call ""ref int Program.P.get"" IL_000c: stloc.0 IL_000d: ret }"); comp.VerifyIL("Program3.M()", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program3.program"" IL_0007: call ""ref int Program.P.get"" IL_000c: stloc.0 IL_000d: ret }"); } [Fact] public void RefAssignConstrainedInstanceProperty() { var text = @" interface I { ref int P { get; } } class Program<T> where T : I { T t = default(T); void M() { ref int rl = ref t.P; } } class Program2<T> where T : class, I { void M(T t) { ref int rl = ref t.P; } } class Program3<T> where T : struct, I { T t = default(T); void M() { ref int rl = ref t.P; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll); comp.VerifyIL("Program<T>.M()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program<T>.t"" IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.P.get"" IL_0012: stloc.0 IL_0013: ret }"); comp.VerifyIL("Program2<T>.M(T)", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.1 IL_0002: box ""T"" IL_0007: callvirt ""ref int I.P.get"" IL_000c: stloc.0 IL_000d: ret }"); comp.VerifyIL("Program3<T>.M()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program3<T>.t"" IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.P.get"" IL_0012: stloc.0 IL_0013: ret }"); } [Fact] public void RefAssignClassInstanceIndexer() { var text = @" class Program { int field = 0; ref int this[int i] { get { return ref field; } } void M() { ref int rl = ref this[0]; } void M1() { ref int rl = ref new Program()[0]; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 10 (0xa) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""ref int Program.this[int].get"" IL_0008: stloc.0 IL_0009: ret }"); comp.VerifyIL("Program.M1()", @" { // Code size 14 (0xe) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: stloc.0 IL_000d: ret }"); } [Fact] public void RefAssignStructInstanceIndexer() { var text = @" struct Program { public ref int this[int i] { get { return ref (new int[1])[0]; } } void M() { ref int rl = ref this[0]; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } void M() { ref int rl = ref program[0]; } } class Program3 { Program program = default(Program); void M() { ref int rl = ref program[0]; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 10 (0xa) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""ref int Program.this[int].get"" IL_0008: stloc.0 IL_0009: ret }"); comp.VerifyIL("Program2.M()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program2.program"" IL_0007: ldc.i4.0 IL_0008: call ""ref int Program.this[int].get"" IL_000d: stloc.0 IL_000e: ret }"); comp.VerifyIL("Program3.M()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program3.program"" IL_0007: ldc.i4.0 IL_0008: call ""ref int Program.this[int].get"" IL_000d: stloc.0 IL_000e: ret }"); } [Fact] public void RefAssignConstrainedInstanceIndexer() { var text = @" interface I { ref int this[int i] { get; } } class Program<T> where T : I { T t = default(T); void M() { ref int rl = ref t[0]; } } class Program2<T> where T : class, I { void M(T t) { ref int rl = ref t[0]; } } class Program3<T> where T : struct, I { T t = default(T); void M() { ref int rl = ref t[0]; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll); comp.VerifyIL("Program<T>.M()", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program<T>.t"" IL_0007: ldc.i4.0 IL_0008: constrained. ""T"" IL_000e: callvirt ""ref int I.this[int].get"" IL_0013: stloc.0 IL_0014: ret }"); comp.VerifyIL("Program2<T>.M(T)", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.1 IL_0002: box ""T"" IL_0007: ldc.i4.0 IL_0008: callvirt ""ref int I.this[int].get"" IL_000d: stloc.0 IL_000e: ret }"); comp.VerifyIL("Program3<T>.M()", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program3<T>.t"" IL_0007: ldc.i4.0 IL_0008: constrained. ""T"" IL_000e: callvirt ""ref int I.this[int].get"" IL_0013: stloc.0 IL_0014: ret }"); } [Fact] public void RefAssignStaticFieldLikeEvent() { var text = @" delegate void D(); class Program { static event D d; static void M() { ref D rl = ref d; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 1 .locals init (D& V_0) //rl IL_0000: nop IL_0001: ldsflda ""D Program.d"" IL_0006: stloc.0 IL_0007: ret }"); } [Fact] public void RefAssignClassInstanceFieldLikeEvent() { var text = @" delegate void D(); class Program { event D d; void M() { ref D rl = ref d; } void M1() { ref D rl = ref new Program().d; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll); comp.VerifyIL("Program.M()", @" { // Code size 9 (0x9) .maxstack 1 .locals init (D& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""D Program.d"" IL_0007: stloc.0 IL_0008: ret }"); comp.VerifyIL("Program.M1()", @" { // Code size 13 (0xd) .maxstack 1 .locals init (D& V_0) //rl IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: ldflda ""D Program.d"" IL_000b: stloc.0 IL_000c: ret }"); } [Fact] public void RefAssignStaticField() { var text = @" class Program { static int i = 0; static void M() { ref int rl = ref i; rl = i; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldsflda ""int Program.i"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldsfld ""int Program.i"" IL_000d: stind.i4 IL_000e: ret }"); } [Fact] public void RefAssignClassInstanceField() { var text = @" class Program { int i = 0; void M() { ref int rl = ref i; } void M1() { ref int rl = ref new Program().i; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll); comp.VerifyIL("Program.M()", @" { // Code size 9 (0x9) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""int Program.i"" IL_0007: stloc.0 IL_0008: ret }"); comp.VerifyIL("Program.M1()", @" { // Code size 13 (0xd) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: ldflda ""int Program.i"" IL_000b: stloc.0 IL_000c: ret }"); } [Fact] public void RefAssignStructInstanceField() { var text = @" struct Program { public int i; } class Program2 { Program program = default(Program); void M(ref Program program) { ref int rl = ref program.i; rl = program.i; } void M() { ref int rl = ref program.i; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll); comp.VerifyIL("Program2.M(ref Program)", @" { // Code size 17 (0x11) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.1 IL_0002: ldflda ""int Program.i"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldarg.1 IL_000a: ldfld ""int Program.i"" IL_000f: stind.i4 IL_0010: ret }"); comp.VerifyIL("Program2.M()", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program2.program"" IL_0007: ldflda ""int Program.i"" IL_000c: stloc.0 IL_000d: ret }"); } [Fact] public void RefAssignStaticCallWithoutArguments() { var text = @" class Program { static ref int M() { ref int rl = ref M(); return ref rl; } } "; CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M()", @" { // Code size 13 (0xd) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: call ""ref int Program.M()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: br.s IL_000b IL_000b: ldloc.1 IL_000c: ret }"); } [Fact] public void RefAssignClassInstanceCallWithoutArguments() { var text = @" class Program { ref int M() { ref int rl = ref M(); return ref rl; } ref int M1() { ref int rl = ref new Program().M(); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""ref int Program.M()"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: stloc.1 IL_000a: br.s IL_000c IL_000c: ldloc.1 IL_000d: ret }"); comp.VerifyIL("Program.M1()", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: call ""ref int Program.M()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: stloc.1 IL_000e: br.s IL_0010 IL_0010: ldloc.1 IL_0011: ret }"); } [Fact] public void RefAssignStructInstanceCallWithoutArguments() { var text = @" struct Program { public ref int M() { ref int rl = ref M(); return ref rl; } } struct Program2 { Program program; ref int M() { ref int rl = ref program.M(); return ref rl; } } class Program3 { Program program; ref int M() { ref int rl = ref program.M(); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""ref int Program.M()"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: stloc.1 IL_000a: br.s IL_000c IL_000c: ldloc.1 IL_000d: ret }"); comp.VerifyIL("Program2.M()", @" { // Code size 19 (0x13) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program2.program"" IL_0007: call ""ref int Program.M()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.1 IL_000f: br.s IL_0011 IL_0011: ldloc.1 IL_0012: ret }"); comp.VerifyIL("Program3.M()", @" { // Code size 19 (0x13) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program3.program"" IL_0007: call ""ref int Program.M()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.1 IL_000f: br.s IL_0011 IL_0011: ldloc.1 IL_0012: ret }"); } [Fact] public void RefAssignConstrainedInstanceCallWithoutArguments() { var text = @" interface I { ref int M(); } class Program<T> where T : I { T t = default(T); ref int M() { ref int rl = ref t.M(); return ref rl; } } class Program2<T> where T : class, I { ref int M(T t) { ref int rl = ref t.M(); return ref rl; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { ref int rl = ref t.M(); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program<T>.M()", @" { // Code size 25 (0x19) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program<T>.t"" IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.M()"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: stloc.1 IL_0015: br.s IL_0017 IL_0017: ldloc.1 IL_0018: ret }"); comp.VerifyIL("Program2<T>.M(T)", @" { // Code size 19 (0x13) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.1 IL_0002: box ""T"" IL_0007: callvirt ""ref int I.M()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.1 IL_000f: br.s IL_0011 IL_0011: ldloc.1 IL_0012: ret }"); comp.VerifyIL("Program3<T>.M()", @" { // Code size 25 (0x19) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program3<T>.t"" IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.M()"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: stloc.1 IL_0015: br.s IL_0017 IL_0017: ldloc.1 IL_0018: ret }"); } [Fact] public void RefAssignStaticCallWithArguments() { var text = @" class Program { static ref int M(ref int i, ref int j, object o) { ref int rl = ref M(ref i, ref j, o); return ref rl; } } "; CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 16 (0x10) .maxstack 3 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: ldarg.2 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: stloc.1 IL_000c: br.s IL_000e IL_000e: ldloc.1 IL_000f: ret }"); } [Fact] public void RefAssignClassInstanceCallWithArguments() { var text = @" class Program { ref int M(ref int i, ref int j, object o) { ref int rl = ref M(ref i, ref j, o); return ref rl; } ref int M1(ref int i, ref int j, object o) { ref int rl = ref new Program().M(ref i, ref j, o); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: ldarg.2 IL_0004: ldarg.3 IL_0005: call ""ref int Program.M(ref int, ref int, object)"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: stloc.1 IL_000d: br.s IL_000f IL_000f: ldloc.1 IL_0010: ret }"); comp.VerifyIL("Program.M1(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: stloc.1 IL_0011: br.s IL_0013 IL_0013: ldloc.1 IL_0014: ret }"); } [Fact] public void RefAssignStructInstanceCallWithArguments() { var text = @" struct Program { public ref int M(ref int i, ref int j, object o) { ref int rl = ref M(ref i, ref j, o); return ref rl; } } struct Program2 { Program program; ref int M(ref int i, ref int j, object o) { ref int rl = ref program.M(ref i, ref j, o); return ref rl; } } class Program3 { Program program; ref int M(ref int i, ref int j, object o) { ref int rl = ref program.M(ref i, ref j, o); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: ldarg.2 IL_0004: ldarg.3 IL_0005: call ""ref int Program.M(ref int, ref int, object)"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: stloc.1 IL_000d: br.s IL_000f IL_000f: ldloc.1 IL_0010: ret }"); comp.VerifyIL("Program2.M(ref int, ref int, object)", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program2.program"" IL_0007: ldarg.1 IL_0008: ldarg.2 IL_0009: ldarg.3 IL_000a: call ""ref int Program.M(ref int, ref int, object)"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); comp.VerifyIL("Program3.M(ref int, ref int, object)", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program3.program"" IL_0007: ldarg.1 IL_0008: ldarg.2 IL_0009: ldarg.3 IL_000a: call ""ref int Program.M(ref int, ref int, object)"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); } [Fact] public void RefAssignConstrainedInstanceCallWithArguments() { var text = @" interface I { ref int M(ref int i, ref int j, object o); } class Program<T> where T : I { T t = default(T); ref int M(ref int i, ref int j, object o) { ref int rl = ref t.M(ref i, ref j, o); return ref rl; } } class Program2<T> where T : class, I { ref int M(T t, ref int i, ref int j, object o) { ref int rl = ref t.M(ref i, ref j, o); return ref rl; } } class Program3<T> where T : struct, I { T t = default(T); ref int M(ref int i, ref int j, object o) { ref int rl = ref t.M(ref i, ref j, o); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program<T>.M(ref int, ref int, object)", @" { // Code size 28 (0x1c) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program<T>.t"" IL_0007: ldarg.1 IL_0008: ldarg.2 IL_0009: ldarg.3 IL_000a: constrained. ""T"" IL_0010: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0015: stloc.0 IL_0016: ldloc.0 IL_0017: stloc.1 IL_0018: br.s IL_001a IL_001a: ldloc.1 IL_001b: ret }"); comp.VerifyIL("Program2<T>.M(T, ref int, ref int, object)", @" { // Code size 23 (0x17) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.1 IL_0002: box ""T"" IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: ldarg.s V_4 IL_000b: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: br.s IL_0015 IL_0015: ldloc.1 IL_0016: ret }"); comp.VerifyIL("Program3<T>.M(ref int, ref int, object)", @" { // Code size 28 (0x1c) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program3<T>.t"" IL_0007: ldarg.1 IL_0008: ldarg.2 IL_0009: ldarg.3 IL_000a: constrained. ""T"" IL_0010: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0015: stloc.0 IL_0016: ldloc.0 IL_0017: stloc.1 IL_0018: br.s IL_001a IL_001a: ldloc.1 IL_001b: ret }"); } [Fact] public void RefAssignDelegateInvocationWithNoArguments() { var text = @" delegate ref int D(); class Program { static void M(D d) { ref int rl = ref d(); } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(D)", @" { // Code size 9 (0x9) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: callvirt ""ref int D.Invoke()"" IL_0007: stloc.0 IL_0008: ret }"); } [Fact] public void RefAssignDelegateInvocationWithArguments() { var text = @" delegate ref int D(ref int i, ref int j, object o); class Program { static ref int M(D d, ref int i, ref int j, object o) { ref int rl = ref d(ref i, ref j, o); return ref rl; } } "; CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M(D, ref int, ref int, object)", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: ldarg.2 IL_0004: ldarg.3 IL_0005: callvirt ""ref int D.Invoke(ref int, ref int, object)"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: stloc.1 IL_000d: br.s IL_000f IL_000f: ldloc.1 IL_0010: ret }"); } [Fact] public void RefLocalsAreVariables() { var text = @" class Program { static int field = 0; static void M(ref int i) { } static void N(out int i) { i = 0; } static unsafe void Main() { ref int rl = ref field; rl = 0; rl += 1; rl++; M(ref rl); N(out rl); fixed (int* i = &rl) { } var tr = __makeref(rl); } } "; CompileAndVerify(text, options: TestOptions.UnsafeDebugDll).VerifyIL("Program.Main()", @" { // Code size 51 (0x33) .maxstack 3 .locals init (int& V_0, //rl System.TypedReference V_1, //tr pinned int& V_2) //i IL_0000: nop IL_0001: ldsflda ""int Program.field"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: stind.i4 IL_000a: ldloc.0 IL_000b: ldloc.0 IL_000c: ldind.i4 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stind.i4 IL_0010: ldloc.0 IL_0011: ldloc.0 IL_0012: ldind.i4 IL_0013: ldc.i4.1 IL_0014: add IL_0015: stind.i4 IL_0016: ldloc.0 IL_0017: call ""void Program.M(ref int)"" IL_001c: nop IL_001d: ldloc.0 IL_001e: call ""void Program.N(out int)"" IL_0023: nop IL_0024: ldloc.0 IL_0025: stloc.2 IL_0026: nop IL_0027: nop IL_0028: ldc.i4.0 IL_0029: conv.u IL_002a: stloc.2 IL_002b: ldloc.0 IL_002c: mkrefany ""int"" IL_0031: stloc.1 IL_0032: ret }"); } [Fact] private void RefLocalsAreValues() { var text = @" class Program { static int field = 0; static void N(int i) { } static unsafe int Main() { ref int rl = ref field; var @int = rl + 0; var @string = rl.ToString(); var @long = (long)rl; N(rl); return unchecked((int)((long)@int + @long)); } } "; CompileAndVerify(text, options: TestOptions.UnsafeDebugDll).VerifyIL("Program.Main()", @" { // Code size 41 (0x29) .maxstack 2 .locals init (int& V_0, //rl int V_1, //int string V_2, //string long V_3, //long int V_4) IL_0000: nop IL_0001: ldsflda ""int Program.field"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldind.i4 IL_0009: stloc.1 IL_000a: ldloc.0 IL_000b: call ""string int.ToString()"" IL_0010: stloc.2 IL_0011: ldloc.0 IL_0012: ldind.i4 IL_0013: conv.i8 IL_0014: stloc.3 IL_0015: ldloc.0 IL_0016: ldind.i4 IL_0017: call ""void Program.N(int)"" IL_001c: nop IL_001d: ldloc.1 IL_001e: conv.i8 IL_001f: ldloc.3 IL_0020: add IL_0021: conv.i4 IL_0022: stloc.s V_4 IL_0024: br.s IL_0026 IL_0026: ldloc.s V_4 IL_0028: ret } "); } [Fact] public void RefLocal_CSharp6() { var text = @" class Program { static void M() { ref int rl = ref (new int[1])[0]; } } "; var comp = CreateStandardCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7 or greater. // ref int rl = ref (new int[1])[0]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref int").WithArguments("byref locals and returns", "7").WithLocation(6, 9), // (6,22): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7 or greater. // ref int rl = ref (new int[1])[0]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7").WithLocation(6, 22) ); } [Fact] public void RefVarSemanticModel() { var text = @" class Program { static void M() { int i = 0; ref var x = ref i; } } "; var comp = CreateStandardCompilation(text); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var xDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); Assert.Equal("System.Int32 x", model.GetDeclaredSymbol(xDecl).ToTestDisplayString()); var refVar = tree.GetRoot().DescendantNodes().OfType<RefTypeSyntax>().Single(); var type = refVar.Type; Assert.Equal("System.Int32", model.GetTypeInfo(type).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetSymbolInfo(type).Symbol.ToTestDisplayString()); Assert.Null(model.GetAliasInfo(type)); Assert.Null(model.GetSymbolInfo(refVar).Symbol); Assert.Null(model.GetTypeInfo(refVar).Type); } [Fact] public void RefAliasVarSemanticModel() { var text = @" using var = C; class C { static void M() { C i = null; ref var x = ref i; } } "; var comp = CreateStandardCompilation(text); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var xDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); Assert.Equal("C x", model.GetDeclaredSymbol(xDecl).ToTestDisplayString()); var refVar = tree.GetRoot().DescendantNodes().OfType<RefTypeSyntax>().Single(); var type = refVar.Type; Assert.Equal("C", model.GetTypeInfo(type).Type.ToTestDisplayString()); Assert.Equal("C", model.GetSymbolInfo(type).Symbol.ToTestDisplayString()); var alias = model.GetAliasInfo(type); Assert.Equal(SymbolKind.NamedType, alias.Target.Kind); Assert.Equal("C", alias.Target.ToDisplayString()); Assert.Null(model.GetSymbolInfo(refVar).Symbol); Assert.Null(model.GetTypeInfo(refVar).Type); } [Fact] public void RefIntSemanticModel() { var text = @" class Program { static void M() { int i = 0; ref System.Int32 x = ref i; } } "; var comp = CreateStandardCompilation(text); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var xDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); Assert.Equal("System.Int32 x", model.GetDeclaredSymbol(xDecl).ToTestDisplayString()); var refInt = tree.GetRoot().DescendantNodes().OfType<RefTypeSyntax>().Single(); var type = refInt.Type; Assert.Equal("System.Int32", model.GetTypeInfo(type).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetSymbolInfo(type).Symbol.ToTestDisplayString()); Assert.Null(model.GetAliasInfo(type)); Assert.Null(model.GetSymbolInfo(refInt).Symbol); Assert.Null(model.GetTypeInfo(refInt).Type); } [WorkItem(17395, "https://github.com/dotnet/roslyn/issues/17453")] [Fact] public void Regression17395() { var source = @" using System; public class C { public void F() { ref int[] a = ref {1,2,3}; Console.WriteLine(a[0]); ref var b = ref {4, 5, 6}; Console.WriteLine(b[0]); ref object c = ref {7,8,9}; Console.WriteLine(c); } } "; var c = CreateStandardCompilation(source); c.VerifyDiagnostics( // (8,27): error CS1510: A ref or out value must be an assignable variable // ref int[] a = ref {1,2,3}; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "{1,2,3}"), // (11,17): error CS0820: Cannot initialize an implicitly-typed variable with an array initializer // ref var b = ref {4, 5, 6}; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, "b = ref {4, 5, 6}").WithLocation(11, 17), // (14,28): error CS0622: Can only use array initializer expressions to assign to array types. Try using a new expression instead. // ref object c = ref {7,8,9}; Diagnostic(ErrorCode.ERR_ArrayInitToNonArrayType, "{7,8,9}").WithLocation(14, 28) ); } } }
namespace Trionic5Controls { partial class SurfaceGraphViewer { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.spinEdit1 = new DevExpress.XtraEditors.SpinEdit(); this.spinEdit2 = new DevExpress.XtraEditors.SpinEdit(); this.spinEdit3 = new DevExpress.XtraEditors.SpinEdit(); this.spinEdit4 = new DevExpress.XtraEditors.SpinEdit(); this.toolTipController1 = new DevExpress.Utils.ToolTipController(this.components); this.spinEdit5 = new DevExpress.XtraEditors.SpinEdit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit2.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit5.Properties)).BeginInit(); this.SuspendLayout(); // // spinEdit1 // this.spinEdit1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.spinEdit1.EditValue = new decimal(new int[] { 0, 0, 0, 0}); this.spinEdit1.Location = new System.Drawing.Point(11, 401); this.spinEdit1.Name = "spinEdit1"; this.spinEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit1.Properties.IsFloatValue = false; this.spinEdit1.Properties.Mask.EditMask = "N00"; this.spinEdit1.Properties.MaxValue = new decimal(new int[] { 180, 0, 0, 0}); this.spinEdit1.Properties.MinValue = new decimal(new int[] { 180, 0, 0, -2147483648}); this.spinEdit1.Size = new System.Drawing.Size(60, 20); this.spinEdit1.TabIndex = 0; this.spinEdit1.Visible = false; this.spinEdit1.ValueChanged += new System.EventHandler(this.spinEdit1_ValueChanged); // // spinEdit2 // this.spinEdit2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.spinEdit2.EditValue = new decimal(new int[] { 0, 0, 0, 0}); this.spinEdit2.Location = new System.Drawing.Point(77, 401); this.spinEdit2.Name = "spinEdit2"; this.spinEdit2.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit2.Properties.IsFloatValue = false; this.spinEdit2.Properties.Mask.EditMask = "N00"; this.spinEdit2.Properties.MaxValue = new decimal(new int[] { 180, 0, 0, 0}); this.spinEdit2.Properties.MinValue = new decimal(new int[] { 180, 0, 0, -2147483648}); this.spinEdit2.Size = new System.Drawing.Size(60, 20); this.spinEdit2.TabIndex = 1; this.spinEdit2.Visible = false; this.spinEdit2.ValueChanged += new System.EventHandler(this.spinEdit1_ValueChanged); // // spinEdit3 // this.spinEdit3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.spinEdit3.EditValue = new decimal(new int[] { 0, 0, 0, 0}); this.spinEdit3.Location = new System.Drawing.Point(143, 401); this.spinEdit3.Name = "spinEdit3"; this.spinEdit3.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit3.Properties.IsFloatValue = false; this.spinEdit3.Properties.Mask.EditMask = "N00"; this.spinEdit3.Properties.MaxValue = new decimal(new int[] { 180, 0, 0, 0}); this.spinEdit3.Properties.MinValue = new decimal(new int[] { 180, 0, 0, -2147483648}); this.spinEdit3.Size = new System.Drawing.Size(60, 20); this.spinEdit3.TabIndex = 2; this.spinEdit3.Visible = false; this.spinEdit3.ValueChanged += new System.EventHandler(this.spinEdit1_ValueChanged); // // spinEdit4 // this.spinEdit4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.spinEdit4.EditValue = new decimal(new int[] { 5, 0, 0, 65536}); this.spinEdit4.Location = new System.Drawing.Point(209, 401); this.spinEdit4.Name = "spinEdit4"; this.spinEdit4.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit4.Properties.Increment = new decimal(new int[] { 1, 0, 0, 65536}); this.spinEdit4.Properties.MaxValue = new decimal(new int[] { 100, 0, 0, 0}); this.spinEdit4.Size = new System.Drawing.Size(60, 20); this.spinEdit4.TabIndex = 3; this.spinEdit4.Visible = false; this.spinEdit4.ValueChanged += new System.EventHandler(this.spinEdit4_ValueChanged); // // spinEdit5 // this.spinEdit5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.spinEdit5.EditValue = new decimal(new int[] { 12, 0, 0, 0}); this.spinEdit5.Location = new System.Drawing.Point(275, 401); this.spinEdit5.Name = "spinEdit5"; this.spinEdit5.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit5.Properties.IsFloatValue = false; this.spinEdit5.Properties.Mask.EditMask = "N00"; this.spinEdit5.Properties.MaxValue = new decimal(new int[] { 180, 0, 0, 0}); this.spinEdit5.Properties.MinValue = new decimal(new int[] { 180, 0, 0, -2147483648}); this.spinEdit5.Size = new System.Drawing.Size(60, 20); this.spinEdit5.TabIndex = 4; this.spinEdit5.Visible = false; this.spinEdit5.EditValueChanged += new System.EventHandler(this.spinEdit5_EditValueChanged); // // SurfaceGraphViewer // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.spinEdit5); this.Controls.Add(this.spinEdit4); this.Controls.Add(this.spinEdit3); this.Controls.Add(this.spinEdit2); this.Controls.Add(this.spinEdit1); this.Name = "SurfaceGraphViewer"; this.Size = new System.Drawing.Size(578, 435); this.toolTipController1.SetSuperTip(this, null); this.DoubleClick += new System.EventHandler(this.SurfaceGraphViewer_DoubleClick); this.Load += new System.EventHandler(this.SurfaceGraphViewer_Load); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.frm3DSurfaceGraphViewer_MouseDown); this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.frm3DSurfaceGraphViewer_MouseMove); this.Scroll += new System.Windows.Forms.ScrollEventHandler(this.SurfaceGraphViewer_Scroll); this.Resize += new System.EventHandler(this.frm3DSurfaceGraphViewer_Resize); this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.SurfaceGraphViewer_KeyPress); this.Paint += new System.Windows.Forms.PaintEventHandler(this.frm3DSurfaceGraphViewer_Paint); this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.frm3DSurfaceGraphViewer_MouseUp); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.SurfaceGraphViewer_KeyDown); ((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit2.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit5.Properties)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraEditors.SpinEdit spinEdit1; private DevExpress.XtraEditors.SpinEdit spinEdit2; private DevExpress.XtraEditors.SpinEdit spinEdit3; private DevExpress.XtraEditors.SpinEdit spinEdit4; private DevExpress.Utils.ToolTipController toolTipController1; private DevExpress.XtraEditors.SpinEdit spinEdit5; } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Collections.Generic; using Boo.Lang.Resources; using Boo.Lang.Runtime; namespace Boo.Lang { public delegate TResult Function<in T1, out TResult>(T1 arg); [Serializable] public class List<T> : IList<T>, IList, IEquatable<List<T>> { private static readonly T[] EmptyArray = new T[0]; protected T[] _items; protected int _count; public List() { _items = EmptyArray; } public List(IEnumerable enumerable) : this() { Extend(enumerable); } public List(int initialCapacity) { if (initialCapacity < 0) throw new ArgumentOutOfRangeException("initialCapacity"); _items = new T[initialCapacity]; _count = 0; } public List(T[] items, bool takeOwnership) { if (null == items) throw new ArgumentNullException("items"); _items = takeOwnership ? items : (T[]) items.Clone(); _count = items.Length; } public static List<T> operator*(List<T> lhs, int count) { return lhs.Multiply(count); } public static List<T> operator*(int count, List<T> rhs) { return rhs.Multiply(count); } public static List<T> operator+(List<T> lhs, IEnumerable rhs) { var result = lhs.NewConcreteList(lhs.ToArray(), true); result.Extend(rhs); return result; } public List<T> Multiply(int count) { if (count < 0) throw new ArgumentOutOfRangeException("count"); var items = new T[_count*count]; for (int i=0; i<count; ++i) Array.Copy(_items, 0, items, i*_count, _count); return NewConcreteList(items, true); } protected virtual List<T> NewConcreteList(T[] items, bool takeOwnership) { return new List<T>(items, takeOwnership); } public IEnumerable<T> Reversed { get { for (int i=_count-1; i>=0; --i) yield return _items[i]; } } public int Count { get { return _count; } } void ICollection<T>.Add(T item) { Push(item); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>) this).GetEnumerator(); } public IEnumerator<T> GetEnumerator() { int originalCount = _count; T[] originalItems = _items; for (int i = 0; i < _count; ++i) { if (originalCount != _count || originalItems != _items) throw new InvalidOperationException(StringResources.ListWasModified); yield return _items[i]; } } public void CopyTo(T[] target, int index) { Array.Copy(_items, 0, target, index, _count); } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return _items; } } public bool IsReadOnly { get { return false; } } public T this[int index] { get { return _items[CheckIndex(NormalizeIndex(index))]; } set { _items[CheckIndex(NormalizeIndex(index))] = value; } } public T FastAt(int normalizedIndex) { return _items[normalizedIndex]; } public List<T> Push(T item) { return Add(item); } public virtual List<T> Add(T item) { EnsureCapacity(_count+1); _items[_count] = item; ++_count; return this; } public List<T> AddUnique(T item) { if (!Contains(item)) Add(item); return this; } public List<T> Extend(IEnumerable enumerable) { AddRange(enumerable); return this; } public void AddRange(IEnumerable enumerable) { foreach (T item in enumerable) Add(item); } public List<T> ExtendUnique(IEnumerable enumerable) { foreach (T item in enumerable) AddUnique(item); return this; } public List<T> Collect(Predicate<T> condition) { if (null == condition) throw new ArgumentNullException("condition"); var newList = NewConcreteList(new T[0], true); InnerCollect(newList, condition); return newList; } public List<T> Collect(List<T> target, Predicate<T> condition) { if (null == target) throw new ArgumentNullException("target"); if (null == condition) throw new ArgumentNullException("condition"); InnerCollect(target, condition); return target; } public T[] ToArray() { if (_count == 0) return EmptyArray; var target = new T[_count]; CopyTo(target, 0); return target; } public T[] ToArray(T[] array) { CopyTo(array, 0); return array; } public TOut[] ToArray<TOut>(Function<T, TOut> selector) { var result = new TOut[_count]; for (var i = 0; i < _count; ++i) result[i] = selector(_items[i]); return result; } public List<T> Sort() { Array.Sort(_items, 0, _count, BooComparer.Default); return this; } public List<T> Sort(IComparer comparer) { Array.Sort(_items, 0, _count, comparer); return this; } private sealed class ComparisonComparer : IComparer<T> { private readonly Comparison<T> _comparison; public ComparisonComparer(Comparison<T> comparison) { _comparison = comparison; } #region IComparer<T> Members public int Compare(T x, T y) { return _comparison(x, y); } #endregion } public List<T> Sort(Comparison<T> comparison) { return Sort(new ComparisonComparer(comparison)); } public List<T> Sort(IComparer<T> comparer) { Array.Sort(_items, 0, _count, comparer); return this; } public List<T> Sort(Comparer comparer) { if (null == comparer) throw new ArgumentNullException("comparer"); Array.Sort(_items, 0, _count, comparer); return this; } override public string ToString() { return "[" + Join(", ") + "]"; } public string Join(string separator) { return Builtins.join(this, separator); } override public int GetHashCode() { var hash = _count; for (var i=0; i<_count; ++i) { var item = _items[i]; if (item != null) hash ^= item.GetHashCode(); } return hash; } override public bool Equals(object other) { if (null == other) return false; if (this == other) return true; var list = other as List<T>; return Equals(list); } public bool Equals(List<T> other) { if (null == other) return false; if (this == other) return true; if (_count != other.Count) return false; for (int i=0; i < _count; ++i) if (!RuntimeServices.EqualityOperator(_items[i], other[i])) return false; return true; } public void Clear() { for (int i=0; i<_count; ++i) _items[i] = default(T); _count = 0; } public List<T> GetRange(int begin) { return InnerGetRange(AdjustIndex(NormalizeIndex(begin)), _count); } public List<T> GetRange(int begin, int end) { return InnerGetRange( AdjustIndex(NormalizeIndex(begin)), AdjustIndex(NormalizeIndex(end))); } public bool Contains(T item) { return -1 != IndexOf(item); } public bool Contains(Predicate<T> condition) { return -1 != IndexOf(condition); } public bool Find(Predicate<T> condition, out T found) { int index = IndexOf(condition); if (-1 != index) { found = _items[index]; return true; } found = default(T); return false; } public List<T> FindAll(Predicate<T> condition) { var result = NewConcreteList(new T[0], true); foreach (T item in this) if (condition(item)) result.Add(item); return result; } public int IndexOf(Predicate<T> condition) { if (null == condition) throw new ArgumentNullException("condition"); for (int i=0; i<_count; ++i) if (condition(_items[i])) return i; return -1; } public int IndexOf(T item) { for (int i=0; i<_count; ++i) if (RuntimeServices.EqualityOperator(_items[i], item)) return i; return -1; } public List<T> Insert(int index, T item) { int actual = NormalizeIndex(index); EnsureCapacity(Math.Max(_count, actual) + 1); if (actual < _count) Array.Copy(_items, actual, _items, actual+1, _count-actual); _items[actual] = item; ++_count; return this; } public T Pop() { return Pop(-1); } public T Pop(int index) { int actualIndex = CheckIndex(NormalizeIndex(index)); T item = _items[actualIndex]; InnerRemoveAt(actualIndex); return item; } public List<T> PopRange(int begin) { int actualIndex = AdjustIndex(NormalizeIndex(begin)); List<T> range = InnerGetRange(actualIndex, AdjustIndex(NormalizeIndex(_count))); for (int i=actualIndex; i<_count; ++i) _items[i] = default(T); _count = actualIndex; return range; } public List<T> RemoveAll(Predicate<T> match) { if (null == match) throw new ArgumentNullException("match"); for (int i=0; i<_count; ++i) if (match(_items[i])) InnerRemoveAt(i--); return this; } public List<T> Remove(T item) { InnerRemove(item); return this; } public List<T> RemoveAt(int index) { InnerRemoveAt(CheckIndex(NormalizeIndex(index))); return this; } void IList<T>.Insert(int index, T item) { Insert(index, item); } void IList<T>.RemoveAt(int index) { InnerRemoveAt(CheckIndex(NormalizeIndex(index))); } bool ICollection<T>.Remove(T item) { return InnerRemove(item); } void EnsureCapacity(int minCapacity) { if (minCapacity > _items.Length) { T[] items = NewArray(minCapacity); Array.Copy(_items, 0, items, 0, _count); _items = items; } } T[] NewArray(int minCapacity) { int newLen = Math.Max(1, _items.Length)*2; return new T[Math.Max(newLen, minCapacity)]; } void InnerRemoveAt(int index) { --_count; _items[index] = default(T); if (index != _count) Array.Copy(_items, index+1, _items, index, _count-index); } bool InnerRemove(T item) { int index = IndexOf(item); if (index != -1) { InnerRemoveAt(index); return true; } return false; } void InnerCollect(List<T> target, Predicate<T> condition) { for (int i=0; i<_count; ++i) { T item = _items[i]; if (condition(item)) target.Add(item); } } List<T> InnerGetRange(int begin, int end) { int targetLen = end-begin; if (targetLen > 0) { var target = new T[targetLen]; Array.Copy(_items, begin, target, 0, targetLen); return NewConcreteList(target, true); } return NewConcreteList(new T[0], true); } int AdjustIndex(int index) { if (index > _count) return _count; if (index < 0) return 0; return index; } int CheckIndex(int index) { if (index >= _count) throw new IndexOutOfRangeException(); return index; } int NormalizeIndex(int index) { return index < 0 ? index + _count : index; } #region IList Members int IList.Add(object value) { Add((T)value); return Count - 1; } void IList.Insert(int index, object value) { Insert(index, Coerce(value)); } private static T Coerce(object value) { if (value is T) return (T) value; return (T)RuntimeServices.Coerce(value, typeof(T)); } void IList.Remove(object value) { Remove(Coerce(value)); } int IList.IndexOf(object value) { return IndexOf(Coerce(value)); } bool IList.Contains(object value) { return Contains(Coerce(value)); } object IList.this[int index] { get { return this[index]; } set { this[index] = Coerce(value); } } void IList.RemoveAt(int index) { RemoveAt(index); } bool IList.IsFixedSize { get { return false; } } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { Array.Copy(_items, 0, array, index, _count); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.Internal; using Microsoft.Internal.Collections; namespace System.ComponentModel.Composition.Hosting { // This class guarantees thread-safety under the following conditions: // - Each composition is executed on a single thread // - No recomposition ever takes place // - The class is created with isThreadSafe=true public partial class ImportEngine : ICompositionService, IDisposable { private const int MaximumNumberOfCompositionIterations = 100; private volatile bool _isDisposed; private ExportProvider _sourceProvider; private Stack<PartManager> _recursionStateStack = new Stack<PartManager>(); private ConditionalWeakTable<ComposablePart, PartManager> _partManagers = new ConditionalWeakTable<ComposablePart, PartManager>(); private RecompositionManager _recompositionManager = new RecompositionManager(); private readonly CompositionLock _lock = null; private readonly CompositionOptions _compositionOptions; /// <summary> /// Initializes a new instance of the <see cref="ImportEngine"/> class. /// </summary> /// <param name="sourceProvider"> /// The <see cref="ExportProvider"/> which provides the /// <see cref="ImportEngine"/> access to <see cref="Export"/>s. /// </param> public ImportEngine(ExportProvider sourceProvider) : this(sourceProvider, CompositionOptions.Default) { } public ImportEngine(ExportProvider sourceProvider, bool isThreadSafe) : this(sourceProvider, isThreadSafe ? CompositionOptions.IsThreadSafe : CompositionOptions.Default) { } public ImportEngine(ExportProvider sourceProvider, CompositionOptions compositionOptions) { Requires.NotNull(sourceProvider, nameof(sourceProvider)); _compositionOptions = compositionOptions; _sourceProvider = sourceProvider; _sourceProvider.ExportsChanging += OnExportsChanging; _lock = new CompositionLock(compositionOptions.HasFlag(CompositionOptions.IsThreadSafe)); } /// <summary> /// Previews all the required imports for the given <see cref="ComposablePart"/> to /// ensure they can all be satisified. The preview does not actually set the imports /// only ensures that they exist in the source provider. If the preview succeeds then /// the <see cref="ImportEngine"/> also enforces that changes to exports in the source /// provider will not break any of the required imports. If this enforcement needs to be /// lifted for this part then <see cref="ReleaseImports"/> needs to be called for this /// <see cref="ComposablePart"/>. /// </summary> /// <param name="part"> /// The <see cref="ComposablePart"/> to preview the required imports. /// </param> /// <param name="atomicComposition"></param> /// <exception cref="CompositionException"> /// An error occurred during previewing and <paramref name="atomicComposition"/> is null. /// <see cref="CompositionException.Errors"/> will contain a collection of errors that occurred. /// The pre-existing composition is in an unknown state, depending on the errors that occured. /// </exception> /// <exception cref="ChangeRejectedException"> /// An error occurred during the previewing and <paramref name="atomicComposition"/> is not null. /// <see cref="CompositionException.Errors"/> will contain a collection of errors that occurred. /// The pre-existing composition remains in valid state. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="ImportEngine"/> has been disposed of. /// </exception> public void PreviewImports(ComposablePart part, AtomicComposition atomicComposition) { ThrowIfDisposed(); Requires.NotNull(part, nameof(part)); // Do not do any previewing if SilentRejection is disabled. if (_compositionOptions.HasFlag(CompositionOptions.DisableSilentRejection)) { return; } // NOTE : this is a very intricate area threading-wise, please use caution when changing, otherwise state corruption or deadlocks will ensue // The gist of what we are doing is as follows: // We need to lock the composition, as we will proceed modifying our internal state. The tricky part is when we release the lock // Due to the fact that some actions will take place AFTER we leave this method, we need to KEEP THAT LOCK HELD until the transation is commiited or rolled back // This is the reason we CAN'T use "using here. // Instead, if the transaction is present we will queue up the release of the lock, otherwise we will release it when we exit this method // We add the "release" lock to BOTH Commit and Revert queues, because they are mutually exclusive, and we need to release the lock regardless. // This will take the lock, if necesary IDisposable compositionLockHolder = _lock.IsThreadSafe ? _lock.LockComposition() : null; bool compositionLockTaken = (compositionLockHolder != null); try { // revert actions are processed in the reverse order, so we have to add the "release lock" action now if (compositionLockTaken && (atomicComposition != null)) { atomicComposition.AddRevertAction(() => compositionLockHolder.Dispose()); } var partManager = GetPartManager(part, true); var result = TryPreviewImportsStateMachine(partManager, part, atomicComposition); result.ThrowOnErrors(atomicComposition); StartSatisfyingImports(partManager, atomicComposition); // Add the "release lock" to the commit actions if (compositionLockTaken && (atomicComposition != null)) { atomicComposition.AddCompleteAction(() => compositionLockHolder.Dispose()); } } finally { // We haven't updated the queues, so we can release the lock now if (compositionLockTaken && (atomicComposition == null)) { compositionLockHolder.Dispose(); } } } /// <summary> /// Satisfies the imports of the specified composable part. If the satisfy succeeds then /// the <see cref="ImportEngine"/> also enforces that changes to exports in the source /// provider will not break any of the required imports. If this enforcement needs to be /// lifted for this part then <see cref="ReleaseImports"/> needs to be called for this /// <see cref="ComposablePart"/>. /// </summary> /// <param name="part"> /// The <see cref="ComposablePart"/> to set the imports. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="part"/> is <see langword="null"/>. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="ImportEngine"/> has been disposed of. /// </exception> public void SatisfyImports(ComposablePart part) { ThrowIfDisposed(); Requires.NotNull(part, nameof(part)); // NOTE : the following two calls use the state lock PartManager partManager = GetPartManager(part, true); if (partManager.State == ImportState.Composed) { return; } using (_lock.LockComposition()) { var result = TrySatisfyImports(partManager, part, true); result.ThrowOnErrors(); // throw CompositionException not ChangeRejectedException } } /// <summary> /// Sets the imports of the specified composable part exactly once and they will not /// ever be recomposed. /// </summary> /// <param name="part"> /// The <see cref="ComposablePart"/> to set the imports. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="part"/> is <see langword="null"/>. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="ICompositionService"/> has been disposed of. /// </exception> public void SatisfyImportsOnce(ComposablePart part) { ThrowIfDisposed(); Requires.NotNull(part, nameof(part)); // NOTE : the following two calls use the state lock PartManager partManager = GetPartManager(part, true); if (partManager.State == ImportState.Composed) { return; } using (_lock.LockComposition()) { var result = TrySatisfyImports(partManager, part, false); result.ThrowOnErrors(); // throw CompositionException not ChangeRejectedException } } /// <summary> /// Removes any state stored in the <see cref="ImportEngine"/> for the associated /// <see cref="ComposablePart"/> and releases all the <see cref="Export"/>s used to /// satisfy the imports on the <see cref="ComposablePart"/>. /// /// Also removes the enforcement for changes that would break a required import on /// <paramref name="part"/>. /// </summary> /// <param name="part"> /// The <see cref="ComposablePart"/> to release the imports on. /// </param> /// <param name="atomicComposition"> /// The <see cref="AtomicComposition"/> that the release imports is running under. /// </param> public void ReleaseImports(ComposablePart part, AtomicComposition atomicComposition) { ThrowIfDisposed(); Requires.NotNull(part, nameof(part)); using (_lock.LockComposition()) { PartManager partManager = GetPartManager(part, false); if (partManager != null) { StopSatisfyingImports(partManager, atomicComposition); } } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (!_isDisposed) { bool disposeLock = false; ExportProvider sourceProviderToUnsubscribeFrom = null; using (_lock.LockStateForWrite()) { if (!_isDisposed) { sourceProviderToUnsubscribeFrom = _sourceProvider; _sourceProvider = null; _recompositionManager = null; _partManagers = null; _isDisposed = true; disposeLock = true; } } if (sourceProviderToUnsubscribeFrom != null) { sourceProviderToUnsubscribeFrom.ExportsChanging -= OnExportsChanging; } if (disposeLock) { _lock.Dispose(); } } } } private CompositionResult TryPreviewImportsStateMachine(PartManager partManager, ComposablePart part, AtomicComposition atomicComposition) { var result = CompositionResult.SucceededResult; if (partManager.State == ImportState.ImportsPreviewing) { // We shouldn't nomally ever hit this case but if we do // then we should just error with a cycle error. return new CompositionResult(ErrorBuilder.CreatePartCycle(part)); } // Transition from NoImportsStatisified to ImportsPreviewed if (partManager.State == ImportState.NoImportsSatisfied) { partManager.State = ImportState.ImportsPreviewing; var requiredImports = part.ImportDefinitions.Where(IsRequiredImportForPreview); // If this atomicComposition gets rolledback for any reason we need to reset our state atomicComposition.AddRevertActionAllowNull(() => partManager.State = ImportState.NoImportsSatisfied); result = result.MergeResult( TrySatisfyImportSubset(partManager, requiredImports, atomicComposition)); if (!result.Succeeded) { partManager.State = ImportState.NoImportsSatisfied; return result; } partManager.State = ImportState.ImportsPreviewed; } return result; } private CompositionResult TrySatisfyImportsStateMachine(PartManager partManager, ComposablePart part) { var result = CompositionResult.SucceededResult; while (partManager.State < ImportState.Composed) { var previousState = partManager.State; switch (partManager.State) { // "ed" states which represent a some sort of steady state and will // attempt to do a state transition case ImportState.NoImportsSatisfied: case ImportState.ImportsPreviewed: { partManager.State = ImportState.PreExportImportsSatisfying; var prereqImports = part.ImportDefinitions.Where(import => import.IsPrerequisite); result = result.MergeResult( TrySatisfyImportSubset(partManager, prereqImports, null)); partManager.State = ImportState.PreExportImportsSatisfied; break; } case ImportState.PreExportImportsSatisfied: { partManager.State = ImportState.PostExportImportsSatisfying; var requiredImports = part.ImportDefinitions.Where(import => !import.IsPrerequisite); result = result.MergeResult( TrySatisfyImportSubset(partManager, requiredImports, null)); partManager.State = ImportState.PostExportImportsSatisfied; break; } case ImportState.PostExportImportsSatisfied: { partManager.State = ImportState.ComposedNotifying; partManager.ClearSavedImports(); result = result.MergeResult(partManager.TryOnComposed()); partManager.State = ImportState.Composed; break; } // "ing" states which represent some sort of cycle // These state should always return, error or not, instead of breaking case ImportState.ImportsPreviewing: { // We shouldn't nomally ever hit this case but if we do // then we should just error with a cycle error. return new CompositionResult(ErrorBuilder.CreatePartCycle(part)); } case ImportState.PreExportImportsSatisfying: case ImportState.PostExportImportsSatisfying: { if (InPrerequisiteLoop()) { return result.MergeError(ErrorBuilder.CreatePartCycle(part)); } // Cycles in post export imports are allowed so just return in that case return result; } case ImportState.ComposedNotifying: { // We are currently notifying so don't notify again just return return result; } } // if an error occured while doing a state transition if (!result.Succeeded) { // revert to the previous state and return the error partManager.State = previousState; return result; } } return result; } private CompositionResult TrySatisfyImports(PartManager partManager, ComposablePart part, bool shouldTrackImports) { if (part == null) { throw new ArgumentNullException(nameof(part)); } var result = CompositionResult.SucceededResult; // get out if the part is already composed if (partManager.State == ImportState.Composed) { return result; } // Track number of recursive iterations and throw an exception before the stack // fills up and debugging the root cause becomes tricky if (_recursionStateStack.Count >= MaximumNumberOfCompositionIterations) { return result.MergeError( ErrorBuilder.ComposeTookTooManyIterations(MaximumNumberOfCompositionIterations)); } // Maintain the stack to detect whether recursive loops cross prerequisites _recursionStateStack.Push(partManager); try { result = result.MergeResult( TrySatisfyImportsStateMachine(partManager, part)); } finally { _recursionStateStack.Pop(); } if (shouldTrackImports) { StartSatisfyingImports(partManager, null); } return result; } private CompositionResult TrySatisfyImportSubset(PartManager partManager, IEnumerable<ImportDefinition> imports, AtomicComposition atomicComposition) { CompositionResult result = CompositionResult.SucceededResult; var part = partManager.Part; foreach (ImportDefinition import in imports) { var exports = partManager.GetSavedImport(import); if (exports == null) { CompositionResult<IEnumerable<Export>> exportsResult = TryGetExports( _sourceProvider, part, import, atomicComposition); if (!exportsResult.Succeeded) { result = result.MergeResult(exportsResult.ToResult()); continue; } exports = exportsResult.Value.AsArray(); } if (atomicComposition == null) { result = result.MergeResult( partManager.TrySetImport(import, exports)); } else { partManager.SetSavedImport(import, exports, atomicComposition); } } return result; } private void OnExportsChanging(object sender, ExportsChangeEventArgs e) { CompositionResult result = CompositionResult.SucceededResult; // Prepare for the recomposition effort by minimizing the amount of work we'll have to do later AtomicComposition atomicComposition = e.AtomicComposition; IEnumerable<PartManager> affectedParts = _recompositionManager.GetAffectedParts(e.ChangedContractNames); // When in a atomicComposition account for everything that isn't yet reflected in the // index if (atomicComposition != null) { EngineContext engineContext; if (atomicComposition.TryGetValue(this, out engineContext)) { // always added the new part managers to see if they will also be // affected by these changes affectedParts = affectedParts.ConcatAllowingNull(engineContext.GetAddedPartManagers()) .Except(engineContext.GetRemovedPartManagers()); } } var changedExports = e.AddedExports.ConcatAllowingNull(e.RemovedExports); foreach (var partManager in affectedParts) { result = result.MergeResult(TryRecomposeImports(partManager, changedExports, atomicComposition)); } result.ThrowOnErrors(atomicComposition); } private CompositionResult TryRecomposeImports(PartManager partManager, IEnumerable<ExportDefinition> changedExports, AtomicComposition atomicComposition) { var result = CompositionResult.SucceededResult; switch (partManager.State) { case ImportState.ImportsPreviewed: case ImportState.Composed: // Validate states to continue. break; default: { // All other states are invalid and for recomposition. return new CompositionResult(ErrorBuilder.InvalidStateForRecompposition(partManager.Part)); } } var affectedImports = RecompositionManager.GetAffectedImports(partManager.Part, changedExports); bool partComposed = (partManager.State == ImportState.Composed); bool recomposedImport = false; foreach (var import in affectedImports) { result = result.MergeResult( TryRecomposeImport(partManager, partComposed, import, atomicComposition)); recomposedImport = true; } // Knowing that the part has already been composed before and that the only possible // changes are to recomposable imports, we can safely go ahead and do this now or // schedule it for later if (result.Succeeded && recomposedImport && partComposed) { if (atomicComposition == null) { result = result.MergeResult(partManager.TryOnComposed()); } else { atomicComposition.AddCompleteAction(() => partManager.TryOnComposed().ThrowOnErrors()); } } return result; } private CompositionResult TryRecomposeImport(PartManager partManager, bool partComposed, ImportDefinition import, AtomicComposition atomicComposition) { if (partComposed && !import.IsRecomposable) { return new CompositionResult(ErrorBuilder.PreventedByExistingImport(partManager.Part, import)); } // During recomposition you must always requery with the new atomicComposition you cannot use any // cached value in the part manager var exportsResult = TryGetExports(_sourceProvider, partManager.Part, import, atomicComposition); if (!exportsResult.Succeeded) { return exportsResult.ToResult(); } var exports = exportsResult.Value.AsArray(); if (partComposed) { // Knowing that the part has already been composed before and that the only possible // changes are to recomposable imports, we can safely go ahead and do this now or // schedule it for later if (atomicComposition == null) { return partManager.TrySetImport(import, exports); } else { atomicComposition.AddCompleteAction(() => partManager.TrySetImport(import, exports).ThrowOnErrors()); } } else { partManager.SetSavedImport(import, exports, atomicComposition); } return CompositionResult.SucceededResult; } private void StartSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition) { // When not running in a atomicCompositional state, schedule reindexing after ensuring // that this isn't a redundant addition if (atomicComposition == null) { if (!partManager.TrackingImports) { partManager.TrackingImports = true; _recompositionManager.AddPartToIndex(partManager); } } else { // While in a atomicCompositional state use a less efficient but effective means // of achieving the same results GetEngineContext(atomicComposition).AddPartManager(partManager); } } private void StopSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition) { // When not running in a atomicCompositional state, schedule reindexing after ensuring // that this isn't a redundant removal if (atomicComposition == null) { ConditionalWeakTable<ComposablePart, PartManager> partManagers = null; RecompositionManager recompositionManager = null; using (_lock.LockStateForRead()) { partManagers = _partManagers; recompositionManager = _recompositionManager; } if (partManagers != null) // Disposal race may have been won by dispose { partManagers.Remove(partManager.Part); // Take care of lifetime requirements partManager.DisposeAllDependencies(); if (partManager.TrackingImports) { partManager.TrackingImports = false; recompositionManager.AddPartToUnindex(partManager); } } } else { // While in a atomicCompositional state use a less efficient but effective means // of achieving the same results GetEngineContext(atomicComposition).RemovePartManager(partManager); } } private PartManager GetPartManager(ComposablePart part, bool createIfNotpresent) { PartManager partManager = null; using (_lock.LockStateForRead()) { if (_partManagers.TryGetValue(part, out partManager)) { return partManager; } } if (createIfNotpresent) { using (_lock.LockStateForWrite()) { if (!_partManagers.TryGetValue(part, out partManager)) { partManager = new PartManager(this, part); _partManagers.Add(part, partManager); } } } return partManager; } private EngineContext GetEngineContext(AtomicComposition atomicComposition) { if (atomicComposition == null) { throw new ArgumentNullException(nameof(atomicComposition)); } EngineContext engineContext; if (!atomicComposition.TryGetValue(this, true, out engineContext)) { EngineContext parentContext; atomicComposition.TryGetValue(this, false, out parentContext); engineContext = new EngineContext(this, parentContext); atomicComposition.SetValue(this, engineContext); atomicComposition.AddCompleteAction(engineContext.Complete); } return engineContext; } private bool InPrerequisiteLoop() { PartManager firstPart = _recursionStateStack.First(); PartManager lastPart = null; foreach (PartManager testPart in _recursionStateStack.Skip(1)) { if (testPart.State == ImportState.PreExportImportsSatisfying) { return true; } if (testPart == firstPart) { lastPart = testPart; break; } } // This should only be called when a loop has been detected - so it should always be on the stack if (lastPart != firstPart) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } return false; } [DebuggerStepThrough] private void ThrowIfDisposed() { if (_isDisposed) { throw ExceptionBuilder.CreateObjectDisposed(this); } } private static CompositionResult<IEnumerable<Export>> TryGetExports(ExportProvider provider, ComposablePart part, ImportDefinition definition, AtomicComposition atomicComposition) { try { IEnumerable<Export> exports = null; if (provider != null) { exports = provider.GetExports(definition, atomicComposition).AsArray(); } return new CompositionResult<IEnumerable<Export>>(exports); } catch (ImportCardinalityMismatchException ex) { // Either not enough or too many exports that match the definition CompositionException exception = new CompositionException(ErrorBuilder.CreateImportCardinalityMismatch(ex, definition)); return new CompositionResult<IEnumerable<Export>>( ErrorBuilder.CreatePartCannotSetImport(part, definition, exception)); } } internal static bool IsRequiredImportForPreview(ImportDefinition import) { return import.Cardinality == ImportCardinality.ExactlyOne; } // Ordering of this enum is important so be sure to use caution if you // try to reorder them. private enum ImportState { NoImportsSatisfied = 0, ImportsPreviewing = 1, ImportsPreviewed = 2, PreExportImportsSatisfying = 3, PreExportImportsSatisfied = 4, PostExportImportsSatisfying = 5, PostExportImportsSatisfied = 6, ComposedNotifying = 7, Composed = 8, } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Swagger { 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> /// QueryKeysOperations operations. /// </summary> internal partial class QueryKeysOperations : IServiceOperations<SearchManagementClient>, IQueryKeysOperations { /// <summary> /// Initializes a new instance of the QueryKeysOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal QueryKeysOperations(SearchManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SearchManagementClient /// </summary> public SearchManagementClient Client { get; private set; } /// <summary> /// &gt; `#QueryKeys_List` searches for an object that has a string property /// containing "QueryKeys_List". /// /// Returns the list of query API keys for the given Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn832701.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. /// </param> /// <param name='serviceName'> /// The name of the Search service to operate on. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <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<ListQueryKeysResult>> ListWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", 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.Search/searchServices/{serviceName}/listQueryKeys").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ListQueryKeysResult>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ListQueryKeysResult>(_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; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Generators; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Metadata; using Avalonia.Styling; using Avalonia.VisualTree; namespace Avalonia.Controls.Primitives { /// <summary> /// An <see cref="ItemsControl"/> that maintains a selection. /// </summary> /// <remarks> /// <para> /// <see cref="SelectingItemsControl"/> provides a base class for <see cref="ItemsControl"/>s /// that maintain a selection (single or multiple). By default only its /// <see cref="SelectedIndex"/> and <see cref="SelectedItem"/> properties are visible; the /// current multiple selection <see cref="SelectedItems"/> together with the /// <see cref="SelectionMode"/> properties are protected, however a derived class can expose /// these if it wishes to support multiple selection. /// </para> /// <para> /// <see cref="SelectingItemsControl"/> maintains a selection respecting the current /// <see cref="SelectionMode"/> but it does not react to user input; this must be handled in a /// derived class. It does, however, respond to <see cref="IsSelectedChangedEvent"/> events /// from items and updates the selection accordingly. /// </para> /// </remarks> public class SelectingItemsControl : ItemsControl { /// <summary> /// Defines the <see cref="AutoScrollToSelectedItem"/> property. /// </summary> public static readonly StyledProperty<bool> AutoScrollToSelectedItemProperty = AvaloniaProperty.Register<SelectingItemsControl, bool>( nameof(AutoScrollToSelectedItem), defaultValue: true); /// <summary> /// Defines the <see cref="SelectedIndex"/> property. /// </summary> public static readonly DirectProperty<SelectingItemsControl, int> SelectedIndexProperty = AvaloniaProperty.RegisterDirect<SelectingItemsControl, int>( nameof(SelectedIndex), o => o.SelectedIndex, (o, v) => o.SelectedIndex = v, unsetValue: -1); /// <summary> /// Defines the <see cref="SelectedItem"/> property. /// </summary> public static readonly DirectProperty<SelectingItemsControl, object> SelectedItemProperty = AvaloniaProperty.RegisterDirect<SelectingItemsControl, object>( nameof(SelectedItem), o => o.SelectedItem, (o, v) => o.SelectedItem = v, defaultBindingMode: BindingMode.TwoWay); /// <summary> /// Defines the <see cref="SelectedItems"/> property. /// </summary> protected static readonly DirectProperty<SelectingItemsControl, IList> SelectedItemsProperty = AvaloniaProperty.RegisterDirect<SelectingItemsControl, IList>( nameof(SelectedItems), o => o.SelectedItems, (o, v) => o.SelectedItems = v); /// <summary> /// Defines the <see cref="SelectionMode"/> property. /// </summary> protected static readonly StyledProperty<SelectionMode> SelectionModeProperty = AvaloniaProperty.Register<SelectingItemsControl, SelectionMode>( nameof(SelectionMode)); /// <summary> /// Event that should be raised by items that implement <see cref="ISelectable"/> to /// notify the parent <see cref="SelectingItemsControl"/> that their selection state /// has changed. /// </summary> public static readonly RoutedEvent<RoutedEventArgs> IsSelectedChangedEvent = RoutedEvent.Register<SelectingItemsControl, RoutedEventArgs>( "IsSelectedChanged", RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="SelectionChanged"/> event. /// </summary> public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent = RoutedEvent.Register<SelectingItemsControl, SelectionChangedEventArgs>( "SelectionChanged", RoutingStrategies.Bubble); private static readonly IList Empty = new object[0]; private int _selectedIndex = -1; private object _selectedItem; private IList _selectedItems; private bool _ignoreContainerSelectionChanged; private bool _syncingSelectedItems; private int _updateCount; private int _updateSelectedIndex; private IList _updateSelectedItems; /// <summary> /// Initializes static members of the <see cref="SelectingItemsControl"/> class. /// </summary> static SelectingItemsControl() { IsSelectedChangedEvent.AddClassHandler<SelectingItemsControl>(x => x.ContainerSelectionChanged); } /// <summary> /// Occurs when the control's selection changes. /// </summary> public event EventHandler<SelectionChangedEventArgs> SelectionChanged { add { AddHandler(SelectionChangedEvent, value); } remove { RemoveHandler(SelectionChangedEvent, value); } } /// <summary> /// Gets or sets a value indicating whether to automatically scroll to newly selected items. /// </summary> public bool AutoScrollToSelectedItem { get { return GetValue(AutoScrollToSelectedItemProperty); } set { SetValue(AutoScrollToSelectedItemProperty, value); } } /// <summary> /// Gets or sets the index of the selected item. /// </summary> public int SelectedIndex { get { return _selectedIndex; } set { if (_updateCount == 0) { SetAndRaise(SelectedIndexProperty, ref _selectedIndex, (int val, ref int backing, Action<Action> notifyWrapper) => { var old = backing; var effective = (val >= 0 && val < Items?.Cast<object>().Count()) ? val : -1; if (old != effective) { backing = effective; notifyWrapper(() => RaisePropertyChanged( SelectedIndexProperty, old, effective, BindingPriority.LocalValue)); SelectedItem = ElementAt(Items, effective); } }, value); } else { _updateSelectedIndex = value; _updateSelectedItems = null; } } } /// <summary> /// Gets or sets the selected item. /// </summary> public object SelectedItem { get { return _selectedItem; } set { if (_updateCount == 0) { SetAndRaise(SelectedItemProperty, ref _selectedItem, (object val, ref object backing, Action<Action> notifyWrapper) => { var old = backing; var index = IndexOf(Items, val); var effective = index != -1 ? val : null; if (!object.Equals(effective, old)) { backing = effective; notifyWrapper(() => RaisePropertyChanged( SelectedItemProperty, old, effective, BindingPriority.LocalValue)); SelectedIndex = index; if (effective != null) { if (SelectedItems.Count != 1 || SelectedItems[0] != effective) { _syncingSelectedItems = true; SelectedItems.Clear(); SelectedItems.Add(effective); _syncingSelectedItems = false; } } else if (SelectedItems.Count > 0) { SelectedItems.Clear(); } } }, value); } else { _updateSelectedItems = new AvaloniaList<object>(value); _updateSelectedIndex = int.MinValue; } } } /// <summary> /// Gets the selected items. /// </summary> protected IList SelectedItems { get { if (_selectedItems == null) { _selectedItems = new AvaloniaList<object>(); SubscribeToSelectedItems(); } return _selectedItems; } set { if (value?.IsFixedSize == true || value?.IsReadOnly == true) { throw new NotSupportedException( "Cannot use a fixed size or read-only collection as SelectedItems."); } UnsubscribeFromSelectedItems(); _selectedItems = value ?? new AvaloniaList<object>(); SubscribeToSelectedItems(); } } /// <summary> /// Gets or sets the selection mode. /// </summary> protected SelectionMode SelectionMode { get { return GetValue(SelectionModeProperty); } set { SetValue(SelectionModeProperty, value); } } /// <summary> /// Gets a value indicating whether <see cref="SelectionMode.AlwaysSelected"/> is set. /// </summary> protected bool AlwaysSelected => (SelectionMode & SelectionMode.AlwaysSelected) != 0; /// <inheritdoc/> public override void BeginInit() { base.BeginInit(); ++_updateCount; _updateSelectedIndex = int.MinValue; } /// <inheritdoc/> public override void EndInit() { base.EndInit(); if (--_updateCount == 0) { UpdateFinished(); } } /// <summary> /// Scrolls the specified item into view. /// </summary> /// <param name="item">The item.</param> public void ScrollIntoView(object item) => Presenter?.ScrollIntoView(item); /// <summary> /// Tries to get the container that was the source of an event. /// </summary> /// <param name="eventSource">The control that raised the event.</param> /// <returns>The container or null if the event did not originate in a container.</returns> protected IControl GetContainerFromEventSource(IInteractive eventSource) { var item = ((IVisual)eventSource).GetSelfAndVisualAncestors() .OfType<IControl>() .FirstOrDefault(x => x.LogicalParent == this && ItemContainerGenerator?.IndexFromContainer(x) != -1); return item; } /// <inheritdoc/> protected override void ItemsChanged(AvaloniaPropertyChangedEventArgs e) { base.ItemsChanged(e); if (_updateCount == 0) { if (SelectedIndex != -1) { SelectedIndex = IndexOf((IEnumerable)e.NewValue, SelectedItem); } else if (AlwaysSelected && Items != null && Items.Cast<object>().Any()) { SelectedIndex = 0; } } } /// <inheritdoc/> protected override void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { base.ItemsCollectionChanged(sender, e); switch (e.Action) { case NotifyCollectionChangedAction.Add: if (AlwaysSelected && SelectedIndex == -1) { SelectedIndex = 0; } break; case NotifyCollectionChangedAction.Remove: case NotifyCollectionChangedAction.Replace: var selectedIndex = SelectedIndex; if (selectedIndex >= e.OldStartingIndex && selectedIndex < e.OldStartingIndex + e.OldItems.Count) { if (!AlwaysSelected) { SelectedIndex = -1; } else { LostSelection(); } } break; case NotifyCollectionChangedAction.Reset: SelectedIndex = IndexOf(e.NewItems, SelectedItem); break; } } /// <inheritdoc/> protected override void OnContainersMaterialized(ItemContainerEventArgs e) { base.OnContainersMaterialized(e); var selectedIndex = SelectedIndex; var selectedContainer = e.Containers .FirstOrDefault(x => (x.ContainerControl as ISelectable)?.IsSelected == true); if (selectedContainer != null) { SelectedIndex = selectedContainer.Index; } else if (selectedIndex >= e.StartingIndex && selectedIndex < e.StartingIndex + e.Containers.Count) { var container = e.Containers[selectedIndex - e.StartingIndex]; if (container.ContainerControl != null) { MarkContainerSelected(container.ContainerControl, true); } } } /// <inheritdoc/> protected override void OnContainersDematerialized(ItemContainerEventArgs e) { base.OnContainersDematerialized(e); var panel = (InputElement)Presenter.Panel; foreach (var container in e.Containers) { if (KeyboardNavigation.GetTabOnceActiveElement(panel) == container.ContainerControl) { KeyboardNavigation.SetTabOnceActiveElement(panel, null); break; } } } protected override void OnContainersRecycled(ItemContainerEventArgs e) { foreach (var i in e.Containers) { if (i.ContainerControl != null && i.Item != null) { MarkContainerSelected( i.ContainerControl, SelectedItems.Contains(i.Item)); } } } /// <inheritdoc/> protected override void OnDataContextBeginUpdate() { base.OnDataContextBeginUpdate(); ++_updateCount; } /// <inheritdoc/> protected override void OnDataContextEndUpdate() { base.OnDataContextEndUpdate(); if (--_updateCount == 0) { UpdateFinished(); } } /// <summary> /// Updates the selection for an item based on user interaction. /// </summary> /// <param name="index">The index of the item.</param> /// <param name="select">Whether the item should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> protected void UpdateSelection( int index, bool select = true, bool rangeModifier = false, bool toggleModifier = false) { if (index != -1) { if (select) { var mode = SelectionMode; var toggle = toggleModifier || (mode & SelectionMode.Toggle) != 0; var multi = (mode & SelectionMode.Multiple) != 0; var range = multi && SelectedIndex != -1 && rangeModifier; if (!toggle && !range) { SelectedIndex = index; } else if (multi && range) { SynchronizeItems( SelectedItems, GetRange(Items, SelectedIndex, index)); } else { var item = ElementAt(Items, index); var i = SelectedItems.IndexOf(item); if (i != -1 && (!AlwaysSelected || SelectedItems.Count > 1)) { SelectedItems.Remove(item); } else { if (multi) { SelectedItems.Add(item); } else { SelectedIndex = index; } } } if (Presenter?.Panel != null) { var container = ItemContainerGenerator.ContainerFromIndex(index); KeyboardNavigation.SetTabOnceActiveElement( (InputElement)Presenter.Panel, container); } } else { LostSelection(); } } } /// <summary> /// Updates the selection for a container based on user interaction. /// </summary> /// <param name="container">The container.</param> /// <param name="select">Whether the container should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> protected void UpdateSelection( IControl container, bool select = true, bool rangeModifier = false, bool toggleModifier = false) { var index = ItemContainerGenerator?.IndexFromContainer(container) ?? -1; if (index != -1) { UpdateSelection(index, select, rangeModifier, toggleModifier); } } /// <summary> /// Updates the selection based on an event that may have originated in a container that /// belongs to the control. /// </summary> /// <param name="eventSource">The control that raised the event.</param> /// <param name="select">Whether the container should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> /// <returns> /// True if the event originated from a container that belongs to the control; otherwise /// false. /// </returns> protected bool UpdateSelectionFromEventSource( IInteractive eventSource, bool select = true, bool rangeModifier = false, bool toggleModifier = false) { var container = GetContainerFromEventSource(eventSource); if (container != null) { UpdateSelection(container, select, rangeModifier, toggleModifier); return true; } return false; } /// <summary> /// Gets a range of items from an IEnumerable. /// </summary> /// <param name="items">The items.</param> /// <param name="first">The index of the first item.</param> /// <param name="last">The index of the last item.</param> /// <returns>The items.</returns> private static IEnumerable<object> GetRange(IEnumerable items, int first, int last) { var list = (items as IList) ?? items.Cast<object>().ToList(); int step = first > last ? -1 : 1; for (int i = first; i != last; i += step) { yield return list[i]; } yield return list[last]; } /// <summary> /// Makes a list of objects equal another. /// </summary> /// <param name="items">The items collection.</param> /// <param name="desired">The desired items.</param> private static void SynchronizeItems(IList items, IEnumerable<object> desired) { int index = 0; foreach (var i in desired) { if (index < items.Count) { if (items[index] != i) { items[index] = i; } } else { items.Add(i); } ++index; } while (index < items.Count) { items.RemoveAt(items.Count - 1); } } /// <summary> /// Called when a container raises the <see cref="IsSelectedChangedEvent"/>. /// </summary> /// <param name="e">The event.</param> private void ContainerSelectionChanged(RoutedEventArgs e) { if (!_ignoreContainerSelectionChanged) { var control = e.Source as IControl; var selectable = e.Source as ISelectable; if (control != null && selectable != null && control.LogicalParent == this && ItemContainerGenerator?.IndexFromContainer(control) != -1) { UpdateSelection(control, selectable.IsSelected); } } if (e.Source != this) { e.Handled = true; } } /// <summary> /// Called when the currently selected item is lost and the selection must be changed /// depending on the <see cref="SelectionMode"/> property. /// </summary> private void LostSelection() { var items = Items?.Cast<object>(); if (items != null && AlwaysSelected) { var index = Math.Min(SelectedIndex, items.Count() - 1); if (index > -1) { SelectedItem = items.ElementAt(index); return; } } SelectedIndex = -1; } /// <summary> /// Sets a container's 'selected' class or <see cref="ISelectable.IsSelected"/>. /// </summary> /// <param name="container">The container.</param> /// <param name="selected">Whether the control is selected</param> /// <returns>The previous selection state.</returns> private bool MarkContainerSelected(IControl container, bool selected) { try { var selectable = container as ISelectable; bool result; _ignoreContainerSelectionChanged = true; if (selectable != null) { result = selectable.IsSelected; selectable.IsSelected = selected; } else { result = container.Classes.Contains(":selected"); ((IPseudoClasses)container.Classes).Set(":selected", selected); } return result; } finally { _ignoreContainerSelectionChanged = false; } } /// <summary> /// Sets an item container's 'selected' class or <see cref="ISelectable.IsSelected"/>. /// </summary> /// <param name="index">The index of the item.</param> /// <param name="selected">Whether the item should be selected or deselected.</param> private void MarkItemSelected(int index, bool selected) { var container = ItemContainerGenerator?.ContainerFromIndex(index); if (container != null) { MarkContainerSelected(container, selected); } } /// <summary> /// Sets an item container's 'selected' class or <see cref="ISelectable.IsSelected"/>. /// </summary> /// <param name="item">The item.</param> /// <param name="selected">Whether the item should be selected or deselected.</param> private void MarkItemSelected(object item, bool selected) { var index = IndexOf(Items, item); if (index != -1) { MarkItemSelected(index, selected); } } /// <summary> /// Called when the <see cref="SelectedItems"/> CollectionChanged event is raised. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> private void SelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { var generator = ItemContainerGenerator; IList added = null; IList removed = null; switch (e.Action) { case NotifyCollectionChangedAction.Add: SelectedItemsAdded(e.NewItems.Cast<object>().ToList()); if (AutoScrollToSelectedItem) { ScrollIntoView(e.NewItems[0]); } added = e.NewItems; break; case NotifyCollectionChangedAction.Remove: if (SelectedItems.Count == 0) { if (!_syncingSelectedItems) { SelectedIndex = -1; } } else { foreach (var item in e.OldItems) { MarkItemSelected(item, false); } } removed = e.OldItems; break; case NotifyCollectionChangedAction.Reset: if (generator != null) { removed = new List<object>(); foreach (var item in generator.Containers) { if (item?.ContainerControl != null) { if (MarkContainerSelected(item.ContainerControl, false)) { removed.Add(item.Item); } } } } if (SelectedItems.Count > 0) { _selectedItem = null; SelectedItemsAdded(SelectedItems); added = SelectedItems; } else if (!_syncingSelectedItems) { SelectedIndex = -1; } break; case NotifyCollectionChangedAction.Replace: foreach (var item in e.OldItems) { MarkItemSelected(item, false); } foreach (var item in e.NewItems) { MarkItemSelected(item, true); } if (SelectedItem != SelectedItems[0] && !_syncingSelectedItems) { var oldItem = SelectedItem; var oldIndex = SelectedIndex; var item = SelectedItems[0]; var index = IndexOf(Items, item); _selectedIndex = index; _selectedItem = item; RaisePropertyChanged(SelectedIndexProperty, oldIndex, index, BindingPriority.LocalValue); RaisePropertyChanged(SelectedItemProperty, oldItem, item, BindingPriority.LocalValue); } added = e.OldItems; removed = e.NewItems; break; } if (added?.Count > 0 || removed?.Count > 0) { var changed = new SelectionChangedEventArgs( SelectionChangedEvent, added ?? Empty, removed ?? Empty); RaiseEvent(changed); } } /// <summary> /// Called when items are added to the <see cref="SelectedItems"/> collection. /// </summary> /// <param name="items">The added items.</param> private void SelectedItemsAdded(IList items) { if (items.Count > 0) { foreach (var item in items) { MarkItemSelected(item, true); } if (SelectedItem == null && !_syncingSelectedItems) { var index = IndexOf(Items, items[0]); if (index != -1) { _selectedItem = items[0]; _selectedIndex = index; RaisePropertyChanged(SelectedIndexProperty, -1, index, BindingPriority.LocalValue); RaisePropertyChanged(SelectedItemProperty, null, items[0], BindingPriority.LocalValue); } } } } /// <summary> /// Subscribes to the <see cref="SelectedItems"/> CollectionChanged event, if any. /// </summary> private void SubscribeToSelectedItems() { var incc = _selectedItems as INotifyCollectionChanged; if (incc != null) { incc.CollectionChanged += SelectedItemsCollectionChanged; } SelectedItemsCollectionChanged( _selectedItems, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } /// <summary> /// Unsubscribes from the <see cref="SelectedItems"/> CollectionChanged event, if any. /// </summary> private void UnsubscribeFromSelectedItems() { var incc = _selectedItems as INotifyCollectionChanged; if (incc != null) { incc.CollectionChanged -= SelectedItemsCollectionChanged; } } private void UpdateFinished() { if (_updateSelectedIndex != int.MinValue) { SelectedIndex = _updateSelectedIndex; } else if (_updateSelectedItems != null) { SelectedItems = _updateSelectedItems; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UserDiagnosticProviderEngine { public class DiagnosticAnalyzerDriverTests { [Fact] public async Task DiagnosticAnalyzerDriverAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers or named types with primary constructors. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); symbolKindsWithNoCodeBlocks.Add(SymbolKind.NamedType); var syntaxKindsMissing = new HashSet<SyntaxKind>(); // AllInOneCSharpCode has no deconstruction or declaration expression syntaxKindsMissing.Add(SyntaxKind.SingleVariableDesignation); syntaxKindsMissing.Add(SyntaxKind.ParenthesizedVariableDesignation); syntaxKindsMissing.Add(SyntaxKind.ForEachVariableStatement); syntaxKindsMissing.Add(SyntaxKind.DeclarationExpression); syntaxKindsMissing.Add(SyntaxKind.DiscardDesignation); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); AccessSupportedDiagnostics(analyzer); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length)); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(syntaxKindsMissing); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks, true); } } [Fact, WorkItem(908658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908658")] public async Task DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock() { var methodNames = new string[] { "Initialize", "AnalyzeCodeBlock" }; var source = @" [System.Obsolete] class C { int P { get; set; } delegate void A(); delegate string F(); } "; var ideEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineAnalyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); foreach (var method in methodNames) { Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } var compilerEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { compilerEngineAnalyzer }); foreach (var method in methodNames) { Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } } [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public async Task DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var source = TestResource.AllInOneCSharpCode; using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); await ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(async analyzer => await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length), logAnalyzerExceptionAsDiagnostics: true)); } } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_1() { var analyzer = new ThrowingDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); AccessSupportedDiagnostics(analyzer); } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_2() { var analyzer = new ThrowingDoNotCatchDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); var exceptions = new List<Exception>(); try { AccessSupportedDiagnostics(analyzer); } catch (Exception e) { exceptions.Add(e); } Assert.True(exceptions.Count == 0); } [Fact] public async Task AnalyzerOptionsArePassedToAllAnalyzers() { using (var workspace = await TestWorkspace.CreateCSharpAsync(TestResource.AllInOneCSharpCode, TestOptions.Regular)) { var currentProject = workspace.CurrentSolution.Projects.Single(); var additionalDocId = DocumentId.CreateNewId(currentProject.Id); var newSln = workspace.CurrentSolution.AddAdditionalDocument(additionalDocId, "add.config", SourceText.From("random text")); currentProject = newSln.Projects.Single(); var additionalDocument = currentProject.GetAdditionalDocument(additionalDocId); AdditionalText additionalStream = new AdditionalTextDocument(additionalDocument.State); AnalyzerOptions options = new AnalyzerOptions(ImmutableArray.Create(additionalStream)); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(expectedOptions: options); var sourceDocument = currentProject.Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, sourceDocument, new Text.TextSpan(0, sourceDocument.GetTextAsync().Result.Length)); analyzer.VerifyAnalyzerOptions(); } } private void AccessSupportedDiagnostics(DiagnosticAnalyzer analyzer) { var diagnosticService = new TestDiagnosticAnalyzerService(LanguageNames.CSharp, analyzer); diagnosticService.GetDiagnosticDescriptors(projectOpt: null); } private class ThrowingDoNotCatchDiagnosticAnalyzer<TLanguageKindEnum> : ThrowingDiagnosticAnalyzer<TLanguageKindEnum>, IBuiltInAnalyzer where TLanguageKindEnum : struct { public bool OpenFileOnly(Workspace workspace) => false; public DiagnosticAnalyzerCategory GetAnalyzerCategory() { return DiagnosticAnalyzerCategory.SyntaxAnalysis | DiagnosticAnalyzerCategory.SemanticDocumentAnalysis | DiagnosticAnalyzerCategory.ProjectAnalysis; } } [Fact] public async Task AnalyzerCreatedAtCompilationLevelNeedNotBeCompilationAnalyzer() { var source = @"x"; var analyzer = new CompilationAnalyzerWithSyntaxTreeAnalyzer(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == "SyntaxDiagnostic"); Assert.Equal(1, diagnosticsFromAnalyzer.Count()); } } private class CompilationAnalyzerWithSyntaxTreeAnalyzer : DiagnosticAnalyzer { private const string ID = "SyntaxDiagnostic"; private static readonly DiagnosticDescriptor s_syntaxDiagnosticDescriptor = new DiagnosticDescriptor(ID, title: "Syntax", messageFormat: "Syntax", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_syntaxDiagnosticDescriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxTreeAction(new SyntaxTreeAnalyzer().AnalyzeSyntaxTree); } private class SyntaxTreeAnalyzer { public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(s_syntaxDiagnosticDescriptor, context.Tree.GetRoot().GetFirstToken().GetLocation())); } } } [Fact] public async Task CodeBlockAnalyzersOnlyAnalyzeExecutableCode() { var source = @" using System; class C { void F(int x = 0) { Console.WriteLine(0); } } "; var analyzer = new CodeBlockAnalyzerFactory(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(2, diagnosticsFromAnalyzer.Count()); } source = @" using System; class C { void F(int x = 0, int y = 1, int z = 2) { Console.WriteLine(0); } } "; using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer }); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(4, diagnosticsFromAnalyzer.Count()); } } private class CodeBlockAnalyzerFactory : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(CreateAnalyzerWithinCodeBlock); } public void CreateAnalyzerWithinCodeBlock(CodeBlockStartAnalysisContext<SyntaxKind> context) { var blockAnalyzer = new CodeBlockAnalyzer(); context.RegisterCodeBlockEndAction(blockAnalyzer.AnalyzeCodeBlock); context.RegisterSyntaxNodeAction(blockAnalyzer.AnalyzeNode, blockAnalyzer.SyntaxKindsOfInterest.ToArray()); } private class CodeBlockAnalyzer { public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest { get { return ImmutableArray.Create(SyntaxKind.MethodDeclaration, SyntaxKind.ExpressionStatement, SyntaxKind.EqualsValueClause); } } public void AnalyzeCodeBlock(CodeBlockAnalysisContext context) { } public void AnalyzeNode(SyntaxNodeAnalysisContext context) { // Ensure only executable nodes are analyzed. Assert.NotEqual(SyntaxKind.MethodDeclaration, context.Node.Kind()); context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation())); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** Class: EqualityComparer<T> ** ===========================================================*/ using System; using System.Collections; namespace System.Collections.Generic { public abstract class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T> { protected EqualityComparer() { } public static EqualityComparer<T> Default { get { if (_default == null) { object comparer; // NUTC compiler is able to static evalulate the conditions and only put the necessary branches in finally binary code, // even casting to EqualityComparer<T> can be removed. // For example: for Byte, the code generated is // if (_default == null) _default = new EqualityComparerForByte(); return _default; // For classes, due to generic sharing, the code generated is: // if (_default == null) { if (handle == typeof(string).RuntimeTypeHandle) comparer = new EqualityComparerForString(); else comparer = new LastResortEqalityComparer<T>; ... if (typeof(T) == typeof(SByte)) comparer = new EqualityComparerForSByte(); else if (typeof(T) == typeof(Byte)) comparer = new EqualityComparerForByte(); else if (typeof(T) == typeof(Int16)) comparer = new EqualityComparerForInt16(); else if (typeof(T) == typeof(UInt16)) comparer = new EqualityComparerForUInt16(); else if (typeof(T) == typeof(Int32)) comparer = new EqualityComparerForInt32(); else if (typeof(T) == typeof(UInt32)) comparer = new EqualityComparerForUInt32(); else if (typeof(T) == typeof(Int64)) comparer = new EqualityComparerForInt64(); else if (typeof(T) == typeof(UInt64)) comparer = new EqualityComparerForUInt64(); else if (typeof(T) == typeof(IntPtr)) comparer = new EqualityComparerForIntPtr(); else if (typeof(T) == typeof(UIntPtr)) comparer = new EqualityComparerForUIntPtr(); else if (typeof(T) == typeof(Single)) comparer = new EqualityComparerForSingle(); else if (typeof(T) == typeof(Double)) comparer = new EqualityComparerForDouble(); else if (typeof(T) == typeof(Decimal)) comparer = new EqualityComparerForDecimal(); else if (typeof(T) == typeof(String)) comparer = new EqualityComparerForString(); else comparer = new LastResortEqualityComparer<T>(); _default = (EqualityComparer<T>)comparer; } return _default; } } private static volatile EqualityComparer<T> _default; public abstract bool Equals(T x, T y); public abstract int GetHashCode(T obj); int IEqualityComparer.GetHashCode(object obj) { if (obj == null) return 0; if (obj is T) return GetHashCode((T)obj); throw new ArgumentException(SR.Argument_InvalidArgumentForComparison, nameof(obj)); } bool IEqualityComparer.Equals(object x, object y) { if (x == y) return true; if (x == null || y == null) return false; if ((x is T) && (y is T)) return Equals((T)x, (T)y); throw new ArgumentException(SR.Argument_InvalidArgumentForComparison); } } // // ProjectN compatiblity notes: // // Unlike the full desktop, we make no attempt to use the IEquatable<T> interface on T. Because we can't generate // code at runtime, we derive no performance benefit from using the type-specific Equals(). We can't even // perform the check for IEquatable<> at the time the type-specific constructor is created (due to the removable of Type.IsAssignableFrom). // We would thus be incurring an interface cast check on each call to Equals() for no performance gain. // // This should not cause a compat problem unless some type implements an IEquatable.Equals() that is semantically // incompatible with Object.Equals(). That goes specifically against the documented guidelines (and would in any case, // break any hashcode-dependent collection.) // internal sealed class LastResortEqualityComparer<T> : EqualityComparer<T> { public LastResortEqualityComparer() { } public sealed override bool Equals(T x, T y) { if (x == null) return y == null; if (y == null) return false; return x.Equals(y); } public sealed override int GetHashCode(T obj) { if (obj == null) return 0; return obj.GetHashCode(); } } internal sealed class EqualityComparerForSByte : EqualityComparer<SByte> { public override bool Equals(SByte x, SByte y) { return x == y; } public override int GetHashCode(SByte x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForByte : EqualityComparer<Byte> { public override bool Equals(Byte x, Byte y) { return x == y; } public override int GetHashCode(Byte x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForInt16 : EqualityComparer<Int16> { public override bool Equals(Int16 x, Int16 y) { return x == y; } public override int GetHashCode(Int16 x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForUInt16 : EqualityComparer<UInt16> { public override bool Equals(UInt16 x, UInt16 y) { return x == y; } public override int GetHashCode(UInt16 x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForInt32 : EqualityComparer<Int32> { public override bool Equals(Int32 x, Int32 y) { return x == y; } public override int GetHashCode(Int32 x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForUInt32 : EqualityComparer<UInt32> { public override bool Equals(UInt32 x, UInt32 y) { return x == y; } public override int GetHashCode(UInt32 x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForInt64 : EqualityComparer<Int64> { public override bool Equals(Int64 x, Int64 y) { return x == y; } public override int GetHashCode(Int64 x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForUInt64 : EqualityComparer<UInt64> { public override bool Equals(UInt64 x, UInt64 y) { return x == y; } public override int GetHashCode(UInt64 x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForIntPtr : EqualityComparer<IntPtr> { public override bool Equals(IntPtr x, IntPtr y) { return x == y; } public override int GetHashCode(IntPtr x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForUIntPtr : EqualityComparer<UIntPtr> { public override bool Equals(UIntPtr x, UIntPtr y) { return x == y; } public override int GetHashCode(UIntPtr x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForSingle : EqualityComparer<Single> { public override bool Equals(Single x, Single y) { // == has the wrong semantic for NaN for Single return x.Equals(y); } public override int GetHashCode(Single x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForDouble : EqualityComparer<Double> { public override bool Equals(Double x, Double y) { // == has the wrong semantic for NaN for Double return x.Equals(y); } public override int GetHashCode(Double x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForDecimal : EqualityComparer<Decimal> { public override bool Equals(Decimal x, Decimal y) { return x == y; } public override int GetHashCode(Decimal x) { return x.GetHashCode(); } } internal sealed class EqualityComparerForString : EqualityComparer<String> { public override bool Equals(String x, String y) { return x == y; } public override int GetHashCode(String x) { if (x == null) return 0; return x.GetHashCode(); } } }
using UnityEngine; using System.Collections; public class Map : MonoBehaviour { // static int kMAX_LENGTH = 128; // static int kMIN_LENGTH = 32; static int kTILE_SIZE = 32; static float kTILE_SIZE_WORLD = 1.6f; public float actorZOffset = 1.0f; public float itemZOffset = 0.9f; public Step[] steps; public GameManager m_gm; public tk2dTiledSprite stepTile; [SerializeField] private Vector3 m_floorGimicOffset = new Vector3(-0.1737356f,0.1478726f,0.0f); [SerializeField] private GameObject m_enemyFab; [SerializeField] private GameObject m_itemFab; private EnemyDatabase m_enemyDB; private ItemDatabase m_itemDB; private FloorGimicDatabase m_fgDB; private GameObject m_enemyParent; private GameObject m_itemParent; private GameObject m_eventParent; private GameObject m_gimicParent; void Awake () { m_enemyDB = GetComponent<EnemyDatabase>() as EnemyDatabase; m_itemDB = GetComponent<ItemDatabase>() as ItemDatabase; m_fgDB = GetComponent<FloorGimicDatabase>() as FloorGimicDatabase; } /* * Generates given level; * called from gamemanager */ public void GenerateMap(string questName) { /* * Should load some data for each currentSteps for generation */ // int length = Random.Range (kMIN_LENGTH, kMAX_LENGTH); int length = 1000; steps = new Step[length]; for(int i = 0; i< length; ++i) { steps[i] = ScriptableObject.CreateInstance<Step>(); steps[i].index = i; steps[i].map = this; } stepTile.dimensions = new Vector2(kTILE_SIZE * length, kTILE_SIZE); steps[0].SetActor(m_gm.currentPlayer); m_enemyParent = new GameObject("enemies"); m_itemParent = new GameObject("items"); m_eventParent = new GameObject("events"); m_gimicParent = new GameObject("floorgimic"); m_enemyParent.transform.parent = transform; m_itemParent.transform.parent = transform; m_eventParent.transform.parent = transform; m_gimicParent.transform.parent = transform; _GenerateEnemy(questName); _GenerateItem(questName); _GenerateFloorGimic(questName); } /* * generate enemy */ private void _GenerateEnemy(string questName) { int length = steps.Length; int enemyPopGap = Random.Range (5, 10); int nEnemies = ((int) length / enemyPopGap ) + 1; int initialNoEnemyZone = m_enemyDB.GetMinimumEnemyStep(questName); for(int i = 0; i < nEnemies; ++i) { int popStep = enemyPopGap * i + Random.Range (-3, 3); popStep = Mathf.Clamp (popStep, 0, length-1); while (steps[popStep].actorOnStep != null && popStep < length) { ++popStep; } if( popStep >= length ) { Debug.Log ("[EnemyGen] max step reached. finishing enemy pop.. "); break; } if( popStep < initialNoEnemyZone ) { continue; } //Debug.Log ("[Enemy] pop at "+ popStep); GameObject eo = GameObject.Instantiate(m_enemyFab, Vector3.zero, Quaternion.identity) as GameObject; EnemyActor ea = eo.GetComponent<EnemyActor>(); ea.Initialize(questName, popStep, m_enemyDB, m_itemDB); steps[popStep].SetActor(ea); eo.transform.parent = m_enemyParent.transform; } } /* * generate item */ private void _GenerateItem(string questName) { int length = steps.Length; int itemPopGap = Random.Range (3, 15); int nItems = ((int) length / itemPopGap ) + 1; int initialNoItemZone = m_itemDB.GetMinimumItemStep(questName); for(int i = 0; i < nItems; ++i) { int popStep = itemPopGap * i + Random.Range (-2, 2); popStep = Mathf.Clamp (popStep, 0, length-1); while (steps[popStep].itemOnStep != null && popStep < length) { ++popStep; } if( popStep >= length ) { Debug.Log ("[ItemGen] max step reached. finishing item pop.. "); break; } if( popStep < initialNoItemZone ) { continue; } //Debug.Log ("[Enemy] pop at "+ popStep); GameObject obj = GameObject.Instantiate(m_itemFab, Vector3.zero, Quaternion.identity) as GameObject; Item item = obj.GetComponent<Item>(); item.Initialize(questName, popStep, m_itemDB); steps[popStep].SetItem(item); obj.transform.parent = m_itemParent.transform; } } /* * generate item */ private void _GenerateFloorGimic(string questName) { int length = steps.Length; int fgPopGap = Random.Range (3, 20); int nGimics = ((int) length / fgPopGap ) + 1; int initialNoGimicZone = m_fgDB.GetMinimumFloorGimicStep(questName); for(int i = 0; i < nGimics; ++i) { int popStep = fgPopGap * i + Random.Range (-2, 2); popStep = Mathf.Clamp (popStep, 0, length-1); while (steps[popStep].floorGimicOnStep != null && popStep < length) { ++popStep; } if( popStep >= length ) { Debug.Log ("[FgGen] max step reached. finishing item pop.. "); break; } if( popStep < initialNoGimicZone ) { continue; } FloorGimic fg = m_fgDB.CreateGimic(questName, popStep); steps[popStep].SetFloorGimic(fg); fg.gameObject.transform.parent = m_gimicParent.transform; } } public void GenerateItemDynamic(int itemid, int step) { if( steps[step].itemOnStep != null ) { Destroy(steps[step].itemOnStep.gameObject); } GameObject obj = GameObject.Instantiate(m_itemFab, Vector3.zero, Quaternion.identity) as GameObject; Item item = obj.GetComponent<Item>(); item.Initialize(itemid, step, m_itemDB); steps[step].SetItem(item); obj.transform.parent = m_itemParent.transform; } public void GenerateEnemyDynamic(int enemyid, int step) { GameObject eo = GameObject.Instantiate(m_enemyFab, Vector3.zero, Quaternion.identity) as GameObject; EnemyActor ea = eo.GetComponent<EnemyActor>(); ea.Initialize(enemyid, m_enemyDB, m_itemDB); steps[step].SetActor(ea); eo.transform.parent = m_enemyParent.transform; } public void GenerateFloorGimicDynamic(int fgid, int step) { FloorGimic fg = m_fgDB.CreateGimic(fgid); steps[step].SetFloorGimic(fg); fg.gameObject.transform.parent = m_gimicParent.transform; } public Item CreateItem(ItemEntity e) { GameObject obj = GameObject.Instantiate(m_itemFab, Vector3.zero, Quaternion.identity) as GameObject; Item item = obj.GetComponent<Item>(); item.Initialize(e); obj.transform.parent = m_itemParent.transform; return item; } public int ClampIndexToMapSize(int stepIndex) { return Mathf.Clamp (stepIndex, 0, steps.Length); } public Vector3 GetActorStepPosition(int index) { Vector3 pos = transform.position; return new Vector3(pos.x - kTILE_SIZE_WORLD * index, pos.y, pos.z - actorZOffset); } public Vector3 GetItemStepPosition(int index) { Vector3 pos = transform.position; return new Vector3(pos.x - kTILE_SIZE_WORLD * index, pos.y, pos.z - itemZOffset); } public Vector3 GetFloorGimicStepPosition(int index) { Vector3 pos = transform.position; return new Vector3(pos.x - kTILE_SIZE_WORLD * index + m_floorGimicOffset.x, pos.y + m_floorGimicOffset.y, pos.z + m_floorGimicOffset.z); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// PaymentsConfigurationWireTransfer /// </summary> [DataContract] public partial class PaymentsConfigurationWireTransfer : IEquatable<PaymentsConfigurationWireTransfer>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PaymentsConfigurationWireTransfer" /> class. /// </summary> /// <param name="acceptWireTransfer">Master flag indicating this merchant accepts wire transfers.</param> /// <param name="accountNumber">account_number.</param> /// <param name="accountingCode">Optional Quickbooks accounting code.</param> /// <param name="bankAddress">Bank address.</param> /// <param name="depositToAccount">Optional Quickbooks deposit to account.</param> /// <param name="intermediateRoutingNumber">Intermediate routing number.</param> /// <param name="restrictions">restrictions.</param> /// <param name="routingNumber">Routing number.</param> /// <param name="surchargeAccountingCode">If a surcharge is present and this merchant is integrated with Quickbooks, this is the accounting code for the surcharge amount.</param> /// <param name="surchargeFee">surcharge_fee.</param> /// <param name="surchargePercentage">surcharge_percentage.</param> public PaymentsConfigurationWireTransfer(bool? acceptWireTransfer = default(bool?), string accountNumber = default(string), string accountingCode = default(string), string bankAddress = default(string), string depositToAccount = default(string), string intermediateRoutingNumber = default(string), PaymentsConfigurationRestrictions restrictions = default(PaymentsConfigurationRestrictions), string routingNumber = default(string), string surchargeAccountingCode = default(string), decimal? surchargeFee = default(decimal?), decimal? surchargePercentage = default(decimal?)) { this.AcceptWireTransfer = acceptWireTransfer; this.AccountNumber = accountNumber; this.AccountingCode = accountingCode; this.BankAddress = bankAddress; this.DepositToAccount = depositToAccount; this.IntermediateRoutingNumber = intermediateRoutingNumber; this.Restrictions = restrictions; this.RoutingNumber = routingNumber; this.SurchargeAccountingCode = surchargeAccountingCode; this.SurchargeFee = surchargeFee; this.SurchargePercentage = surchargePercentage; } /// <summary> /// Master flag indicating this merchant accepts wire transfers /// </summary> /// <value>Master flag indicating this merchant accepts wire transfers</value> [DataMember(Name="accept_wire_transfer", EmitDefaultValue=false)] public bool? AcceptWireTransfer { get; set; } /// <summary> /// account_number /// </summary> /// <value>account_number</value> [DataMember(Name="account_number", EmitDefaultValue=false)] public string AccountNumber { get; set; } /// <summary> /// Optional Quickbooks accounting code /// </summary> /// <value>Optional Quickbooks accounting code</value> [DataMember(Name="accounting_code", EmitDefaultValue=false)] public string AccountingCode { get; set; } /// <summary> /// Bank address /// </summary> /// <value>Bank address</value> [DataMember(Name="bank_address", EmitDefaultValue=false)] public string BankAddress { get; set; } /// <summary> /// Optional Quickbooks deposit to account /// </summary> /// <value>Optional Quickbooks deposit to account</value> [DataMember(Name="deposit_to_account", EmitDefaultValue=false)] public string DepositToAccount { get; set; } /// <summary> /// Intermediate routing number /// </summary> /// <value>Intermediate routing number</value> [DataMember(Name="intermediate_routing_number", EmitDefaultValue=false)] public string IntermediateRoutingNumber { get; set; } /// <summary> /// Gets or Sets Restrictions /// </summary> [DataMember(Name="restrictions", EmitDefaultValue=false)] public PaymentsConfigurationRestrictions Restrictions { get; set; } /// <summary> /// Routing number /// </summary> /// <value>Routing number</value> [DataMember(Name="routing_number", EmitDefaultValue=false)] public string RoutingNumber { get; set; } /// <summary> /// If a surcharge is present and this merchant is integrated with Quickbooks, this is the accounting code for the surcharge amount /// </summary> /// <value>If a surcharge is present and this merchant is integrated with Quickbooks, this is the accounting code for the surcharge amount</value> [DataMember(Name="surcharge_accounting_code", EmitDefaultValue=false)] public string SurchargeAccountingCode { get; set; } /// <summary> /// surcharge_fee /// </summary> /// <value>surcharge_fee</value> [DataMember(Name="surcharge_fee", EmitDefaultValue=false)] public decimal? SurchargeFee { get; set; } /// <summary> /// surcharge_percentage /// </summary> /// <value>surcharge_percentage</value> [DataMember(Name="surcharge_percentage", EmitDefaultValue=false)] public decimal? SurchargePercentage { 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 PaymentsConfigurationWireTransfer {\n"); sb.Append(" AcceptWireTransfer: ").Append(AcceptWireTransfer).Append("\n"); sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); sb.Append(" AccountingCode: ").Append(AccountingCode).Append("\n"); sb.Append(" BankAddress: ").Append(BankAddress).Append("\n"); sb.Append(" DepositToAccount: ").Append(DepositToAccount).Append("\n"); sb.Append(" IntermediateRoutingNumber: ").Append(IntermediateRoutingNumber).Append("\n"); sb.Append(" Restrictions: ").Append(Restrictions).Append("\n"); sb.Append(" RoutingNumber: ").Append(RoutingNumber).Append("\n"); sb.Append(" SurchargeAccountingCode: ").Append(SurchargeAccountingCode).Append("\n"); sb.Append(" SurchargeFee: ").Append(SurchargeFee).Append("\n"); sb.Append(" SurchargePercentage: ").Append(SurchargePercentage).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 virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PaymentsConfigurationWireTransfer); } /// <summary> /// Returns true if PaymentsConfigurationWireTransfer instances are equal /// </summary> /// <param name="input">Instance of PaymentsConfigurationWireTransfer to be compared</param> /// <returns>Boolean</returns> public bool Equals(PaymentsConfigurationWireTransfer input) { if (input == null) return false; return ( this.AcceptWireTransfer == input.AcceptWireTransfer || (this.AcceptWireTransfer != null && this.AcceptWireTransfer.Equals(input.AcceptWireTransfer)) ) && ( this.AccountNumber == input.AccountNumber || (this.AccountNumber != null && this.AccountNumber.Equals(input.AccountNumber)) ) && ( this.AccountingCode == input.AccountingCode || (this.AccountingCode != null && this.AccountingCode.Equals(input.AccountingCode)) ) && ( this.BankAddress == input.BankAddress || (this.BankAddress != null && this.BankAddress.Equals(input.BankAddress)) ) && ( this.DepositToAccount == input.DepositToAccount || (this.DepositToAccount != null && this.DepositToAccount.Equals(input.DepositToAccount)) ) && ( this.IntermediateRoutingNumber == input.IntermediateRoutingNumber || (this.IntermediateRoutingNumber != null && this.IntermediateRoutingNumber.Equals(input.IntermediateRoutingNumber)) ) && ( this.Restrictions == input.Restrictions || (this.Restrictions != null && this.Restrictions.Equals(input.Restrictions)) ) && ( this.RoutingNumber == input.RoutingNumber || (this.RoutingNumber != null && this.RoutingNumber.Equals(input.RoutingNumber)) ) && ( this.SurchargeAccountingCode == input.SurchargeAccountingCode || (this.SurchargeAccountingCode != null && this.SurchargeAccountingCode.Equals(input.SurchargeAccountingCode)) ) && ( this.SurchargeFee == input.SurchargeFee || (this.SurchargeFee != null && this.SurchargeFee.Equals(input.SurchargeFee)) ) && ( this.SurchargePercentage == input.SurchargePercentage || (this.SurchargePercentage != null && this.SurchargePercentage.Equals(input.SurchargePercentage)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.AcceptWireTransfer != null) hashCode = hashCode * 59 + this.AcceptWireTransfer.GetHashCode(); if (this.AccountNumber != null) hashCode = hashCode * 59 + this.AccountNumber.GetHashCode(); if (this.AccountingCode != null) hashCode = hashCode * 59 + this.AccountingCode.GetHashCode(); if (this.BankAddress != null) hashCode = hashCode * 59 + this.BankAddress.GetHashCode(); if (this.DepositToAccount != null) hashCode = hashCode * 59 + this.DepositToAccount.GetHashCode(); if (this.IntermediateRoutingNumber != null) hashCode = hashCode * 59 + this.IntermediateRoutingNumber.GetHashCode(); if (this.Restrictions != null) hashCode = hashCode * 59 + this.Restrictions.GetHashCode(); if (this.RoutingNumber != null) hashCode = hashCode * 59 + this.RoutingNumber.GetHashCode(); if (this.SurchargeAccountingCode != null) hashCode = hashCode * 59 + this.SurchargeAccountingCode.GetHashCode(); if (this.SurchargeFee != null) hashCode = hashCode * 59 + this.SurchargeFee.GetHashCode(); if (this.SurchargePercentage != null) hashCode = hashCode * 59 + this.SurchargePercentage.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Audio; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Rulesets.Edit; using osuTK; namespace osu.Game.Screens.Edit.Compose.Components.Timeline { [Cached(typeof(IPositionSnapProvider))] [Cached] public class Timeline : ZoomableScrollContainer, IPositionSnapProvider { private readonly Drawable userContent; public readonly Bindable<bool> WaveformVisible = new Bindable<bool>(); public readonly Bindable<bool> ControlPointsVisible = new Bindable<bool>(); public readonly Bindable<bool> TicksVisible = new Bindable<bool>(); public readonly IBindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>(); [Resolved] private EditorClock editorClock { get; set; } /// <summary> /// The timeline's scroll position in the last frame. /// </summary> private float lastScrollPosition; /// <summary> /// The track time in the last frame. /// </summary> private double lastTrackTime; /// <summary> /// Whether the user is currently dragging the timeline. /// </summary> private bool handlingDragInput; /// <summary> /// Whether the track was playing before a user drag event. /// </summary> private bool trackWasPlaying; private Track track; private const float timeline_height = 72; private const float timeline_expanded_height = 156; public Timeline(Drawable userContent) { this.userContent = userContent; RelativeSizeAxes = Axes.X; Height = timeline_height; ZoomDuration = 200; ZoomEasing = Easing.OutQuint; ScrollbarVisible = false; } private WaveformGraph waveform; private TimelineTickDisplay ticks; private TimelineControlPointDisplay controlPoints; private Container mainContent; private Bindable<float> waveformOpacity; [BackgroundDependencyLoader] private void load(IBindable<WorkingBeatmap> beatmap, OsuColour colours, OsuConfigManager config) { CentreMarker centreMarker; // We don't want the centre marker to scroll AddInternal(centreMarker = new CentreMarker()); AddRange(new Drawable[] { controlPoints = new TimelineControlPointDisplay { RelativeSizeAxes = Axes.X, Height = timeline_expanded_height, }, mainContent = new Container { RelativeSizeAxes = Axes.X, Height = timeline_height, Depth = float.MaxValue, Children = new[] { waveform = new WaveformGraph { RelativeSizeAxes = Axes.Both, BaseColour = colours.Blue.Opacity(0.2f), LowColour = colours.BlueLighter, MidColour = colours.BlueDark, HighColour = colours.BlueDarker, }, centreMarker.CreateProxy(), ticks = new TimelineTickDisplay(), new Box { Name = "zero marker", RelativeSizeAxes = Axes.Y, Width = 2, Origin = Anchor.TopCentre, Colour = colours.YellowDarker, }, userContent, } }, }); waveformOpacity = config.GetBindable<float>(OsuSetting.EditorWaveformOpacity); Beatmap.BindTo(beatmap); Beatmap.BindValueChanged(b => { waveform.Waveform = b.NewValue.Waveform; track = b.NewValue.Track; // todo: i don't think this is safe, the track may not be loaded yet. if (track.Length > 0) { MaxZoom = getZoomLevelForVisibleMilliseconds(500); MinZoom = getZoomLevelForVisibleMilliseconds(10000); Zoom = getZoomLevelForVisibleMilliseconds(2000); } }, true); } protected override void LoadComplete() { base.LoadComplete(); waveformOpacity.BindValueChanged(_ => updateWaveformOpacity(), true); WaveformVisible.ValueChanged += _ => updateWaveformOpacity(); TicksVisible.ValueChanged += visible => ticks.FadeTo(visible.NewValue ? 1 : 0, 200, Easing.OutQuint); ControlPointsVisible.BindValueChanged(visible => { if (visible.NewValue) { this.ResizeHeightTo(timeline_expanded_height, 200, Easing.OutQuint); mainContent.MoveToY(36, 200, Easing.OutQuint); // delay the fade in else masking looks weird. controlPoints.Delay(180).FadeIn(400, Easing.OutQuint); } else { controlPoints.FadeOut(200, Easing.OutQuint); // likewise, delay the resize until the fade is complete. this.Delay(180).ResizeHeightTo(timeline_height, 200, Easing.OutQuint); mainContent.Delay(180).MoveToY(0, 200, Easing.OutQuint); } }, true); } private void updateWaveformOpacity() => waveform.FadeTo(WaveformVisible.Value ? waveformOpacity.Value : 0, 200, Easing.OutQuint); private float getZoomLevelForVisibleMilliseconds(double milliseconds) => Math.Max(1, (float)(track.Length / milliseconds)); protected override void Update() { base.Update(); // The extrema of track time should be positioned at the centre of the container when scrolled to the start or end Content.Margin = new MarginPadding { Horizontal = DrawWidth / 2 }; // This needs to happen after transforms are updated, but before the scroll position is updated in base.UpdateAfterChildren if (editorClock.IsRunning) scrollToTrackTime(); } protected override bool OnScroll(ScrollEvent e) { // if this is not a precision scroll event, let the editor handle the seek itself (for snapping support) if (!e.AltPressed && !e.IsPrecise) return false; return base.OnScroll(e); } protected override void UpdateAfterChildren() { base.UpdateAfterChildren(); if (handlingDragInput) seekTrackToCurrent(); else if (!editorClock.IsRunning) { // The track isn't running. There are three cases we have to be wary of: // 1) The user flick-drags on this timeline and we are applying an interpolated seek on the clock, until interrupted by 2 or 3. // 2) The user changes the track time through some other means (scrolling in the editor or overview timeline; clicking a hitobject etc.). We want the timeline to track the clock's time. // 3) An ongoing seek transform is running from an external seek. We want the timeline to track the clock's time. // The simplest way to cover the first two cases is by checking whether the scroll position has changed and the audio hasn't been changed externally // Checking IsSeeking covers the third case, where the transform may not have been applied yet. if (Current != lastScrollPosition && editorClock.CurrentTime == lastTrackTime && !editorClock.IsSeeking) seekTrackToCurrent(); else scrollToTrackTime(); } lastScrollPosition = Current; lastTrackTime = editorClock.CurrentTime; } private void seekTrackToCurrent() { if (!track.IsLoaded) return; double target = Current / Content.DrawWidth * track.Length; editorClock.Seek(Math.Min(track.Length, target)); } private void scrollToTrackTime() { if (!track.IsLoaded || track.Length == 0) return; // covers the case where the user starts playback after a drag is in progress. // we want to ensure the clock is always stopped during drags to avoid weird audio playback. if (handlingDragInput) editorClock.Stop(); ScrollTo((float)(editorClock.CurrentTime / track.Length) * Content.DrawWidth, false); } protected override bool OnMouseDown(MouseDownEvent e) { if (base.OnMouseDown(e)) { beginUserDrag(); return true; } return false; } protected override void OnMouseUp(MouseUpEvent e) { endUserDrag(); base.OnMouseUp(e); } private void beginUserDrag() { handlingDragInput = true; trackWasPlaying = editorClock.IsRunning; editorClock.Stop(); } private void endUserDrag() { handlingDragInput = false; if (trackWasPlaying) editorClock.Start(); } [Resolved] private EditorBeatmap beatmap { get; set; } [Resolved] private IBeatSnapProvider beatSnapProvider { get; set; } /// <summary> /// The total amount of time visible on the timeline. /// </summary> public double VisibleRange => track.Length / Zoom; public SnapResult SnapScreenSpacePositionToValidPosition(Vector2 screenSpacePosition) => new SnapResult(screenSpacePosition, null); public SnapResult SnapScreenSpacePositionToValidTime(Vector2 screenSpacePosition) => new SnapResult(screenSpacePosition, beatSnapProvider.SnapTime(getTimeFromPosition(Content.ToLocalSpace(screenSpacePosition)))); private double getTimeFromPosition(Vector2 localPosition) => (localPosition.X / Content.DrawWidth) * track.Length; public float GetBeatSnapDistanceAt(double referenceTime) => throw new NotImplementedException(); public float DurationToDistance(double referenceTime, double duration) => throw new NotImplementedException(); public double DistanceToDuration(double referenceTime, float distance) => throw new NotImplementedException(); public double GetSnappedDurationFromDistance(double referenceTime, float distance) => throw new NotImplementedException(); public float GetSnappedDistanceFromDistance(double referenceTime, float distance) => throw new NotImplementedException(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; namespace System.Collections.Specialized.Tests { public class MoveNextTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { StringCollection sc; StringEnumerator en; string curr; // Enumerator.Current value // simple string values string[] values = { "a", "aa", "", " ", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // [] StringEnumerator.MoveNext() //----------------------------------------------------------------- sc = new StringCollection(); // // [] on Empty Collection // en = sc.GetEnumerator(); string type = en.GetType().ToString(); if (type.IndexOf("StringEnumerator", 0) == 0) { Assert.False(true, string.Format("Error, type is not StringEnumerator")); } // // MoveNext should return false // bool res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = en.Current; }); // // Add item to collection and MoveNext // int cnt = sc.Count; sc.Add(values[0]); if (sc.Count != 1) { Assert.False(true, string.Format("Error, failed to add item")); } Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); }); // // [] on Filled collection // sc.AddRange(values); en = sc.GetEnumerator(); type = en.GetType().ToString(); if (type.IndexOf("StringEnumerator", 0) == 0) { Assert.False(true, string.Format("Error, type is not StringEnumerator")); } // // MoveNext should return true // for (int i = 0; i < sc.Count; i++) { res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false", i)); } curr = en.Current; if (String.Compare(curr, sc[i]) != 0) { Assert.False(true, string.Format("Error, Current returned \"{1}\" instead of \"{2}\"", i, curr, sc[i])); } // while we didn't MoveNext, Current should return the same value string curr1 = en.Current; if (String.Compare(curr, curr1) != 0) { Assert.False(true, string.Format("Error, second call of Current returned different result", i)); } } // next MoveNext should bring us outside of the collection // res = en.MoveNext(); res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = en.Current; }); en.Reset(); // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = en.Current; }); // // [] Modify collection when enumerating // if (sc.Count < 1) sc.AddRange(values); en = sc.GetEnumerator(); for (int i = 0; i < sc.Count / 2; i++) { res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false", i)); } } cnt = sc.Count; curr = en.Current; sc.RemoveAt(0); if (sc.Count != cnt - 1) { Assert.False(true, string.Format("Error, didn't remove 0-item")); } // will return previous current if (String.Compare(curr, en.Current) != 0) { Assert.False(true, string.Format("Error, current returned {0} instead of {1}", en.Current, curr)); } // exception expected Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); }); // // [] Modify collection after enumerating // if (sc.Count < 1) sc.AddRange(values); en = sc.GetEnumerator(); for (int i = 0; i < sc.Count; i++) { res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false", i)); } } cnt = sc.Count; curr = en.Current; sc.RemoveAt(0); if (sc.Count != cnt - 1) { Assert.False(true, string.Format("Error, didn't remove 0-item")); } // will return previous current if (String.Compare(curr, en.Current) != 0) { Assert.False(true, string.Format("Error, current returned {0} instead of {1}", en.Current, curr)); } // exception expected Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); }); } } }
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using System.Globalization; namespace Newtonsoft.Json.Utilities { internal class DynamicReflectionDelegateFactory : ReflectionDelegateFactory { public static DynamicReflectionDelegateFactory Instance = new DynamicReflectionDelegateFactory(); private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) { DynamicMethod dynamicMethod = !owner.IsInterface ? new DynamicMethod(name, returnType, parameterTypes, owner, true) : new DynamicMethod(name, returnType, parameterTypes, owner.Module, true); return dynamicMethod; } public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method) { DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateMethodCallIL(method, generator); return (MethodCall<T, object>)dynamicMethod.CreateDelegate(typeof(MethodCall<T, object>)); } private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator) { ParameterInfo[] args = method.GetParameters(); Label argsOk = generator.DefineLabel(); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Ldlen); generator.Emit(OpCodes.Ldc_I4, args.Length); generator.Emit(OpCodes.Beq, argsOk); generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(Type.EmptyTypes)); generator.Emit(OpCodes.Throw); generator.MarkLabel(argsOk); if (!method.IsConstructor && !method.IsStatic) generator.PushInstance(method.DeclaringType); for (int i = 0; i < args.Length; i++) { generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Ldc_I4, i); generator.Emit(OpCodes.Ldelem_Ref); generator.UnboxIfNeeded(args[i].ParameterType); } if (method.IsConstructor) generator.Emit(OpCodes.Newobj, (ConstructorInfo)method); else if (method.IsFinal || !method.IsVirtual) generator.CallMethod((MethodInfo)method); Type returnType = method.IsConstructor ? method.DeclaringType : ((MethodInfo)method).ReturnType; if (returnType != typeof(void)) generator.BoxIfNeeded(returnType); else generator.Emit(OpCodes.Ldnull); generator.Return(); } public override Func<T> CreateDefaultConstructor<T>(Type type) { DynamicMethod dynamicMethod = CreateDynamicMethod("Create" + type.FullName, typeof(T), Type.EmptyTypes, type); dynamicMethod.InitLocals = true; ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateDefaultConstructorIL(type, generator); return (Func<T>)dynamicMethod.CreateDelegate(typeof(Func<T>)); } private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator) { if (type.IsValueType) { generator.DeclareLocal(type); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Box, type); } else { ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); if (constructorInfo == null) throw new Exception("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type)); generator.Emit(OpCodes.Newobj, constructorInfo); } generator.Return(); } public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(T), new[] { typeof(object) }, propertyInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateGetPropertyIL(propertyInfo, generator); return (Func<T, object>)dynamicMethod.CreateDelegate(typeof(Func<T, object>)); } private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) { MethodInfo getMethod = propertyInfo.GetGetMethod(true); if (getMethod == null) throw new Exception("Property '{0}' does not have a getter.".FormatWith(CultureInfo.InvariantCulture, propertyInfo.Name)); if (!getMethod.IsStatic) generator.PushInstance(propertyInfo.DeclaringType); generator.CallMethod(getMethod); generator.BoxIfNeeded(propertyInfo.PropertyType); generator.Return(); } public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateGetFieldIL(fieldInfo, generator); return (Func<T, object>)dynamicMethod.CreateDelegate(typeof(Func<T, object>)); } private void GenerateCreateGetFieldIL(FieldInfo fieldInfo, ILGenerator generator) { if (!fieldInfo.IsStatic) generator.PushInstance(fieldInfo.DeclaringType); generator.Emit(OpCodes.Ldfld, fieldInfo); generator.BoxIfNeeded(fieldInfo.FieldType); generator.Return(); } public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateSetFieldIL(fieldInfo, generator); return (Action<T, object>)dynamicMethod.CreateDelegate(typeof(Action<T, object>)); } internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator generator) { if (!fieldInfo.IsStatic) generator.PushInstance(fieldInfo.DeclaringType); generator.Emit(OpCodes.Ldarg_1); generator.UnboxIfNeeded(fieldInfo.FieldType); generator.Emit(OpCodes.Stfld, fieldInfo); generator.Return(); } public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateSetPropertyIL(propertyInfo, generator); return (Action<T, object>)dynamicMethod.CreateDelegate(typeof(Action<T, object>)); } internal static void GenerateCreateSetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) { MethodInfo setMethod = propertyInfo.GetSetMethod(true); if (!setMethod.IsStatic) generator.PushInstance(propertyInfo.DeclaringType); generator.Emit(OpCodes.Ldarg_1); generator.UnboxIfNeeded(propertyInfo.PropertyType); generator.CallMethod(setMethod); generator.Return(); } } } #endif
namespace groupmanager { partial class frmGroupManager { /// <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.groupBox = new System.Windows.Forms.GroupBox(); this.cmdInfo = new System.Windows.Forms.Button(); this.cmdActivate = new System.Windows.Forms.Button(); this.cmdCreate = new System.Windows.Forms.Button(); this.cmdLeave = new System.Windows.Forms.Button(); this.lstGroups = new System.Windows.Forms.ListBox(); this.grpLogin = new System.Windows.Forms.GroupBox(); this.comboGrid = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.cmdConnect = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.txtPassword = new System.Windows.Forms.TextBox(); this.txtLastName = new System.Windows.Forms.TextBox(); this.txtFirstName = new System.Windows.Forms.TextBox(); this.groupBox.SuspendLayout(); this.grpLogin.SuspendLayout(); this.SuspendLayout(); // // groupBox // this.groupBox.Controls.Add(this.cmdInfo); this.groupBox.Controls.Add(this.cmdActivate); this.groupBox.Controls.Add(this.cmdCreate); this.groupBox.Controls.Add(this.cmdLeave); this.groupBox.Controls.Add(this.lstGroups); this.groupBox.Enabled = false; this.groupBox.Location = new System.Drawing.Point(12, 12); this.groupBox.Name = "groupBox"; this.groupBox.Size = new System.Drawing.Size(419, 214); this.groupBox.TabIndex = 0; this.groupBox.TabStop = false; this.groupBox.Text = "Groups"; // // cmdInfo // this.cmdInfo.Enabled = false; this.cmdInfo.Location = new System.Drawing.Point(216, 174); this.cmdInfo.Name = "cmdInfo"; this.cmdInfo.Size = new System.Drawing.Size(90, 23); this.cmdInfo.TabIndex = 10; this.cmdInfo.Text = "Info"; this.cmdInfo.UseVisualStyleBackColor = true; this.cmdInfo.Click += new System.EventHandler(this.cmdInfo_Click); // // cmdActivate // this.cmdActivate.Enabled = false; this.cmdActivate.Location = new System.Drawing.Point(116, 174); this.cmdActivate.Name = "cmdActivate"; this.cmdActivate.Size = new System.Drawing.Size(90, 23); this.cmdActivate.TabIndex = 9; this.cmdActivate.Text = "Activate"; this.cmdActivate.UseVisualStyleBackColor = true; // // cmdCreate // this.cmdCreate.Location = new System.Drawing.Point(19, 174); this.cmdCreate.Name = "cmdCreate"; this.cmdCreate.Size = new System.Drawing.Size(90, 23); this.cmdCreate.TabIndex = 8; this.cmdCreate.Text = "Create"; this.cmdCreate.UseVisualStyleBackColor = true; // // cmdLeave // this.cmdLeave.Enabled = false; this.cmdLeave.Location = new System.Drawing.Point(313, 174); this.cmdLeave.Name = "cmdLeave"; this.cmdLeave.Size = new System.Drawing.Size(90, 23); this.cmdLeave.TabIndex = 7; this.cmdLeave.Text = "Leave"; this.cmdLeave.UseVisualStyleBackColor = true; // // lstGroups // this.lstGroups.FormattingEnabled = true; this.lstGroups.Location = new System.Drawing.Point(19, 31); this.lstGroups.Name = "lstGroups"; this.lstGroups.Size = new System.Drawing.Size(384, 134); this.lstGroups.TabIndex = 0; this.lstGroups.SelectedIndexChanged += new System.EventHandler(this.lstGroups_SelectedIndexChanged); // // grpLogin // this.grpLogin.Controls.Add(this.comboGrid); this.grpLogin.Controls.Add(this.label4); this.grpLogin.Controls.Add(this.cmdConnect); this.grpLogin.Controls.Add(this.label3); this.grpLogin.Controls.Add(this.label2); this.grpLogin.Controls.Add(this.label1); this.grpLogin.Controls.Add(this.txtPassword); this.grpLogin.Controls.Add(this.txtLastName); this.grpLogin.Controls.Add(this.txtFirstName); this.grpLogin.Location = new System.Drawing.Point(12, 232); this.grpLogin.Name = "grpLogin"; this.grpLogin.Size = new System.Drawing.Size(419, 176); this.grpLogin.TabIndex = 51; this.grpLogin.TabStop = false; // // comboGrid // this.comboGrid.FormattingEnabled = true; this.comboGrid.Items.AddRange(new object[] { "https://login.agni.lindenlab.com/cgi-bin/login.cgi", "https://login.aditi.lindenlab.com/cgi-bin/login.cgi", "http://127.0.0.1:8002"}); this.comboGrid.Location = new System.Drawing.Point(116, 104); this.comboGrid.Name = "comboGrid"; this.comboGrid.Size = new System.Drawing.Size(287, 21); this.comboGrid.TabIndex = 52; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(13, 107); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(73, 13); this.label4.TabIndex = 51; this.label4.Text = "Grid Selection"; // // cmdConnect // this.cmdConnect.Location = new System.Drawing.Point(116, 146); this.cmdConnect.Name = "cmdConnect"; this.cmdConnect.Size = new System.Drawing.Size(176, 24); this.cmdConnect.TabIndex = 3; this.cmdConnect.Text = "Connect"; this.cmdConnect.Click += new System.EventHandler(this.cmdConnect_Click); // // label3 // this.label3.Location = new System.Drawing.Point(13, 77); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 16); this.label3.TabIndex = 50; this.label3.Text = "Password"; // // label2 // this.label2.Location = new System.Drawing.Point(13, 51); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(65, 16); this.label2.TabIndex = 50; this.label2.Text = "Last Name"; // // label1 // this.label1.Location = new System.Drawing.Point(13, 25); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(59, 13); this.label1.TabIndex = 50; this.label1.Text = "First Name"; // // txtPassword // this.txtPassword.Location = new System.Drawing.Point(116, 74); this.txtPassword.Name = "txtPassword"; this.txtPassword.PasswordChar = '*'; this.txtPassword.Size = new System.Drawing.Size(176, 20); this.txtPassword.TabIndex = 2; // // txtLastName // this.txtLastName.Location = new System.Drawing.Point(116, 48); this.txtLastName.Name = "txtLastName"; this.txtLastName.Size = new System.Drawing.Size(176, 20); this.txtLastName.TabIndex = 1; // // txtFirstName // this.txtFirstName.Location = new System.Drawing.Point(116, 22); this.txtFirstName.Name = "txtFirstName"; this.txtFirstName.Size = new System.Drawing.Size(176, 20); this.txtFirstName.TabIndex = 0; // // frmGroupManager // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(437, 422); this.Controls.Add(this.grpLogin); this.Controls.Add(this.groupBox); this.MaximizeBox = false; this.MaximumSize = new System.Drawing.Size(453, 460); this.MinimumSize = new System.Drawing.Size(453, 460); this.Name = "frmGroupManager"; this.Text = "Group Manager"; this.groupBox.ResumeLayout(false); this.grpLogin.ResumeLayout(false); this.grpLogin.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBox; private System.Windows.Forms.ListBox lstGroups; private System.Windows.Forms.GroupBox grpLogin; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtPassword; private System.Windows.Forms.TextBox txtLastName; private System.Windows.Forms.Button cmdConnect; private System.Windows.Forms.TextBox txtFirstName; private System.Windows.Forms.Button cmdInfo; private System.Windows.Forms.Button cmdActivate; private System.Windows.Forms.Button cmdCreate; private System.Windows.Forms.Button cmdLeave; private System.Windows.Forms.ComboBox comboGrid; private System.Windows.Forms.Label label4; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection.Internal; using System.Text; using Xunit; namespace System.Reflection.Metadata.Tests { public class BlobReaderTests { [Fact] public unsafe void PublicBlobReaderCtorValidatesArgs() { byte* bufferPtrForLambda; byte[] buffer = new byte[4] { 0, 1, 0, 2 }; fixed (byte* bufferPtr = buffer) { bufferPtrForLambda = bufferPtr; Assert.Throws<ArgumentOutOfRangeException>(() => new BlobReader(bufferPtrForLambda, -1)); } Assert.Throws<ArgumentNullException>(() => new BlobReader(null, 1)); Assert.Equal(0, new BlobReader(null, 0).Length); // this is valid Assert.Throws<BadImageFormatException>(() => new BlobReader(null, 0).ReadByte()); // but can't read anything non-empty from it... Assert.Same(String.Empty, new BlobReader(null, 0).ReadUtf8NullTerminated()); // can read empty string. } [Fact] public unsafe void ReadBoolean1() { byte[] buffer = new byte[] { 1, 0xff, 0, 2 }; fixed (byte* bufferPtr = buffer) { var reader = new BlobReader(new MemoryBlock(bufferPtr, buffer.Length)); Assert.True(reader.ReadBoolean()); Assert.True(reader.ReadBoolean()); Assert.False(reader.ReadBoolean()); Assert.True(reader.ReadBoolean()); } } [Fact] public unsafe void ReadFromMemoryReader() { byte[] buffer = new byte[4] { 0, 1, 0, 2 }; fixed (byte* bufferPtr = buffer) { var reader = new BlobReader(new MemoryBlock(bufferPtr, buffer.Length)); Assert.False(reader.SeekOffset(-1)); Assert.False(reader.SeekOffset(Int32.MaxValue)); Assert.False(reader.SeekOffset(Int32.MinValue)); Assert.False(reader.SeekOffset(buffer.Length)); Assert.True(reader.SeekOffset(buffer.Length - 1)); Assert.True(reader.SeekOffset(0)); Assert.Equal(0, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt64()); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(1)); Assert.Equal(1, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadDouble()); Assert.Equal(1, reader.Offset); Assert.True(reader.SeekOffset(2)); Assert.Equal(2, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt32()); Assert.Equal((ushort)0x0200, reader.ReadUInt16()); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(2)); Assert.Equal(2, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadSingle()); Assert.Equal(2, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Equal(9.404242E-38F, reader.ReadSingle()); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(3)); Assert.Equal(3, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt16()); Assert.Equal((byte)0x02, reader.ReadByte()); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Equal("\u0000\u0001\u0000\u0002", reader.ReadUTF8(4)); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF8(5)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF8(-1)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Equal("\u0100\u0200", reader.ReadUTF16(4)); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(5)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(-1)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(6)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Equal(buffer, reader.ReadBytes(4)); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Same(String.Empty, reader.ReadUtf8NullTerminated()); Assert.Equal(1, reader.Offset); Assert.True(reader.SeekOffset(1)); Assert.Equal("\u0001", reader.ReadUtf8NullTerminated()); Assert.Equal(3, reader.Offset); Assert.True(reader.SeekOffset(3)); Assert.Equal("\u0002", reader.ReadUtf8NullTerminated()); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Same(String.Empty, reader.ReadUtf8NullTerminated()); Assert.Equal(1, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadBytes(5)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadBytes(Int32.MinValue)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.GetMemoryBlockAt(-1, 1)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.GetMemoryBlockAt(1, -1)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Equal(3, reader.GetMemoryBlockAt(1, 3).Length); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(3)); reader.ReadByte(); Assert.Equal(4, reader.Offset); Assert.Equal(4, reader.Offset); Assert.Equal(0, reader.ReadBytes(0).Length); Assert.Equal(4, reader.Offset); int value; Assert.False(reader.TryReadCompressedInteger(out value)); Assert.Equal(BlobReader.InvalidCompressedInteger, value); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadCompressedInteger()); Assert.Equal(4, reader.Offset); Assert.Equal(SerializationTypeCode.Invalid, reader.ReadSerializationTypeCode()); Assert.Equal(4, reader.Offset); Assert.Equal(SignatureTypeCode.Invalid, reader.ReadSignatureTypeCode()); Assert.Equal(4, reader.Offset); Assert.Equal(default(EntityHandle), reader.ReadTypeHandle()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadBoolean()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadByte()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadSByte()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt32()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadInt32()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt64()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadInt64()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadSingle()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadDouble()); Assert.Equal(4, reader.Offset); } byte[] buffer2 = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; fixed (byte* bufferPtr2 = buffer2) { var reader = new BlobReader(new MemoryBlock(bufferPtr2, buffer2.Length)); Assert.Equal(reader.Offset, 0); Assert.Equal(0x0807060504030201UL, reader.ReadUInt64()); Assert.Equal(reader.Offset, 8); reader.Reset(); Assert.Equal(reader.Offset, 0); Assert.Equal(0x0807060504030201L, reader.ReadInt64()); reader.Reset(); Assert.Equal(reader.Offset, 0); Assert.Equal(BitConverter.ToDouble(buffer2, 0), reader.ReadDouble()); } } [Fact] public unsafe void ValidatePeekReferenceSize() { byte[] buffer = new byte[8] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; fixed (byte* bufferPtr = buffer) { var block = new MemoryBlock(bufferPtr, buffer.Length); // small ref size always fits in 16 bits Assert.Equal(0xFFFF, block.PeekReference(0, smallRefSize: true)); Assert.Equal(0xFFFF, block.PeekReference(4, smallRefSize: true)); Assert.Equal(0xFFFFU, block.PeekTaggedReference(0, smallRefSize: true)); Assert.Equal(0xFFFFU, block.PeekTaggedReference(4, smallRefSize: true)); Assert.Equal(0x01FFU, block.PeekTaggedReference(6, smallRefSize: true)); // large ref size throws on > RIDMask when tagged variant is not used. Assert.Throws<BadImageFormatException>(() => block.PeekReference(0, smallRefSize: false)); Assert.Throws<BadImageFormatException>(() => block.PeekReference(4, smallRefSize: false)); // large ref size does not throw when Tagged variant is used. Assert.Equal(0xFFFFFFFFU, block.PeekTaggedReference(0, smallRefSize: false)); Assert.Equal(0x01FFFFFFU, block.PeekTaggedReference(4, smallRefSize: false)); // bounds check applies in all cases Assert.Throws<BadImageFormatException>(() => block.PeekReference(7, smallRefSize: true)); Assert.Throws<BadImageFormatException>(() => block.PeekReference(5, smallRefSize: false)); } } [Fact] public unsafe void ReadFromMemoryBlock() { byte[] buffer = new byte[4] { 0, 1, 0, 2 }; fixed (byte* bufferPtr = buffer) { var block = new MemoryBlock(bufferPtr, buffer.Length); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(-1)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(Int32.MinValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(4)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(1)); Assert.Equal(0x02000100U, block.PeekUInt32(0)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(-1)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(Int32.MinValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(4)); Assert.Equal(0x0200, block.PeekUInt16(2)); int bytesRead; MetadataStringDecoder stringDecoder = MetadataStringDecoder.DefaultUTF8; Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MaxValue, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(-1, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MinValue, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(5, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(1, -1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(0, -1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 0)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-Int32.MaxValue, Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, -Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(block.Length, -1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, block.Length)); Assert.Equal("\u0001", block.PeekUtf8NullTerminated(1, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 2); Assert.Equal("\u0002", block.PeekUtf8NullTerminated(3, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 1); Assert.Equal("", block.PeekUtf8NullTerminated(4, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 0); byte[] helloPrefix = Encoding.UTF8.GetBytes("Hello"); Assert.Equal("Hello\u0001", block.PeekUtf8NullTerminated(1, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 2); Assert.Equal("Hello\u0002", block.PeekUtf8NullTerminated(3, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 1); Assert.Equal("Hello", block.PeekUtf8NullTerminated(4, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 0); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementUInt323() { var test = new VectorGetAndWithElement__GetAndWithElementUInt323(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt323 { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt32[] values = new UInt32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt32(); } Vector128<UInt32> value = Vector128.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { UInt32 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<UInt32.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt32 insertedValue = TestLibrary.Generator.GetUInt32(); try { Vector128<UInt32> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<UInt32.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt32[] values = new UInt32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt32(); } Vector128<UInt32> value = Vector128.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector128) .GetMethod(nameof(Vector128.GetElement)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((UInt32)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<UInt32.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt32 insertedValue = TestLibrary.Generator.GetUInt32(); try { object result2 = typeof(Vector128) .GetMethod(nameof(Vector128.WithElement)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector128<UInt32>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<UInt32.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(3 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(3 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(UInt32 result, UInt32[] values, [CallerMemberName] string method = "") { if (result != values[3]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector128<UInt32.GetElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector128<UInt32> result, UInt32[] values, UInt32 insertedValue, [CallerMemberName] string method = "") { UInt32[] resultElements = new UInt32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(UInt32[] result, UInt32[] values, UInt32 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 3) && (result[i] != values[i])) { succeeded = false; break; } } if (result[3] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<UInt32.WithElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input; using osu.Framework.MathUtils; using osu.Framework.Timing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Configuration; using osu.Game.Rulesets; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.UI.Scrolling; using osuTK; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneDrawableScrollingRuleset : OsuTestScene { /// <summary> /// The amount of time visible by the "view window" of the playfield. /// All hitobjects added through <see cref="createBeatmap"/> are spaced apart by this value, such that for a beat length of 1000, /// there will be at most 2 hitobjects visible in the "view window". /// </summary> private const double time_range = 1000; private readonly ManualClock testClock = new ManualClock(); private TestDrawableScrollingRuleset drawableRuleset; [SetUp] public void Setup() => Schedule(() => testClock.CurrentTime = 0); [Test] public void TestRelativeBeatLengthScaleSingleTimingPoint() { var beatmap = createBeatmap(new TimingControlPoint { BeatLength = time_range / 2 }); createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); assertPosition(0, 0f); // The single timing point is 1x speed relative to itself, such that the hitobject occurring time_range milliseconds later should appear // at the bottom of the view window regardless of the timing point's beat length assertPosition(1, 1f); } [Test] public void TestRelativeBeatLengthScaleTimingPointBeyondEndDoesNotBecomeDominant() { var beatmap = createBeatmap( new TimingControlPoint { BeatLength = time_range / 2 }, new TimingControlPoint { Time = 12000, BeatLength = time_range }, new TimingControlPoint { Time = 100000, BeatLength = time_range }); createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); assertPosition(0, 0f); assertPosition(1, 1f); } [Test] public void TestRelativeBeatLengthScaleFromSecondTimingPoint() { var beatmap = createBeatmap( new TimingControlPoint { BeatLength = time_range }, new TimingControlPoint { Time = 3 * time_range, BeatLength = time_range / 2 }); createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); // The first timing point should have a relative velocity of 2 assertPosition(0, 0f); assertPosition(1, 0.5f); assertPosition(2, 1f); // Move to the second timing point setTime(3 * time_range); assertPosition(3, 0f); // As above, this is the timing point that is 1x speed relative to itself, so the hitobject occurring time_range milliseconds later should be at the bottom of the view window assertPosition(4, 1f); } [Test] public void TestNonRelativeScale() { var beatmap = createBeatmap( new TimingControlPoint { BeatLength = time_range }, new TimingControlPoint { Time = 3 * time_range, BeatLength = time_range / 2 }); createTest(beatmap); assertPosition(0, 0f); assertPosition(1, 1); // Move to the second timing point setTime(3 * time_range); assertPosition(3, 0f); // For a beat length of 500, the view window of this timing point is elongated 2x (1000 / 500), such that the second hitobject is two TimeRanges away (offscreen) // To bring it on-screen, half TimeRange is added to the current time, bringing the second half of the view window into view, and the hitobject should appear at the bottom setTime(3 * time_range + time_range / 2); assertPosition(4, 1f); } [Test] public void TestSliderMultiplierDoesNotAffectRelativeBeatLength() { var beatmap = createBeatmap(new TimingControlPoint { BeatLength = time_range }); beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier = 2; createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 5000); for (int i = 0; i < 5; i++) assertPosition(i, i / 5f); } [Test] public void TestSliderMultiplierAffectsNonRelativeBeatLength() { var beatmap = createBeatmap(new TimingControlPoint { BeatLength = time_range }); beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier = 2; createTest(beatmap); AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 2000); assertPosition(0, 0); assertPosition(1, 1); } private void assertPosition(int index, float relativeY) => AddAssert($"hitobject {index} at {relativeY}", () => Precision.AlmostEquals(drawableRuleset.Playfield.AllHitObjects.ElementAt(index).DrawPosition.Y, drawableRuleset.Playfield.HitObjectContainer.DrawHeight * relativeY)); private void setTime(double time) { AddStep($"set time = {time}", () => testClock.CurrentTime = time); } /// <summary> /// Creates an <see cref="IBeatmap"/>, containing 10 hitobjects and user-provided timing points. /// The hitobjects are spaced <see cref="time_range"/> milliseconds apart. /// </summary> /// <param name="timingControlPoints">The timing points to add to the beatmap.</param> /// <returns>The <see cref="IBeatmap"/>.</returns> private IBeatmap createBeatmap(params TimingControlPoint[] timingControlPoints) { var beatmap = new Beatmap<HitObject> { BeatmapInfo = { Ruleset = new OsuRuleset().RulesetInfo } }; beatmap.ControlPointInfo.TimingPoints.AddRange(timingControlPoints); for (int i = 0; i < 10; i++) beatmap.HitObjects.Add(new HitObject { StartTime = i * time_range }); return beatmap; } private void createTest(IBeatmap beatmap, Action<TestDrawableScrollingRuleset> overrideAction = null) => AddStep("create test", () => { var ruleset = new TestScrollingRuleset(); drawableRuleset = (TestDrawableScrollingRuleset)ruleset.CreateDrawableRulesetWith(CreateWorkingBeatmap(beatmap), Array.Empty<Mod>()); drawableRuleset.FrameStablePlayback = false; overrideAction?.Invoke(drawableRuleset); Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Y, Height = 0.75f, Width = 400, Masking = true, Clock = new FramedClock(testClock), Child = drawableRuleset }; }); #region Ruleset private class TestScrollingRuleset : Ruleset { public TestScrollingRuleset(RulesetInfo rulesetInfo = null) : base(rulesetInfo) { } public override IEnumerable<Mod> GetModsFor(ModType type) => throw new NotImplementedException(); public override DrawableRuleset CreateDrawableRulesetWith(IWorkingBeatmap beatmap, IReadOnlyList<Mod> mods) => new TestDrawableScrollingRuleset(this, beatmap, mods); public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => new TestBeatmapConverter(beatmap); public override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => throw new NotImplementedException(); public override string Description { get; } = string.Empty; public override string ShortName { get; } = string.Empty; } private class TestDrawableScrollingRuleset : DrawableScrollingRuleset<TestHitObject> { public bool RelativeScaleBeatLengthsOverride { get; set; } protected override bool RelativeScaleBeatLengths => RelativeScaleBeatLengthsOverride; protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Overlapping; public new Bindable<double> TimeRange => base.TimeRange; public TestDrawableScrollingRuleset(Ruleset ruleset, IWorkingBeatmap beatmap, IReadOnlyList<Mod> mods) : base(ruleset, beatmap, mods) { TimeRange.Value = time_range; } public override DrawableHitObject<TestHitObject> CreateDrawableRepresentation(TestHitObject h) => new DrawableTestHitObject(h); protected override PassThroughInputManager CreateInputManager() => new PassThroughInputManager(); protected override Playfield CreatePlayfield() => new TestPlayfield(); } private class TestPlayfield : ScrollingPlayfield { public TestPlayfield() { AddInternal(new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Alpha = 0.2f, }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = 150 }, Children = new Drawable[] { new Box { Anchor = Anchor.TopCentre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Height = 2, Colour = Color4.Green }, HitObjectContainer } } } }); } } private class TestBeatmapConverter : BeatmapConverter<TestHitObject> { public TestBeatmapConverter(IBeatmap beatmap) : base(beatmap) { } protected override IEnumerable<Type> ValidConversionTypes => new[] { typeof(HitObject) }; protected override IEnumerable<TestHitObject> ConvertHitObject(HitObject original, IBeatmap beatmap) { yield return new TestHitObject { StartTime = original.StartTime, EndTime = (original as IHasEndTime)?.EndTime ?? (original.StartTime + 100) }; } } #endregion #region HitObject private class TestHitObject : HitObject, IHasEndTime { public double EndTime { get; set; } public double Duration => EndTime - StartTime; } private class DrawableTestHitObject : DrawableHitObject<TestHitObject> { public DrawableTestHitObject(TestHitObject hitObject) : base(hitObject) { Anchor = Anchor.TopCentre; Origin = Anchor.TopCentre; Size = new Vector2(100, 25); AddRangeInternal(new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.LightPink }, new Box { Origin = Anchor.CentreLeft, RelativeSizeAxes = Axes.X, Height = 2, Colour = Color4.Red } }); } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ApiOperations operations. /// </summary> public partial interface IApiOperations { /// <summary> /// Lists all APIs of the API Management service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-create-apis" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ApiContract>>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, ODataQuery<ApiContract> odataQuery = default(ODataQuery<ApiContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the details of the API specified by its identifier. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management /// service instance. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiContract,ApiGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates new or updates existing specified API of the API Management /// service instance. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management /// service instance. /// </param> /// <param name='parameters'> /// Create or update parameters. /// </param> /// <param name='ifMatch'> /// ETag of the Api Entity. For Create Api Etag should not be /// specified. For Update Etag should match the existing Entity or it /// can be * for unconditional update. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiContract,ApiCreateOrUpdateHeaders>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, ApiCreateOrUpdateParameter parameters, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the specified API of the API Management service instance. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management /// service instance. /// </param> /// <param name='parameters'> /// API Update Contract parameters. /// </param> /// <param name='ifMatch'> /// ETag of the API entity. ETag should match the current entity state /// in the header response of the GET request or it should be * for /// unconditional update. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, ApiUpdateContract parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified API of the API Management service instance. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management /// service instance. /// </param> /// <param name='ifMatch'> /// ETag of the API Entity. ETag should match the current entity state /// from the header response of the GET request or it should be * for /// unconditional update. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all APIs of the API Management service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-create-apis" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ApiContract>>> ListByServiceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Abstractions; using System.Net; using System.Net.Http.Formatting; using System.Web; using System.Web.Http; using System.Web.Routing; using Kudu.Contracts.Infrastructure; using Kudu.Contracts.Settings; using Kudu.Contracts.SourceControl; using Kudu.Contracts.Tracing; using Kudu.Core; using Kudu.Core.Commands; using Kudu.Core.Deployment; using Kudu.Core.Deployment.Generator; using Kudu.Core.Hooks; using Kudu.Core.Infrastructure; using Kudu.Core.Settings; using Kudu.Core.SourceControl; using Kudu.Core.SourceControl.Git; using Kudu.Core.SSHKey; using Kudu.Core.Tracing; using Kudu.Services.GitServer; using Kudu.Services.Infrastructure; using Kudu.Services.Performance; using Kudu.Services.ServiceHookHandlers; using Kudu.Services.SSHKey; using Kudu.Services.Web.Infrastructure; using Kudu.Services.Web.Services; using Kudu.Services.Web.Tracing; using Ninject; using Ninject.Activation; using Ninject.Web.Common; using XmlSettings; [assembly: WebActivator.PreApplicationStartMethod(typeof(Kudu.Services.Web.App_Start.NinjectServices), "Start")] [assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(Kudu.Services.Web.App_Start.NinjectServices), "Stop")] namespace Kudu.Services.Web.App_Start { public static class NinjectServices { /// <summary> /// Root directory that contains the VS target files /// </summary> private const string SdkRootDirectory = "msbuild"; private static readonly Bootstrapper _bootstrapper = new Bootstrapper(); // Due to a bug in Ninject we can't use Dispose to clean up LockFile so we shut it down manually private static LockFile _deploymentLock; private static event Action Shutdown; /// <summary> /// Starts the application /// </summary> public static void Start() { HttpApplication.RegisterModule(typeof(OnePerRequestHttpModule)); HttpApplication.RegisterModule(typeof(NinjectHttpModule)); _bootstrapper.Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { if (Shutdown != null) { Shutdown(); } if (_deploymentLock != null) { _deploymentLock.TerminateAsyncLocks(); _deploymentLock = null; } _bootstrapper.ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); kernel.Components.Add<INinjectHttpApplicationPlugin, NinjectHttpApplicationPlugin>(); RegisterServices(kernel); return kernel; } /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "")] private static void RegisterServices(IKernel kernel) { var serverConfiguration = new ServerConfiguration(); IEnvironment environment = GetEnvironment(); // Per request environment kernel.Bind<IEnvironment>().ToMethod(context => GetEnvironment(context.Kernel.Get<IDeploymentSettingsManager>())) .InRequestScope(); // General kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current)) .InRequestScope(); kernel.Bind<IServerConfiguration>().ToConstant(serverConfiguration); kernel.Bind<IFileSystem>().To<FileSystem>().InSingletonScope(); kernel.Bind<IBuildPropertyProvider>().ToConstant(new BuildPropertyProvider()); System.Func<ITracer> createTracerThunk = () => GetTracer(environment, kernel); System.Func<ILogger> createLoggerThunk = () => GetLogger(environment, kernel); // First try to use the current request profiler if any, otherwise create a new one var traceFactory = new TracerFactory(() => TraceServices.CurrentRequestTracer ?? createTracerThunk()); kernel.Bind<ITracer>().ToMethod(context => TraceServices.CurrentRequestTracer ?? NullTracer.Instance); kernel.Bind<ITraceFactory>().ToConstant(traceFactory); TraceServices.SetTraceFactory(createTracerThunk, createLoggerThunk); // Setup the deployment lock string lockPath = Path.Combine(environment.SiteRootPath, Constants.LockPath); string deploymentLockPath = Path.Combine(lockPath, Constants.DeploymentLockFile); string statusLockPath = Path.Combine(lockPath, Constants.StatusLockFile); string sshKeyLockPath = Path.Combine(lockPath, Constants.SSHKeyLockFile); string hooksLockPath = Path.Combine(lockPath, Constants.HooksLockFile); var fileSystem = new FileSystem(); _deploymentLock = new LockFile(deploymentLockPath, kernel.Get<ITraceFactory>(), fileSystem); _deploymentLock.InitializeAsyncLocks(); var statusLock = new LockFile(statusLockPath, kernel.Get<ITraceFactory>(), fileSystem); var sshKeyLock = new LockFile(sshKeyLockPath, kernel.Get<ITraceFactory>(), fileSystem); var hooksLock = new LockFile(hooksLockPath, kernel.Get<ITraceFactory>(), fileSystem); kernel.Bind<IOperationLock>().ToConstant(sshKeyLock).WhenInjectedInto<SSHKeyController>(); kernel.Bind<IOperationLock>().ToConstant(statusLock).WhenInjectedInto<DeploymentStatusManager>(); kernel.Bind<IOperationLock>().ToConstant(hooksLock).WhenInjectedInto<WebHooksManager>(); kernel.Bind<IOperationLock>().ToConstant(_deploymentLock); kernel.Bind<IAnalytics>().ToMethod(context => new Analytics(context.Kernel.Get<IDeploymentSettingsManager>(), fileSystem, context.Kernel.Get<ITracer>(), environment.AnalyticsPath)); var shutdownDetector = new ShutdownDetector(); shutdownDetector.Initialize(); // Trace shutdown event // Cannot use shutdownDetector.Token.Register because of race condition // with NinjectServices.Stop via WebActivator.ApplicationShutdownMethodAttribute Shutdown += () => TraceShutdown(environment, kernel); // LogStream service // The hooks and log stream start endpoint are low traffic end-points. Re-using it to avoid creating another lock var logStreamManagerLock = hooksLock; kernel.Bind<LogStreamManager>().ToMethod(context => new LogStreamManager(Path.Combine(environment.RootPath, Constants.LogFilesPath), context.Kernel.Get<IEnvironment>(), context.Kernel.Get<IDeploymentSettingsManager>(), context.Kernel.Get<ITracer>(), shutdownDetector, logStreamManagerLock)); kernel.Bind<InfoRefsController>().ToMethod(context => new InfoRefsController(t => context.Kernel.Get(t))) .InRequestScope(); kernel.Bind<CustomGitRepositoryHandler>().ToMethod(context => new CustomGitRepositoryHandler(t => context.Kernel.Get(t))) .InRequestScope(); // Deployment Service kernel.Bind<ISettings>().ToMethod(context => new XmlSettings.Settings(GetSettingsPath(environment))) .InRequestScope(); kernel.Bind<IDeploymentSettingsManager>().To<DeploymentSettingsManager>() .InRequestScope(); kernel.Bind<IDeploymentStatusManager>().To<DeploymentStatusManager>() .InRequestScope(); kernel.Bind<ISiteBuilderFactory>().To<SiteBuilderFactory>() .InRequestScope(); kernel.Bind<IWebHooksManager>().To<WebHooksManager>() .InRequestScope(); kernel.Bind<ILogger>().ToMethod(context => GetLogger(environment, context.Kernel)) .InRequestScope(); kernel.Bind<IRepository>().ToMethod(context => new GitExeRepository(context.Kernel.Get<IEnvironment>(), context.Kernel.Get<IDeploymentSettingsManager>(), context.Kernel.Get<ITraceFactory>())) .InRequestScope(); kernel.Bind<IDeploymentManager>().To<DeploymentManager>() .InRequestScope(); kernel.Bind<ISSHKeyManager>().To<SSHKeyManager>() .InRequestScope(); kernel.Bind<IRepositoryFactory>().To<RepositoryFactory>() .InRequestScope(); // Git server kernel.Bind<IDeploymentEnvironment>().To<DeploymentEnvrionment>(); kernel.Bind<IGitServer>().ToMethod(context => new GitExeServer(context.Kernel.Get<IEnvironment>(), _deploymentLock, GetRequestTraceFile(context.Kernel), context.Kernel.Get<IRepositoryFactory>(), context.Kernel.Get<IDeploymentEnvironment>(), context.Kernel.Get<IDeploymentSettingsManager>(), context.Kernel.Get<ITraceFactory>())) .InRequestScope(); // Git Servicehook parsers kernel.Bind<IServiceHookHandler>().To<GenericHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<GitHubHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<BitbucketHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<DropboxHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<CodePlexHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<CodebaseHqHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<GitlabHqHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<GitHubCompatHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<KilnHgHandler>().InRequestScope(); // Command executor kernel.Bind<ICommandExecutor>().ToMethod(context => GetCommandExecutor(environment, context)) .InRequestScope(); MigrateSite(environment, kernel); RegisterRoutes(kernel, RouteTable.Routes); } public static void RegisterRoutes(IKernel kernel, RouteCollection routes) { var configuration = kernel.Get<IServerConfiguration>(); GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly; var jsonFormatter = new JsonMediaTypeFormatter(); GlobalConfiguration.Configuration.Formatters.Add(jsonFormatter); GlobalConfiguration.Configuration.DependencyResolver = new NinjectWebApiDependencyResolver(kernel); GlobalConfiguration.Configuration.Filters.Add(new TraceExceptionFilterAttribute()); // Git Service routes.MapHttpRoute("git-info-refs-root", "info/refs", new { controller = "InfoRefs", action = "Execute" }); routes.MapHttpRoute("git-info-refs", configuration.GitServerRoot + "/info/refs", new { controller = "InfoRefs", action = "Execute" }); // Push url routes.MapHandler<ReceivePackHandler>(kernel, "git-receive-pack-root", "git-receive-pack"); routes.MapHandler<ReceivePackHandler>(kernel, "git-receive-pack", configuration.GitServerRoot + "/git-receive-pack"); // Fetch Hook routes.MapHandler<FetchHandler>(kernel, "fetch", "deploy"); // Clone url routes.MapHandler<UploadPackHandler>(kernel, "git-upload-pack-root", "git-upload-pack"); routes.MapHandler<UploadPackHandler>(kernel, "git-upload-pack", configuration.GitServerRoot + "/git-upload-pack"); // Custom GIT repositories, which can be served from any directory that has a git repo routes.MapHandler<CustomGitRepositoryHandler>(kernel, "git-custom-repository", "git/{*path}"); // Scm (deployment repository) routes.MapHttpRoute("scm-info", "scm/info", new { controller = "LiveScm", action = "GetRepositoryInfo" }); routes.MapHttpRoute("scm-clean", "scm/clean", new { controller = "LiveScm", action = "Clean" }); routes.MapHttpRoute("scm-delete", "scm", new { controller = "LiveScm", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") }); // Scm files editor routes.MapHttpRoute("scm-get-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") }); routes.MapHttpRoute("scm-put-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpRoute("scm-delete-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "DeleteItem" }, new { verb = new HttpMethodConstraint("DELETE") }); // Live files editor routes.MapHttpRoute("vfs-get-files", "vfs/{*path}", new { controller = "Vfs", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") }); routes.MapHttpRoute("vfs-put-files", "vfs/{*path}", new { controller = "Vfs", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpRoute("vfs-delete-files", "vfs/{*path}", new { controller = "Vfs", action = "DeleteItem" }, new { verb = new HttpMethodConstraint("DELETE") }); // Zip file handler routes.MapHttpRoute("zip-get-files", "zip/{*path}", new { controller = "Zip", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") }); routes.MapHttpRoute("zip-put-files", "zip/{*path}", new { controller = "Zip", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") }); // Live Command Line routes.MapHttpRoute("execute-command", "command", new { controller = "Command", action = "ExecuteCommand" }, new { verb = new HttpMethodConstraint("POST") }); // Deployments routes.MapHttpRoute("all-deployments", "deployments", new { controller = "Deployment", action = "GetDeployResults" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("one-deployment-get", "deployments/{id}", new { controller = "Deployment", action = "GetResult" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("one-deployment-put", "deployments/{id}", new { controller = "Deployment", action = "Deploy", id = RouteParameter.Optional }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpRoute("one-deployment-delete", "deployments/{id}", new { controller = "Deployment", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") }); routes.MapHttpRoute("one-deployment-log", "deployments/{id}/log", new { controller = "Deployment", action = "GetLogEntry" }); routes.MapHttpRoute("one-deployment-log-details", "deployments/{id}/log/{logId}", new { controller = "Deployment", action = "GetLogEntryDetails" }); // SSHKey routes.MapHttpRoute("get-sshkey", "sshkey", new { controller = "SSHKey", action = "GetPublicKey" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("put-sshkey", "sshkey", new { controller = "SSHKey", action = "SetPrivateKey" }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpRoute("delete-sshkey", "sshkey", new { controller = "SSHKey", action = "DeleteKeyPair" }, new { verb = new HttpMethodConstraint("DELETE") }); // Environment routes.MapHttpRoute("get-env", "environment", new { controller = "Environment", action = "Get" }, new { verb = new HttpMethodConstraint("GET") }); // Settings routes.MapHttpRoute("set-setting", "settings", new { controller = "Settings", action = "Set" }, new { verb = new HttpMethodConstraint("POST") }); routes.MapHttpRoute("get-all-settings", "settings", new { controller = "Settings", action = "GetAll" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("get-setting", "settings/{key}", new { controller = "Settings", action = "Get" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("delete-setting", "settings/{key}", new { controller = "Settings", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") }); // Diagnostics routes.MapHttpRoute("diagnostics", "dump", new { controller = "Diagnostics", action = "GetLog" }); routes.MapHttpRoute("diagnostics-set-setting", "diagnostics/settings", new { controller = "Diagnostics", action = "Set" }, new { verb = new HttpMethodConstraint("POST") }); routes.MapHttpRoute("diagnostics-get-all-settings", "diagnostics/settings", new { controller = "Diagnostics", action = "GetAll" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("diagnostics-get-setting", "diagnostics/settings/{key}", new { controller = "Diagnostics", action = "Get" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("diagnostics-delete-setting", "diagnostics/settings/{key}", new { controller = "Diagnostics", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") }); // LogStream routes.MapHandler<LogStreamHandler>(kernel, "logstream", "logstream/{*path}"); // Processes routes.MapHttpRoute("all-processes", "diagnostics/processes", new { controller = "Process", action = "GetAllProcesses" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("one-process-get", "diagnostics/processes/{id}", new { controller = "Process", action = "GetProcess" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("one-process-delete", "diagnostics/processes/{id}", new { controller = "Process", action = "KillProcess" }, new { verb = new HttpMethodConstraint("DELETE") }); routes.MapHttpRoute("one-process-dump", "diagnostics/processes/{id}/dump", new { controller = "Process", action = "MiniDump" }, new { verb = new HttpMethodConstraint("GET") }); if (ProcessExtensions.SupportGCDump) { routes.MapHttpRoute("one-process-gcdump", "diagnostics/processes/{id}/gcdump", new { controller = "Process", action = "GCDump" }, new { verb = new HttpMethodConstraint("GET") }); } routes.MapHttpRoute("all-threads", "diagnostics/processes/{id}/threads", new { controller = "Process", action = "GetAllThreads" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("one-process-thread", "diagnostics/processes/{processId}/threads/{threadId}", new { controller = "Process", action = "GetThread" }, new { verb = new HttpMethodConstraint("GET") }); // Runtime routes.MapHttpRoute("runtime", "diagnostics/runtime", new { controller = "Runtime", action = "GetRuntimeVersions" }, new { verb = new HttpMethodConstraint("GET") }); // Hooks routes.MapHttpRoute("unsubscribe-hook", "hooks/{id}", new { controller = "WebHooks", action = "Unsubscribe" }, new { verb = new HttpMethodConstraint("DELETE") }); routes.MapHttpRoute("get-hook", "hooks/{id}", new { controller = "WebHooks", action = "GetWebHook" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("publish-hooks", "hooks/publish/{hookEventType}", new { controller = "WebHooks", action = "PublishEvent" }, new { verb = new HttpMethodConstraint("POST") }); routes.MapHttpRoute("get-hooks", "hooks", new { controller = "WebHooks", action = "GetWebHooks" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("subscribe-hook", "hooks", new { controller = "WebHooks", action = "Subscribe" }, new { verb = new HttpMethodConstraint("POST") }); } // Perform migration tasks to deal with legacy sites that had different file layout private static void MigrateSite(IEnvironment environment, IKernel kernel) { try { MoveOldSSHFolder(environment); } catch (Exception e) { ITracer tracer = GetTracerWithoutContext(environment, kernel); tracer.Trace("Failed to move legacy .ssh folder: {0}", e.Message); } } // .ssh folder used to be under /site, and is now at the root private static void MoveOldSSHFolder(IEnvironment environment) { var oldSSHDirInfo = new DirectoryInfo(Path.Combine(environment.SiteRootPath, Constants.SSHKeyPath)); if (oldSSHDirInfo.Exists) { string newSSHFolder = Path.Combine(environment.RootPath, Constants.SSHKeyPath); if (!Directory.Exists(newSSHFolder)) { Directory.CreateDirectory(newSSHFolder); } foreach (FileInfo file in oldSSHDirInfo.EnumerateFiles()) { // Copy the file to the new folder, unless it already exists string newFile = Path.Combine(newSSHFolder, file.Name); if (!File.Exists(newFile)) { file.CopyTo(newFile, overwrite: true); } } // Delete the old folder oldSSHDirInfo.Delete(recursive: true); } } private static ITracer GetTracer(IEnvironment environment, IKernel kernel) { TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel(); if (level > TraceLevel.Off) { string tracePath = Path.Combine(environment.TracePath, Constants.TraceFile); string textPath = Path.Combine(environment.TracePath, TraceServices.CurrentRequestTraceFile); string traceLockPath = Path.Combine(environment.TracePath, Constants.TraceLockFile); var traceLock = new LockFile(traceLockPath); return new CascadeTracer(new Tracer(tracePath, level, traceLock), new TextTracer(textPath, level)); } return NullTracer.Instance; } private static ITracer GetTracerWithoutContext(IEnvironment environment, IKernel kernel) { TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel(); if (level > TraceLevel.Off) { string tracePath = Path.Combine(environment.TracePath, Constants.TraceFile); string traceLockPath = Path.Combine(environment.TracePath, Constants.TraceLockFile); var traceLock = new LockFile(traceLockPath); return new Tracer(tracePath, level, traceLock); } return NullTracer.Instance; } private static void TraceShutdown(IEnvironment environment, IKernel kernel) { ITracer tracer = GetTracerWithoutContext(environment, kernel); var attribs = new Dictionary<string, string>(); // Add an attribute containing the process, AppDomain and Thread ids to help debugging attribs.Add("pid", String.Format("{0},{1},{2}", Process.GetCurrentProcess().Id, AppDomain.CurrentDomain.Id.ToString(), System.Threading.Thread.CurrentThread.ManagedThreadId)); attribs.Add("uptime", TraceModule.UpTime.ToString()); attribs.Add("lastrequesttime", TraceModule.LastRequestTime.ToString()); tracer.Trace("Process Shutdown", attribs); } private static ILogger GetLogger(IEnvironment environment, IKernel kernel) { TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel(); if (level > TraceLevel.Off) { string textPath = Path.Combine(environment.DeploymentTracePath, TraceServices.CurrentRequestTraceFile); return new TextLogger(textPath); } return NullLogger.Instance; } private static string GetRequestTraceFile(IKernel kernel) { TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel(); if (level > TraceLevel.Off) { return TraceServices.CurrentRequestTraceFile; } return null; } private static ICommandExecutor GetCommandExecutor(IEnvironment environment, IContext context) { if (System.String.IsNullOrEmpty(environment.RepositoryPath)) { throw new HttpResponseException(HttpStatusCode.NotFound); } return new CommandExecutor(environment.RootPath, environment, context.Kernel.Get<IDeploymentSettingsManager>(), TraceServices.CurrentRequestTracer); } private static string GetSettingsPath(IEnvironment environment) { return Path.Combine(environment.DeploymentsPath, Constants.DeploySettingsPath); } private static IEnvironment GetEnvironment(IDeploymentSettingsManager settings = null) { string root = PathResolver.ResolveRootPath(); string siteRoot = Path.Combine(root, Constants.SiteFolder); string repositoryPath = Path.Combine(siteRoot, settings == null ? Constants.RepositoryPath : settings.GetRepositoryPath()); return new Kudu.Core.Environment( new FileSystem(), root, HttpRuntime.BinDirectory, repositoryPath); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; using System.Threading; namespace System.Linq.Expressions { /// <summary> /// Represents a block that contains a sequence of expressions where variables can be defined. /// </summary> [DebuggerTypeProxy(typeof(BlockExpressionProxy))] public class BlockExpression : Expression { /// <summary> /// Gets the expressions in this block. /// </summary> public ReadOnlyCollection<Expression> Expressions => GetOrMakeExpressions(); /// <summary> /// Gets the variables defined in this block. /// </summary> public ReadOnlyCollection<ParameterExpression> Variables => GetOrMakeVariables(); /// <summary> /// Gets the last expression in this block. /// </summary> public Expression Result => GetExpression(ExpressionCount - 1); internal BlockExpression() { } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitBlock(this); } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.Block; /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. /// </summary> /// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns> public override Type Type => GetExpression(ExpressionCount - 1).Type; /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="variables">The <see cref="Variables"/> property of the result.</param> /// <param name="expressions">The <see cref="Expressions"/> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public BlockExpression Update(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { if (expressions != null) { // Ensure variables is safe to enumerate twice. // (If this means a second call to ToReadOnly it will return quickly). ICollection<ParameterExpression> vars; if (variables == null) { vars = null; } else { vars = variables as ICollection<ParameterExpression>; if (vars == null) { variables = vars = variables.ToReadOnly(); } } if (SameVariables(vars)) { // Ensure expressions is safe to enumerate twice. // (If this means a second call to ToReadOnly it will return quickly). ICollection<Expression> exps = expressions as ICollection<Expression>; if (exps == null) { expressions = exps = expressions.ToReadOnly(); } if (SameExpressions(exps)) { return this; } } } return Block(Type, variables, expressions); } internal virtual bool SameVariables(ICollection<ParameterExpression> variables) => variables == null || variables.Count == 0; [ExcludeFromCodeCoverage] // Unreachable internal virtual bool SameExpressions(ICollection<Expression> expressions) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable internal virtual Expression GetExpression(int index) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable internal virtual int ExpressionCount { get { throw ContractUtils.Unreachable; } } [ExcludeFromCodeCoverage] // Unreachable internal virtual ReadOnlyCollection<Expression> GetOrMakeExpressions() { throw ContractUtils.Unreachable; } internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeVariables() { return EmptyReadOnlyCollection<ParameterExpression>.Instance; } /// <summary> /// Makes a copy of this node replacing the parameters/args with the provided values. The /// shape of the parameters/args needs to match the shape of the current block - in other /// words there should be the same # of parameters and args. /// /// parameters can be null in which case the existing parameters are used. /// /// This helper is provided to allow re-writing of nodes to not depend on the specific optimized /// subclass of BlockExpression which is being used. /// </summary> [ExcludeFromCodeCoverage] // Unreachable internal virtual BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { throw ContractUtils.Unreachable; } /// <summary> /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. /// /// This is similar to the ReturnReadOnly which only takes a single argument. This version /// supports nodes which hold onto 5 Expressions and puts all of the arguments into the /// ReadOnlyCollection. /// /// Ultimately this means if we create the read-only collection we will be slightly more wasteful as we'll /// have a read-only collection + some fields in the type. The DLR internally avoids accessing anything /// which would force the read-only collection to be created. /// /// This is used by BlockExpression5 and MethodCallExpression5. /// </summary> internal static ReadOnlyCollection<Expression> ReturnReadOnlyExpressions(BlockExpression provider, ref object collection) { Expression tObj = collection as Expression; if (tObj != null) { // otherwise make sure only one read-only collection ever gets exposed Interlocked.CompareExchange( ref collection, new ReadOnlyCollection<Expression>(new BlockExpressionList(provider, tObj)), tObj ); } // and return what is not guaranteed to be a read-only collection return (ReadOnlyCollection<Expression>)collection; } } #region Specialized Subclasses internal sealed class Block2 : BlockExpression { private object _arg0; // storage for the 1st argument or a read-only collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd argument. internal Block2(Expression arg0, Expression arg1) { _arg0 = arg0; _arg1 = arg1; } internal override Expression GetExpression(int index) => index switch { 0 => ExpressionUtils.ReturnObject<Expression>(_arg0), 1 => _arg1, _ => throw Error.ArgumentOutOfRange(nameof(index)), }; internal override bool SameExpressions(ICollection<Expression> expressions) { Debug.Assert(expressions != null); if (expressions.Count == 2) { ReadOnlyCollection<Expression> alreadyCollection = _arg0 as ReadOnlyCollection<Expression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(expressions, alreadyCollection); } using (IEnumerator<Expression> en = expressions.GetEnumerator()) { en.MoveNext(); if (en.Current == _arg0) { en.MoveNext(); return en.Current == _arg1; } } } return false; } internal override int ExpressionCount => 2; internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 2); Debug.Assert(variables == null || variables.Count == 0); return new Block2(args[0], args[1]); } } internal sealed class Block3 : BlockExpression { private object _arg0; // storage for the 1st argument or a read-only collection. See IArgumentProvider private readonly Expression _arg1, _arg2; // storage for the 2nd and 3rd arguments. internal Block3(Expression arg0, Expression arg1, Expression arg2) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; } internal override bool SameExpressions(ICollection<Expression> expressions) { Debug.Assert(expressions != null); if (expressions.Count == 3) { ReadOnlyCollection<Expression> alreadyCollection = _arg0 as ReadOnlyCollection<Expression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(expressions, alreadyCollection); } using (IEnumerator<Expression> en = expressions.GetEnumerator()) { en.MoveNext(); if (en.Current == _arg0) { en.MoveNext(); if (en.Current == _arg1) { en.MoveNext(); return en.Current == _arg2; } } } } return false; } internal override Expression GetExpression(int index) => index switch { 0 => ExpressionUtils.ReturnObject<Expression>(_arg0), 1 => _arg1, 2 => _arg2, _ => throw Error.ArgumentOutOfRange(nameof(index)), }; internal override int ExpressionCount => 3; internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 3); Debug.Assert(variables == null || variables.Count == 0); return new Block3(args[0], args[1], args[2]); } } internal sealed class Block4 : BlockExpression { private object _arg0; // storage for the 1st argument or a read-only collection. See IArgumentProvider private readonly Expression _arg1, _arg2, _arg3; // storage for the 2nd, 3rd, and 4th arguments. internal Block4(Expression arg0, Expression arg1, Expression arg2, Expression arg3) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; } internal override bool SameExpressions(ICollection<Expression> expressions) { Debug.Assert(expressions != null); if (expressions.Count == 4) { ReadOnlyCollection<Expression> alreadyCollection = _arg0 as ReadOnlyCollection<Expression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(expressions, alreadyCollection); } using (IEnumerator<Expression> en = expressions.GetEnumerator()) { en.MoveNext(); if (en.Current == _arg0) { en.MoveNext(); if (en.Current == _arg1) { en.MoveNext(); if (en.Current == _arg2) { en.MoveNext(); return en.Current == _arg3; } } } } } return false; } internal override Expression GetExpression(int index) => index switch { 0 => ExpressionUtils.ReturnObject<Expression>(_arg0), 1 => _arg1, 2 => _arg2, 3 => _arg3, _ => throw Error.ArgumentOutOfRange(nameof(index)), }; internal override int ExpressionCount => 4; internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 4); Debug.Assert(variables == null || variables.Count == 0); return new Block4(args[0], args[1], args[2], args[3]); } } internal sealed class Block5 : BlockExpression { private object _arg0; // storage for the 1st argument or a read-only collection. See IArgumentProvider private readonly Expression _arg1, _arg2, _arg3, _arg4; // storage for the 2nd - 5th args. internal Block5(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; _arg4 = arg4; } internal override Expression GetExpression(int index) => index switch { 0 => ExpressionUtils.ReturnObject<Expression>(_arg0), 1 => _arg1, 2 => _arg2, 3 => _arg3, 4 => _arg4, _ => throw Error.ArgumentOutOfRange(nameof(index)), }; internal override bool SameExpressions(ICollection<Expression> expressions) { Debug.Assert(expressions != null); if (expressions.Count == 5) { ReadOnlyCollection<Expression> alreadyCollection = _arg0 as ReadOnlyCollection<Expression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(expressions, alreadyCollection); } using (IEnumerator<Expression> en = expressions.GetEnumerator()) { en.MoveNext(); if (en.Current == _arg0) { en.MoveNext(); if (en.Current == _arg1) { en.MoveNext(); if (en.Current == _arg2) { en.MoveNext(); if (en.Current == _arg3) { en.MoveNext(); return en.Current == _arg4; } } } } } } return false; } internal override int ExpressionCount => 5; internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 5); Debug.Assert(variables == null || variables.Count == 0); return new Block5(args[0], args[1], args[2], args[3], args[4]); } } internal class BlockN : BlockExpression { private IReadOnlyList<Expression> _expressions; // either the original IList<Expression> or a ReadOnlyCollection if the user has accessed it. internal BlockN(IReadOnlyList<Expression> expressions) { Debug.Assert(expressions.Count != 0); _expressions = expressions; } internal override bool SameExpressions(ICollection<Expression> expressions) => ExpressionUtils.SameElements(expressions, _expressions); internal override Expression GetExpression(int index) { Debug.Assert(index >= 0 && index < _expressions.Count); return _expressions[index]; } internal override int ExpressionCount => _expressions.Count; internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ExpressionUtils.ReturnReadOnly(ref _expressions); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(variables == null || variables.Count == 0); Debug.Assert(args != null); return new BlockN(args); } } internal class ScopeExpression : BlockExpression { private IReadOnlyList<ParameterExpression> _variables; // list of variables or ReadOnlyCollection if the user has accessed the read-only collection internal ScopeExpression(IReadOnlyList<ParameterExpression> variables) { _variables = variables; } internal override bool SameVariables(ICollection<ParameterExpression> variables) => ExpressionUtils.SameElements(variables, _variables); internal override ReadOnlyCollection<ParameterExpression> GetOrMakeVariables() { return ExpressionUtils.ReturnReadOnly(ref _variables); } protected IReadOnlyList<ParameterExpression> VariablesList => _variables; // Used for rewrite of the nodes to either reuse existing set of variables if not rewritten. internal IReadOnlyList<ParameterExpression> ReuseOrValidateVariables(ReadOnlyCollection<ParameterExpression> variables) { if (variables != null && variables != VariablesList) { // Need to validate the new variables (uniqueness, not byref) ValidateVariables(variables, nameof(variables)); return variables; } else { return VariablesList; } } } internal sealed class Scope1 : ScopeExpression { private object _body; internal Scope1(IReadOnlyList<ParameterExpression> variables, Expression body) : this(variables, (object)body) { } private Scope1(IReadOnlyList<ParameterExpression> variables, object body) : base(variables) { _body = body; } internal override bool SameExpressions(ICollection<Expression> expressions) { Debug.Assert(expressions != null); if (expressions.Count == 1) { ReadOnlyCollection<Expression> alreadyCollection = _body as ReadOnlyCollection<Expression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(expressions, alreadyCollection); } using (IEnumerator<Expression> en = expressions.GetEnumerator()) { en.MoveNext(); return ExpressionUtils.ReturnObject<Expression>(_body) == en.Current; } } return false; } internal override Expression GetExpression(int index) => index switch { 0 => ExpressionUtils.ReturnObject<Expression>(_body), _ => throw Error.ArgumentOutOfRange(nameof(index)), }; internal override int ExpressionCount => 1; internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _body); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { if (args == null) { Debug.Assert(variables.Count == Variables.Count); ValidateVariables(variables, nameof(variables)); return new Scope1(variables, _body); } Debug.Assert(args.Length == 1); Debug.Assert(variables == null || variables.Count == Variables.Count); return new Scope1(ReuseOrValidateVariables(variables), args[0]); } } internal class ScopeN : ScopeExpression { private IReadOnlyList<Expression> _body; internal ScopeN(IReadOnlyList<ParameterExpression> variables, IReadOnlyList<Expression> body) : base(variables) { _body = body; } internal override bool SameExpressions(ICollection<Expression> expressions) => ExpressionUtils.SameElements(expressions, _body); protected IReadOnlyList<Expression> Body => _body; internal override Expression GetExpression(int index) => _body[index]; internal override int ExpressionCount => _body.Count; internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ExpressionUtils.ReturnReadOnly(ref _body); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { if (args == null) { Debug.Assert(variables.Count == Variables.Count); ValidateVariables(variables, nameof(variables)); return new ScopeN(variables, _body); } Debug.Assert(args.Length == ExpressionCount); Debug.Assert(variables == null || variables.Count == Variables.Count); return new ScopeN(ReuseOrValidateVariables(variables), args); } } internal sealed class ScopeWithType : ScopeN { internal ScopeWithType(IReadOnlyList<ParameterExpression> variables, IReadOnlyList<Expression> expressions, Type type) : base(variables, expressions) { Type = type; } public sealed override Type Type { get; } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { if (args == null) { Debug.Assert(variables.Count == Variables.Count); ValidateVariables(variables, nameof(variables)); return new ScopeWithType(variables, Body, Type); } Debug.Assert(args.Length == ExpressionCount); Debug.Assert(variables == null || variables.Count == Variables.Count); return new ScopeWithType(ReuseOrValidateVariables(variables), args, Type); } } #endregion #region Block List Classes /// <summary> /// Provides a wrapper around an IArgumentProvider which exposes the argument providers /// members out as an IList of Expression. This is used to avoid allocating an array /// which needs to be stored inside of a ReadOnlyCollection. Instead this type has /// the same amount of overhead as an array without duplicating the storage of the /// elements. This ensures that internally we can avoid creating and copying arrays /// while users of the Expression trees also don't pay a size penalty for this internal /// optimization. See IArgumentProvider for more general information on the Expression /// tree optimizations being used here. /// </summary> internal class BlockExpressionList : IList<Expression> { private readonly BlockExpression _block; private readonly Expression _arg0; internal BlockExpressionList(BlockExpression provider, Expression arg0) { _block = provider; _arg0 = arg0; } #region IList<Expression> Members public int IndexOf(Expression item) { if (_arg0 == item) { return 0; } for (int i = 1; i < _block.ExpressionCount; i++) { if (_block.GetExpression(i) == item) { return i; } } return -1; } [ExcludeFromCodeCoverage] // Unreachable public void Insert(int index, Expression item) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable public void RemoveAt(int index) { throw ContractUtils.Unreachable; } public Expression this[int index] { get { if (index == 0) { return _arg0; } return _block.GetExpression(index); } [ExcludeFromCodeCoverage] // Unreachable set { throw ContractUtils.Unreachable; } } #endregion #region ICollection<Expression> Members [ExcludeFromCodeCoverage] // Unreachable public void Add(Expression item) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable public void Clear() { throw ContractUtils.Unreachable; } public bool Contains(Expression item) { return IndexOf(item) != -1; } public void CopyTo(Expression[] array, int index) { ContractUtils.RequiresNotNull(array, nameof(array)); if (index < 0) { throw Error.ArgumentOutOfRange(nameof(index)); } int n = _block.ExpressionCount; Debug.Assert(n > 0); if (index + n > array.Length) { throw new ArgumentException(); } array[index++] = _arg0; for (int i = 1; i < n; i++) { array[index++] = _block.GetExpression(i); } } public int Count => _block.ExpressionCount; [ExcludeFromCodeCoverage] // Unreachable public bool IsReadOnly { get { throw ContractUtils.Unreachable; } } [ExcludeFromCodeCoverage] // Unreachable public bool Remove(Expression item) { throw ContractUtils.Unreachable; } #endregion #region IEnumerable<Expression> Members public IEnumerator<Expression> GetEnumerator() { yield return _arg0; for (int i = 1; i < _block.ExpressionCount; i++) { yield return _block.GetExpression(i); } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } #endregion public partial class Expression { /// <summary> /// Creates a <see cref="BlockExpression"/> that contains two expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1) { ExpressionUtils.RequiresCanRead(arg0, nameof(arg0)); ExpressionUtils.RequiresCanRead(arg1, nameof(arg1)); return new Block2(arg0, arg1); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains three expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2) { ExpressionUtils.RequiresCanRead(arg0, nameof(arg0)); ExpressionUtils.RequiresCanRead(arg1, nameof(arg1)); ExpressionUtils.RequiresCanRead(arg2, nameof(arg2)); return new Block3(arg0, arg1, arg2); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains four expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <param name="arg3">The fourth expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3) { ExpressionUtils.RequiresCanRead(arg0, nameof(arg0)); ExpressionUtils.RequiresCanRead(arg1, nameof(arg1)); ExpressionUtils.RequiresCanRead(arg2, nameof(arg2)); ExpressionUtils.RequiresCanRead(arg3, nameof(arg3)); return new Block4(arg0, arg1, arg2, arg3); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains five expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <param name="arg3">The fourth expression in the block.</param> /// <param name="arg4">The fifth expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { ExpressionUtils.RequiresCanRead(arg0, nameof(arg0)); ExpressionUtils.RequiresCanRead(arg1, nameof(arg1)); ExpressionUtils.RequiresCanRead(arg2, nameof(arg2)); ExpressionUtils.RequiresCanRead(arg3, nameof(arg3)); ExpressionUtils.RequiresCanRead(arg4, nameof(arg4)); return new Block5(arg0, arg1, arg2, arg3, arg4); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables. /// </summary> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(params Expression[] expressions) { ContractUtils.RequiresNotNull(expressions, nameof(expressions)); RequiresCanRead(expressions, nameof(expressions)); return GetOptimizedBlockExpression(expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables. /// </summary> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<Expression> expressions) { return Block(EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, params Expression[] expressions) { ContractUtils.RequiresNotNull(expressions, nameof(expressions)); return Block(type, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<Expression> expressions) { return Block(type, EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<ParameterExpression> variables, params Expression[] expressions) { return Block(variables, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, params Expression[] expressions) { return Block(type, variables, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { ContractUtils.RequiresNotNull(expressions, nameof(expressions)); ReadOnlyCollection<ParameterExpression> variableList = variables.ToReadOnly(); if (variableList.Count == 0) { IReadOnlyList<Expression> expressionList = expressions as IReadOnlyList<Expression> ?? expressions.ToReadOnly(); RequiresCanRead(expressionList, nameof(expressions)); return GetOptimizedBlockExpression(expressionList); } else { ReadOnlyCollection<Expression> expressionList = expressions.ToReadOnly(); RequiresCanRead(expressionList, nameof(expressions)); return BlockCore(null, variableList, expressionList); } } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(expressions, nameof(expressions)); ReadOnlyCollection<Expression> expressionList = expressions.ToReadOnly(); RequiresCanRead(expressionList, nameof(expressions)); ReadOnlyCollection<ParameterExpression> variableList = variables.ToReadOnly(); if (variableList.Count == 0 && expressionList.Count != 0) { int expressionCount = expressionList.Count; if (expressionCount != 0) { Expression lastExpression = expressionList[expressionCount - 1]; if (lastExpression.Type == type) { return GetOptimizedBlockExpression(expressionList); } } } return BlockCore(type, variableList, expressionList); } private static BlockExpression BlockCore(Type type, ReadOnlyCollection<ParameterExpression> variables, ReadOnlyCollection<Expression> expressions) { ValidateVariables(variables, nameof(variables)); if (type != null) { if (expressions.Count == 0) { if (type != typeof(void)) { throw Error.ArgumentTypesMustMatch(); } return new ScopeWithType(variables, expressions, type); } Expression last = expressions.Last(); if (type != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(type, last.Type)) { throw Error.ArgumentTypesMustMatch(); } } if (!TypeUtils.AreEquivalent(type, last.Type)) { return new ScopeWithType(variables, expressions, type); } } return expressions.Count switch { 0 => new ScopeWithType(variables, expressions, typeof(void)), 1 => new Scope1(variables, expressions[0]), _ => new ScopeN(variables, expressions), }; } // Checks that all variables are non-null, not byref, and unique. internal static void ValidateVariables(ReadOnlyCollection<ParameterExpression> varList, string collectionName) { int count = varList.Count; if (count != 0) { var set = new HashSet<ParameterExpression>(); for (int i = 0; i < count; i++) { ParameterExpression v = varList[i]; ContractUtils.RequiresNotNull(v, collectionName, i); if (v.IsByRef) { throw Error.VariableMustNotBeByRef(v, v.Type, collectionName, i); } if (!set.Add(v)) { throw Error.DuplicateVariable(v, collectionName, i); } } } } private static BlockExpression GetOptimizedBlockExpression(IReadOnlyList<Expression> expressions) { return expressions.Count switch { 0 => BlockCore(typeof(void), EmptyReadOnlyCollection<ParameterExpression>.Instance, EmptyReadOnlyCollection<Expression>.Instance), 2 => new Block2(expressions[0], expressions[1]), 3 => new Block3(expressions[0], expressions[1], expressions[2]), 4 => new Block4(expressions[0], expressions[1], expressions[2], expressions[3]), 5 => new Block5(expressions[0], expressions[1], expressions[2], expressions[3], expressions[4]), _ => new BlockN(expressions as ReadOnlyCollection<Expression> ?? (IReadOnlyList<Expression>)expressions.ToArray()), }; } } }
// 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; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class AddStrStrStringDictionaryTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; StringDictionary sd; // simple string values string[] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "one", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count string ind; // key // initialize IntStrings intl = new IntlStrings(); // [] StringDictionary is constructed as expected //----------------------------------------------------------------- sd = new StringDictionary(); // [] Add() simple strings // for (int i = 0; i < values.Length; i++) { cnt = sd.Count; sd.Add(keys[i], values[i]); if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1)); } // verify that collection contains newly added item // if (!sd.ContainsValue(values[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i)); } if (!sd.ContainsKey(keys[i])) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // access the item // if (String.Compare(sd[keys[i]], values[i]) != 0) { Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[keys[i]], values[i])); } } // // Intl strings // [] Add() Intl strings // int len = values.Length; string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant()) caseInsensitive = true; } // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = sd.Count; sd.Add(intlValues[i + len], intlValues[i]); if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1)); } // verify that collection contains newly added item // if (!sd.ContainsValue(intlValues[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i)); } if (!sd.ContainsKey(intlValues[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // access the item // ind = intlValues[i + len]; if (String.Compare(sd[ind], intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i])); } } // // [] Case sensitivity // string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpperInvariant(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLowerInvariant(); } sd.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = sd.Count; sd.Add(intlValues[i + len], intlValues[i]); if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1)); } // verify that collection contains newly added uppercase item // if (!sd.ContainsValue(intlValues[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i)); } if (!sd.ContainsKey(intlValues[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // verify that collection doesn't contains lowercase item // if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i])) { Assert.False(true, string.Format("Error, collection contains lowercase value of new item", i)); } // key is case insensitive if (!sd.ContainsKey(intlValuesLower[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain lowercase key of new item", i)); } } // // [] Add (string, null) // cnt = sd.Count; sd.Add("keykey", null); if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, cnt + 1)); } // verify that collection contains null // if (!sd.ContainsValue(null)) { Assert.False(true, string.Format("Error, collection doesn't contain null")); } // access item-null // if (sd["keykey"] != null) { Assert.False(true, string.Format("Error, returned non-null on place of null")); } // // Add item with null key - ArgumentNullException expected // [] Add (null, string) // Assert.Throws<ArgumentNullException>(() => { sd.Add(null, "item"); }); // // Add duplicate key item - ArgumentException expected // [] Add duplicate key item // // generate key string k = intl.GetRandomString(MAX_LEN); if (!sd.ContainsKey(k)) { sd.Add(k, "newItem"); } if (!sd.ContainsKey(k)) { Assert.False(true, string.Format("Error,failed to add item")); } else { Assert.Throws<ArgumentException>(() => { sd.Add(k, "itemitemitem"); }); } } } }
using Signum.Utilities.DataStructures; using Signum.Utilities.ExpressionTrees; using Signum.Utilities.Reflection; using Signum.Utilities.Synchronization; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Data; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace Signum.Utilities { public static class EnumerableUniqueExtensions { class UniqueExExpander : IMethodExpander { static MethodInfo miWhereE = ReflectionTools.GetMethodInfo(() => Enumerable.Where<int>(null, a => false)).GetGenericMethodDefinition(); static MethodInfo miWhereQ = ReflectionTools.GetMethodInfo(() => Queryable.Where<int>(null, a => false)).GetGenericMethodDefinition(); public Expression Expand(Expression instance, Expression[] arguments, MethodInfo mi) { bool query = mi.GetParameters()[0].ParameterType.IsInstantiationOf(typeof(IQueryable<>)); var whereMi = (query ? miWhereQ : miWhereE).MakeGenericMethod(mi.GetGenericArguments()); var whereExpr = Expression.Call(whereMi, arguments[0], arguments[1]); var uniqueMi = mi.DeclaringType!.GetMethods().SingleEx(m => m.Name == mi.Name && m.IsGenericMethod && m.GetParameters().Length == (mi.GetParameters().Length - 1)); return Expression.Call(uniqueMi.MakeGenericMethod(mi.GetGenericArguments()), whereExpr); } } /// <summary> /// Returns the single Element from a collections satisfying a predicate, or throws an Exception /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection">the collection to search</param> /// <param name="predicate">the predicate</param> /// <returns>the single Element from the collection satisfying the predicate.</returns> [MethodExpander(typeof(UniqueExExpander))] public static T SingleEx<T>(this IEnumerable<T> collection, Func<T, bool> predicate) { if (collection == null) throw new ArgumentNullException(nameof(collection)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); T result = default(T)!; bool found = false; foreach (T item in collection) { if (predicate(item)) { if (found) throw new InvalidOperationException("Sequence contains more than one {0}".FormatWith(typeof(T).TypeName())); result = item; found = true; } } if (found) return result; throw new InvalidOperationException("Sequence contains no {0}".FormatWith(typeof(T).TypeName())); } [MethodExpander(typeof(UniqueExExpander))] public static T SingleEx<T>(this IQueryable<T> query, Expression<Func<T, bool>> predicate) { return query.Where(predicate).SingleEx(); } /// <summary> /// Returns the single Object from the collection or throws an Exception /// </summary> /// <typeparam name="T">Type of the collection</typeparam> /// <param name="collection">The collection to search</param> /// <returns>The single Element from the collection</returns> public static T SingleEx<T>(this IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) throw new InvalidOperationException("Sequence contains no {0}".FormatWith(typeof(T).TypeName())); T current = enumerator.Current; if (!enumerator.MoveNext()) return current; } throw new InvalidOperationException("Sequence contains more than one {0}".FormatWith(typeof(T).TypeName())); } /// <summary> /// Returns the single Object from the collection or throws an Exception /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection"></param> /// <param name="elementName"></param> /// <param name="forEndUser"></param> /// <returns></returns> public static T SingleEx<T>(this IEnumerable<T> collection, Func<string> elementName, bool forEndUser = false) { return collection.SingleEx( () => forEndUser ? CollectionMessage.No0Found.NiceToString(elementName()) : "Sequence contains no {0}".FormatWith(elementName()), () => forEndUser ? CollectionMessage.MoreThanOne0Found.NiceToString(elementName()) : "Sequence contains more than one {0}".FormatWith(elementName()), forEndUser); } /// <summary> /// Returns the single Object from the collection or throws an Exception /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection"></param> /// <param name="errorZero">The Message if there is no Element</param> /// <param name="errorMoreThanOne">The Message if there is more than one Element</param> /// <param name="forEndUser"></param> /// <returns></returns> public static T SingleEx<T>(this IEnumerable<T> collection, Func<string> errorZero, Func<string> errorMoreThanOne, bool forEndUser = false) { if (collection == null) throw new ArgumentNullException(nameof(collection)); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) throw NewException(forEndUser, errorZero()); T current = enumerator.Current; if (!enumerator.MoveNext()) return current; } throw NewException(forEndUser, errorMoreThanOne()); } static Exception NewException(bool forEndUser, string message) { if (forEndUser) return new ApplicationException(message); else return new InvalidOperationException(message); } [MethodExpander(typeof(UniqueExExpander))] [return: MaybeNull] public static T SingleOrDefaultEx<T>(this IEnumerable<T> collection, Func<T, bool> predicate) { if (collection == null) throw new ArgumentNullException(nameof(collection)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); T result = default(T)!; bool found = false; foreach (T item in collection) { if (predicate(item)) { if (found) throw new InvalidOperationException("Sequence contains more than one {0}".FormatWith(typeof(T).TypeName())); result = item; found = true; } } return result; } [MethodExpander(typeof(UniqueExExpander))] [return: MaybeNull] public static T SingleOrDefaultEx<T>(this IQueryable<T> query, Expression<Func<T, bool>> predicate) { return query.Where(predicate).SingleOrDefaultEx(); } [return: MaybeNull] public static T SingleOrDefaultEx<T>(this IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) return default(T)!; T current = enumerator.Current; if (!enumerator.MoveNext()) return current; } throw new InvalidOperationException("Sequence contains more than one {0}".FormatWith(typeof(T).TypeName())); } [return: MaybeNull] public static T SingleOrDefaultEx<T>(this IEnumerable<T> collection, Func<string> errorMoreThanOne, bool forEndUser = false) { if (collection == null) throw new ArgumentNullException(nameof(collection)); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) return default(T)!; T current = enumerator.Current; if (!enumerator.MoveNext()) return current; } throw NewException(forEndUser, errorMoreThanOne()); } [MethodExpander(typeof(UniqueExExpander))] public static T FirstEx<T>(this IEnumerable<T> collection, Func<T, bool> predicate) { if (collection == null) throw new ArgumentNullException(nameof(collection)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); foreach (T item in collection) { if (predicate(item)) return item; } throw new InvalidOperationException("Sequence contains no {0}".FormatWith(typeof(T).TypeName())); } [MethodExpander(typeof(UniqueExExpander))] public static T FirstEx<T>(this IQueryable<T> query, Expression<Func<T, bool>> predicate) { return query.Where(predicate).FirstEx(); } public static T FirstEx<T>(this IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) throw new InvalidOperationException("Sequence contains no {0}".FormatWith(typeof(T).TypeName())); return enumerator.Current; } } public static T FirstEx<T>(this IEnumerable<T> collection, Func<string> errorZero, bool forEndUser = false) { if (collection == null) throw new ArgumentNullException(nameof(collection)); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) throw NewException(forEndUser, errorZero()); return enumerator.Current; } } [MethodExpander(typeof(UniqueExExpander))] [return: MaybeNull] public static T SingleOrManyEx<T>(this IEnumerable<T> collection, Func<T, bool> predicate) { return collection.Where(predicate).FirstEx(); } [MethodExpander(typeof(UniqueExExpander))] [return: MaybeNull] public static T SingleOrManyEx<T>(this IQueryable<T> query, Expression<Func<T, bool>> predicate) { return query.Where(predicate).FirstEx(); } [return: MaybeNull] public static T SingleOrManyEx<T>(this IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) throw new InvalidOperationException("Sequence contains no {0}".FormatWith(typeof(T).TypeName())); T current = enumerator.Current; if (enumerator.MoveNext()) return default(T)!; return current; } } [return: MaybeNull] public static T SingleOrManyEx<T>(this IEnumerable<T> collection, Func<string> errorZero, bool forEndUser = false) { if (collection == null) throw new ArgumentNullException(nameof(collection)); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) throw NewException(forEndUser, errorZero()); T current = enumerator.Current; if (enumerator.MoveNext()) return default(T)!; return current; } } //returns default if 0 or many, returns if one [return: MaybeNull] public static T Only<T>(this IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) return default(T)!; T current = enumerator.Current; if (enumerator.MoveNext()) return default(T)!; return current; } } } public static class EnumerableExtensions { public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T>? collection) { if (collection == null) return Enumerable.Empty<T>(); return collection; } [MethodExpander(typeof(IsEmptyExpander))] public static bool IsEmpty<T>(this IEnumerable<T> collection) { foreach (var item in collection) return false; return true; } class IsEmptyExpander : IMethodExpander { static readonly MethodInfo miAny = ReflectionTools.GetMethodInfo((int[] a) => a.Any()).GetGenericMethodDefinition(); public Expression Expand(Expression instance, Expression[] arguments, MethodInfo mi) { return Expression.Not(Expression.Call(miAny.MakeGenericMethod(mi.GetGenericArguments()), arguments)); } } public static bool IsNullOrEmpty<T>([NotNullWhen(false)]this IEnumerable<T>? collection) { return collection == null || collection.IsEmpty(); } public static bool HasItems<T>([NotNullWhen(true)]this IEnumerable<T>? collection) { return collection != null && collection.Any(); } public static IEnumerable<T> NotNull<T>(this IEnumerable<T?> collection) where T : class { foreach (var item in collection) { if (item != null) yield return item; } } public static IEnumerable<T> NotNull<T>(this IEnumerable<T?> collection) where T : struct { foreach (var item in collection) { if (item.HasValue) yield return item.Value; } } public static IEnumerable<T> And<T>(this IEnumerable<T> collection, T newItem) { foreach (var item in collection) yield return item; yield return newItem; } public static IEnumerable<T> PreAnd<T>(this IEnumerable<T> collection, T newItem) { yield return newItem; foreach (var item in collection) yield return item; } public static int IndexOf<T>(this IEnumerable<T> collection, T item) { int i = 0; foreach (var val in collection) { if (EqualityComparer<T>.Default.Equals(item, val)) return i; i++; } return -1; } public static int IndexOf<T>(this IEnumerable<T> collection, Func<T, bool> condition) { int i = 0; foreach (var val in collection) { if (condition(val)) return i; i++; } return -1; } public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> collection, Random rng) { T[] elements = collection.ToArray(); for (int i = elements.Length - 1; i > 0; i--) { int rnd = rng.Next(i + 1); yield return elements[rnd]; elements[rnd] = elements[i]; } yield return elements[0]; } public static string ToString<T>(this IEnumerable<T> source, string separator) { StringBuilder? sb = null; foreach (var item in source) { if (sb == null) sb = new StringBuilder(); else sb.Append(separator); sb.Append(item?.ToString()); } if (sb == null) return ""; return sb.ToString(); // Remove at the end is faster } public static string ToString<T>(this IEnumerable<T> source, Func<T, string?> toString, string separator) { StringBuilder? sb = null; foreach (var item in source) { if (sb == null) sb = new StringBuilder(); else sb.Append(separator); sb.Append(toString(item)); } if (sb == null) return ""; return sb.ToString(); // Remove at the end is faster } public static string ToString<T>(this IQueryable<T> source, Expression<Func<T, string?>> toString, string separator) { return source.Select(toString).ToString(separator); } public static string CommaAnd<T>(this IEnumerable<T> collection) { return CommaString(collection.Select(a => a!.ToString()).ToArray(), CollectionMessage.And.NiceToString()); } public static string CommaAnd<T>(this IEnumerable<T> collection, Func<T, string?> toString) { return CommaString(collection.Select(toString).ToArray(), CollectionMessage.And.NiceToString()); } public static string CommaOr<T>(this IEnumerable<T> collection) { return CommaString(collection.Select(a => a?.ToString()).ToArray(), CollectionMessage.Or.NiceToString()); } public static string CommaOr<T>(this IEnumerable<T> collection, Func<T, string?> toString) { return CommaString(collection.Select(toString).ToArray(), CollectionMessage.Or.NiceToString()); } public static string Comma<T>(this IEnumerable<T> collection, string lastSeparator) { return CommaString(collection.Select(a => a!.ToString()).ToArray(), lastSeparator); } public static string Comma<T>(this IEnumerable<T> collection, Func<T, string> toString, string lastSeparator) { return CommaString(collection.Select(toString).ToArray(), lastSeparator); } static string CommaString(this string?[] values, string lastSeparator) { if (values.Length == 0) return ""; StringBuilder sb = new StringBuilder(); sb.Append(values[0]); for (int i = 1; i < values.Length - 1; i++) { sb.Append(", "); sb.Append(values[i]); } if (values.Length > 1) { sb.Append(lastSeparator); sb.Append(values[values.Length - 1]); } return sb.ToString(); } public static void ToConsole<T>(this IEnumerable<T> collection) { ToConsole(collection, a => a!.ToString()!); } public static void ToConsole<T>(this IEnumerable<T> collection, Func<T, string> toString) { foreach (var item in collection) Console.WriteLine(toString(item)); } public static void ToFile(this IEnumerable<string> collection, string fileName) { using (FileStream fs = File.Create(fileName)) using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) { foreach (var item in collection) sw.WriteLine(item); } } public static void ToFile<T>(this IEnumerable<T> collection, Func<T, string> toString, string fileName) { collection.Select(toString).ToFile(fileName); } public static DataTable ToDataTable<T>(this IEnumerable<T> collection, bool withDescriptions = false) { DataTable table = new DataTable(); List<MemberEntry<T>> members = MemberEntryFactory.GenerateList<T>(); foreach (var m in members) { var name = withDescriptions ? m.MemberInfo.GetCustomAttribute<DescriptionAttribute>()?.Description ?? m.Name : m.Name; var type = m.MemberInfo.ReturningType().UnNullify(); table.Columns.Add(name, type); } foreach (var e in collection) table.Rows.Add(members.Select(m => m.Getter!(e)).ToArray()); return table; } public static DataTable Transpose(this DataTable table, string captionName = "") { DataTable result = new DataTable(); result.Columns.Add(new DataColumn("Column", typeof(string)) { Caption = captionName}); var list = table.Columns.Cast<DataColumn>().Skip(1).Select(a => a.DataType).Distinct().ToList(); var bestCommon = BetsCommonType(list); foreach (var row in table.Rows.Cast<DataRow>()) { result.Columns.Add(new DataColumn(row[0]?.ToString(), bestCommon)); } foreach (var col in table.Columns.Cast<DataColumn>().Skip(1)) { var array = table.Rows.Cast<DataRow>().Select(dr => dr[col]).Cast<object>().ToArray(); result.Rows.Add(array.PreAnd(col.ColumnName).ToArray()); } return result; } static Type BetsCommonType(List<Type> list) { if (list.Count == 1) return list.Single(); return typeof(string); } #region String Tables public static string[,] ToStringTable<T>(this IEnumerable<T> collection) { List<MemberEntry<T>> members = MemberEntryFactory.GenerateList<T>(); string[,] result = new string[members.Count, collection.Count() + 1]; for (int i = 0; i < members.Count; i++) result[i, 0] = members[i].Name; int j = 1; foreach (var item in collection) { for (int i = 0; i < members.Count; i++) result[i, j] = members[i].Getter!(item)?.ToString() ?? ""; j++; } return result; } public static string[,] ToStringTable(this DataTable table) { string[,] result = new string[table.Columns.Count, table.Rows.Count + 1]; for (int i = 0; i < table.Columns.Count; i++) result[i, 0] = table.Columns[i].ColumnName; int j = 1; foreach (DataRow? row in table.Rows) { for (int i = 0; i < table.Columns.Count; i++) result[i, j] = row![i]?.ToString() ?? ""; j++; } return result; } public static string FormatTable(this string[,] table, bool longHeaders = true, string separator = " ") { int width = table.GetLength(0); int height = table.GetLength(1); int start = height == 1 ? 0 : (longHeaders ? 0 : 1); int[] lengths = 0.To(width).Select(i => Math.Max(3, start.To(height).Max(j => table[i, j].Length))).ToArray(); return 0.To(height).Select(j => 0.To(width).ToString(i => table[i, j].PadChopRight(lengths[i]), separator)).ToString("\r\n"); } public static void WriteFormattedStringTable<T>(this IEnumerable<T> collection, TextWriter textWriter, string? title, bool longHeaders) { textWriter.WriteLine(); if (title.HasText()) textWriter.WriteLine(title!); textWriter.WriteLine(collection.ToStringTable().FormatTable(longHeaders)); textWriter.WriteLine(); } public static void ToConsoleTable<T>(this IEnumerable<T> collection, string? title = null, bool longHeader = false) { collection.WriteFormattedStringTable(Console.Out, title, longHeader); } public static string ToFormattedTable<T>(this IEnumerable<T> collection, string? title = null, bool longHeader = false) { StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) collection.WriteFormattedStringTable(sw, title, longHeader); return sb.ToString(); } #endregion #region Min Max public static T WithMin<T, V>(this IEnumerable<T> collection, Func<T, V> valueSelector) where V : IComparable<V> { T result = default(T)!; bool hasMin = false; V min = default(V)!; foreach (var item in collection) { V val = valueSelector(item); if (!hasMin || val.CompareTo(min) < 0) { hasMin = true; min = val; result = item; } } return result; } public static T WithMax<T, V>(this IEnumerable<T> collection, Func<T, V> valueSelector) where V : IComparable<V> { T result = default(T)!; bool hasMax = false; V max = default(V)!; foreach (var item in collection) { V val = valueSelector(item); if (!hasMax || val.CompareTo(max) > 0) { hasMax = true; max = val; result = item; } } return result; } public static List<T> WithMinList<T, V>(this IEnumerable<T> collection, Func<T, V> valueSelector) where V : IComparable<V> { List<T> result = new List<T>(); V min = default(V)!; foreach (var item in collection) { V val = valueSelector(item); int comp = 0; if (result.Count == 0 || (comp = val.CompareTo(min)) <= 0) { if (comp < 0) result.Clear(); result.Add(item); min = val; } } return result; } public static List<T> WithMaxList<T, V>(this IEnumerable<T> collection, Func<T, V> valueSelector) where V : IComparable<V> { List<T> result = new List<T>(); V max = default(V)!; foreach (var item in collection) { V val = valueSelector(item); int comp = 0; if (result.Count == 0 || (comp = val.CompareTo(max)) >= 0) { if (comp > 0) result.Clear(); result.Add(item); max = val; } } return result; } public static MinMax<T> WithMinMaxPair<T, V>(this IEnumerable<T> collection, Func<T, V> valueSelector) where V : IComparable<V> { T withMin = default(T)!, withMax = default(T)!; bool hasMin = false, hasMax = false; V min = default(V)!, max = default(V)!; foreach (var item in collection) { V val = valueSelector(item); if (!hasMax || val.CompareTo(max) > 0) { hasMax = true; max = val; withMax = item; } if (!hasMin || val.CompareTo(min) < 0) { hasMin = true; min = val; withMin = item; } } return new MinMax<T>(withMin, withMax); } public static Interval<T> ToInterval<T>(this IEnumerable<T> collection) where T : struct, IComparable<T>, IEquatable<T> { bool has = false; T min = default(T), max = default(T); foreach (var item in collection) { if (!has) { has = true; min = max = item; } else { if (item.CompareTo(max) > 0) max = item; if (item.CompareTo(min) < 0) min = item; } } return new Interval<T>(min, max); } public static Interval<V> ToInterval<T, V>(this IEnumerable<T> collection, Func<T, V> valueSelector) where V : struct, IComparable<V>, IEquatable<V> { bool has = false; V min = default(V), max = default(V); foreach (var item in collection) { V val = valueSelector(item); if (!has) { has = true; min = max = val; } else { if (val.CompareTo(max) > 0) max = val; if (val.CompareTo(min) < 0) min = val; } } return new Interval<V>(min, max); } #endregion #region Operation public static IEnumerable<T> Concat<T>(params IEnumerable<T>[] collections) { foreach (var collection in collections) { foreach (var item in collection) { yield return item; } } } public static IEnumerable<S> BiSelectC<T, S>(this IEnumerable<T> collection, Func<T?, T?, S> func, BiSelectOptions options = BiSelectOptions.None) where T : class { using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) yield break; T firstItem = enumerator.Current; if (options == BiSelectOptions.Initial || options == BiSelectOptions.InitialAndFinal) yield return func(null, firstItem); T lastItem = firstItem; while (enumerator.MoveNext()) { T item = enumerator.Current; yield return func(lastItem, item); lastItem = item; } if (options == BiSelectOptions.Final || options == BiSelectOptions.InitialAndFinal) yield return func(lastItem, null); if (options == BiSelectOptions.Circular) yield return func(lastItem, firstItem); } } public static IEnumerable<S> BiSelectS<T, S>(this IEnumerable<T> collection, Func<T?, T?, S> func, BiSelectOptions options = BiSelectOptions.None) where T : struct { using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) yield break; T firstItem = enumerator.Current; if (options == BiSelectOptions.Initial || options == BiSelectOptions.InitialAndFinal) yield return func(null, firstItem); T lastItem = firstItem; while (enumerator.MoveNext()) { T item = enumerator.Current; yield return func(lastItem, item); lastItem = item; } if (options == BiSelectOptions.Final || options == BiSelectOptions.InitialAndFinal) yield return func(lastItem, null); if (options == BiSelectOptions.Circular) yield return func(lastItem, firstItem); } } //return one element more public static IEnumerable<S> SelectAggregate<T, S>(this IEnumerable<T> collection, S seed, Func<S, T, S> aggregate) { yield return seed; foreach (var item in collection) { seed = aggregate(seed, item); yield return seed; } } public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) where T : notnull { IEnumerable<ImmutableStack<T>> emptyProduct = new[] { ImmutableStack<T>.Empty }; var result = sequences.Aggregate( emptyProduct, (accumulator, sequence) => from accseq in accumulator from item in sequence select accseq.Push(item)); return result.Select(a => a.Reverse()); } public static IEnumerable<T> Distinct<T, S>(this IEnumerable<T> collection, Func<T, S> func) { return collection.Distinct(new LambdaComparer<T, S>(func)); } public static IEnumerable<T> Distinct<T, S>(this IEnumerable<T> collection, Func<T, S> func, IEqualityComparer<S> comparer) { return collection.Distinct(new LambdaComparer<T, S>(func, comparer, null)); } public static IEnumerable<T> Slice<T>(this IEnumerable<T> collection, int firstIncluded, int toNotIncluded) { return collection.Skip(firstIncluded).Take(toNotIncluded - firstIncluded); } public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> collection) where T : IComparable<T> { return collection.OrderBy(a => a); } public static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> collection) where T : IComparable<T> { return collection.OrderByDescending(a => a); } #endregion #region Zip public static IEnumerable<R> ZipOrDefault<A, B, R>(this IEnumerable<A> colA, IEnumerable<B> colB, Func<A, B, R> resultSelector) { bool okA = true, okB = true; using (var enumA = colA.GetEnumerator()) using (var enumB = colB.GetEnumerator()) { while (okA & (okA = enumA.MoveNext()) | okB & (okB = enumB.MoveNext())) { yield return resultSelector( okA ? enumA.Current : default(A)!, okB ? enumB.Current : default(B)!); } } } public static IEnumerable<(A first, B second)> ZipOrDefault<A, B>(this IEnumerable<A> colA, IEnumerable<B> colB) { bool okA = true, okB = true; using (var enumA = colA.GetEnumerator()) using (var enumB = colB.GetEnumerator()) { while ((okA &= enumA.MoveNext()) || (okB &= enumB.MoveNext())) { var first = okA ? enumA.Current : default(A)!; var second = okB ? enumB.Current : default(B)!; yield return (first, second); } } } public static void ZipForeach<A, B>(this IEnumerable<A> colA, IEnumerable<B> colB, Action<A, B> actions) { using (var enumA = colA.GetEnumerator()) using (var enumB = colB.GetEnumerator()) { while (enumA.MoveNext() && enumB.MoveNext()) { actions(enumA.Current, enumB.Current); } } } public static IEnumerable<(A first, B second)> ZipStrict<A, B>(this IEnumerable<A> colA, IEnumerable<B> colB) { using (var enumA = colA.GetEnumerator()) using (var enumB = colB.GetEnumerator()) { while (AssertoTwo(enumA.MoveNext(), enumB.MoveNext())) { yield return (first: enumA.Current, second: enumB.Current); } } } public static IEnumerable<R> ZipStrict<A, B, R>(this IEnumerable<A> colA, IEnumerable<B> colB, Func<A, B, R> mixer) { colA.Zip(colB, (a, b) => a); using (var enumA = colA.GetEnumerator()) using (var enumB = colB.GetEnumerator()) { while (AssertoTwo(enumA.MoveNext(), enumB.MoveNext())) { yield return mixer(enumA.Current, enumB.Current); } } } public static void ZipForeachStrict<A, B>(this IEnumerable<A> colA, IEnumerable<B> colB, Action<A, B> action) { using (var enumA = colA.GetEnumerator()) using (var enumB = colB.GetEnumerator()) { while (AssertoTwo(enumA.MoveNext(), enumB.MoveNext())) { action(enumA.Current, enumB.Current); } } } static bool AssertoTwo(bool nextA, bool nextB) { if (nextA != nextB) if (nextA) throw new InvalidOperationException("Second collection is shorter"); else throw new InvalidOperationException("First collection is shorter"); else return nextA; } #endregion #region Conversions public static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T>? collection) { return collection == null ? EmptyReadOnlyCollection<T>.Instance : collection as ReadOnlyCollection<T> ?? (collection as List<T> ?? collection.ToList()).AsReadOnly(); } static class EmptyReadOnlyCollection<T> { internal static ReadOnlyCollection<T> Instance; static EmptyReadOnlyCollection() { EmptyReadOnlyCollection<T>.Instance = new ReadOnlyCollection<T>(new T[0]); } } public static ReadOnlyDictionary<K, V> ToReadOnly<K, V>(this IDictionary<K, V> dictionary) where K: notnull { return dictionary == null ? EmptyReadOnlyDictionary<K, V>.Instance : dictionary as ReadOnlyDictionary<K, V> ?? new ReadOnlyDictionary<K, V>(dictionary); } static class EmptyReadOnlyDictionary<K, V> where K :notnull { internal static ReadOnlyDictionary<K, V> Instance; static EmptyReadOnlyDictionary() { EmptyReadOnlyDictionary<K, V>.Instance = new ReadOnlyDictionary<K, V>(new Dictionary<K, V>()); } } public static ObservableCollection<T>? ToObservableCollection<T>(this IEnumerable<T>? collection) { return collection == null ? null : collection as ObservableCollection<T> ?? new ObservableCollection<T>(collection); } public static IEnumerable<T> AsThreadSafe<T>(this IEnumerable<T> source) { return new TreadSafeEnumerator<T>(source); } public static IEnumerable<T> ToProgressEnumerator<T>(this IEnumerable<T> source, out IProgressInfo pi) { pi = new ProgressEnumerator<T>(source, source.Count()); return (IEnumerable<T>)pi; } public static void PushRange<T>(this Stack<T> stack, IEnumerable<T> elements) { foreach (var item in elements) stack.Push(item); } public static void EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> elements) { foreach (var item in elements) queue.Enqueue(item); } public static void AddRange<T>(this HashSet<T> hashset, IEnumerable<T> coleccion) { foreach (var item in coleccion) { hashset.Add(item); } } public static bool TryContains<T>(this HashSet<T> hashset, T element) { if (hashset == null) return false; return hashset.Contains(element); } #endregion public static IEnumerable<R> JoinStrict<K, C, S, R>( IEnumerable<C> currentCollection, IEnumerable<S> shouldCollection, Func<C, K> currentKeySelector, Func<S, K> shouldKeySelector, Func<C, S, R> resultSelector, string action) { var currentDictionary = currentCollection.ToDictionary(currentKeySelector); var shouldDictionary = shouldCollection.ToDictionary(shouldKeySelector); var extra = currentDictionary.Keys.Where(k => !shouldDictionary.ContainsKey(k)).ToList(); var missing = shouldDictionary.Keys.Where(k => !currentDictionary.ContainsKey(k)).ToList(); string? differences = GetDifferences(extra, missing); if (differences != null) { throw new InvalidOperationException($@"Mismatches {action}: {differences}"); } return currentDictionary.Select(p => resultSelector(p.Value, shouldDictionary[p.Key])); } public static IEnumerable<R> JoinRelaxed<K, C, S, R>( IEnumerable<C> currentCollection, IEnumerable<S> shouldCollection, Func<C, K> currentKeySelector, Func<S, K> shouldKeySelector, Func<C, S, R> resultSelector, string action) { var currentDictionary = currentCollection.ToDictionary(currentKeySelector); var shouldDictionary = shouldCollection.ToDictionary(shouldKeySelector); var extra = currentDictionary.Keys.Where(k => !shouldDictionary.ContainsKey(k)).ToList(); var missing = shouldDictionary.Keys.Where(k => !currentDictionary.ContainsKey(k)).ToList(); string? differences = GetDifferences(extra, missing); if (differences != null) { try { throw new InvalidOperationException($@"Mismatches {action}: {differences} Consider Synchronize."); } catch (Exception e) when (StartParameters.IgnoredDatabaseMismatches != null) { //This try { throw } catch is here to alert developers. //In production, in some cases its OK to attempt starting an application with a slightly different schema (dynamic entities, green-blue deployments). //In development, consider synchronize. StartParameters.IgnoredDatabaseMismatches.Add(e); } } var commonKeys = currentDictionary.Keys.Intersect(shouldDictionary.Keys); return commonKeys.Select(k => resultSelector(currentDictionary[k], shouldDictionary[k])); } private static string? GetDifferences<K>(List<K> extra, List<K> missing) { if (extra.Count != 0) { if (missing.Count != 0) return $" Extra: {extra.ToString(", ")}\r\n Missing: {missing.ToString(", ")}"; else return $" Extra: {extra.ToString(", ")}"; } else { if (missing.Count != 0) return $" Missing: {missing.ToString(", ")}"; else return null; } } public static JoinStrictResult<C, S, R> JoinStrict<K, C, S, R>( IEnumerable<C> currentCollection, IEnumerable<S> shouldCollection, Func<C, K> currentKeySelector, Func<S, K> shouldKeySelector, Func<C, S, R> resultSelector) { var currentDictionary = currentCollection.ToDictionary(currentKeySelector); var newDictionary = shouldCollection.ToDictionary(shouldKeySelector); HashSet<K> commonKeys = new HashSet<K>(currentDictionary.Keys); commonKeys.IntersectWith(newDictionary.Keys); return new JoinStrictResult<C, S, R> { Extra = currentDictionary.Where(e => !newDictionary.ContainsKey(e.Key)).Select(e => e.Value).ToList(), Missing = newDictionary.Where(e => !currentDictionary.ContainsKey(e.Key)).Select(e => e.Value).ToList(), Result = commonKeys.Select(k => resultSelector(currentDictionary[k], newDictionary[k])).ToList() }; } public static IEnumerable<Iteration<T>> Iterate<T>(this IEnumerable<T> collection) { using (IEnumerator<T> enumerator = collection.GetEnumerator()) { if (!enumerator.MoveNext()) { yield break; } bool isFirst = true; bool isLast = false; int index = 0; while (!isLast) { T current = enumerator.Current; isLast = !enumerator.MoveNext(); yield return new Iteration<T>(current, isFirst, isLast, index++); isFirst = false; } } } public static List<T> Duplicates<T, K>(this IEnumerable<T> source, Func<T, K> selector, IEqualityComparer<K>? comparer) { var hash = new HashSet<K>(comparer); return source.Where(item => !hash.Add(selector(item))).ToList(); } public static List<T> Duplicates<T, K>(this IEnumerable<T> source, Func<T, K> selector) { return source.Duplicates(selector, null); } public static List<T> Duplicates<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer) { var hash = new HashSet<T>(comparer); return source.Where(item => !hash.Add(item)).ToList(); } public static List<T> Duplicates<T>(this IEnumerable<T> source) { return source.Duplicates(EqualityComparer<T>.Default); } } public enum CollectionMessage { [Description(" and ")] And, [Description(" or ")] Or, [Description("No {0} found")] No0Found, [Description("More than one {0} found")] MoreThanOne0Found, } #pragma warning disable CS8618 // Non-nullable field is uninitialized. public class JoinStrictResult<O, N, R> { public List<O> Extra; public List<N> Missing; public List<R> Result; } #pragma warning restore CS8618 // Non-nullable field is uninitialized. public enum BiSelectOptions { None, Initial, Final, InitialAndFinal, Circular, } public struct Iteration<T> { readonly T value; readonly bool isFirst; readonly bool isLast; readonly int position; internal Iteration(T value, bool isFirst, bool isLast, int position) { this.value = value; this.isFirst = isFirst; this.isLast = isLast; this.position = position; } public T Value { get { return value; } } public bool IsFirst { get { return isFirst; } } public bool IsLast { get { return isLast; } } public int Position { get { return position; } } public bool IsEven { get { return position % 2 == 0; } } public bool IsOdd { get { return position % 1 == 0; } } } /// <summary> /// Use this if you have a sample of the population /// </summary> public static class StandartDeviationExtensions { public static float? StdDev(this IEnumerable<float> source) { int count = source.Count(); if (count <= 1) return null; double avg = source.Average(); double sum = source.Sum(d => (d - avg) * (d - avg)); return (float)Math.Sqrt(sum / (count - 1)); } public static double? StdDev(this IEnumerable<long?> source) => source.NotNull().Select(a => (double)a).StdDev(); public static float? StdDev(this IEnumerable<float?> source) => source.NotNull().StdDev(); public static double? StdDev(this IEnumerable<double> source) { int count = source.Count(); if (count <= 1) return null; double avg = source.Average(); double sum = source.Sum(d => (d - avg) * (d - avg)); return Math.Sqrt(sum / (count - 1)); } public static double? StdDev(this IEnumerable<int> source) => source.Select(a => (double)a).StdDev(); public static decimal? StdDev(this IEnumerable<decimal> source) { int count = source.Count(); if (count <= 1) return null; decimal avg = source.Average(); decimal sum = source.Sum(d => (d - avg) * (d - avg)); return (decimal)Math.Sqrt((double)(sum / (count - 1))); } public static decimal? StdDev(this IEnumerable<decimal?> source) => source.NotNull().StdDev(); public static double? StdDev(this IEnumerable<long> source) => source.Select(a => (double)a).StdDev(); public static double? StdDev(this IEnumerable<double?> source) => source.NotNull().StdDev(); public static double? StdDev(this IEnumerable<int?> source) => source.NotNull().StdDev(); public static decimal? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector) => source.Select(selector).StdDev(); public static decimal? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector) => source.Select(selector).StdDev(); public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector) => source.Select(selector).StdDev(); public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector) => source.Select(selector).StdDev(); public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector) => source.Select(selector).StdDev(); public static float? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector) => source.Select(selector).StdDev(); public static float? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector) => source.Select(selector).StdDev(); public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector) => source.Select(selector).StdDev(); public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector) => source.Select(selector).StdDev(); public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) => source.Select(selector).StdDev(); public static decimal? StdDev(this IQueryable<decimal> source) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDev(this IQueryable<double> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDev(this IQueryable<int> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDev(this IQueryable<long> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static decimal? StdDev(this IQueryable<decimal?> source) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDev(this IQueryable<double?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDev(this IQueryable<int?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDev(this IQueryable<long?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static float? StdDev(this IQueryable<float> source) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static float? StdDev(this IQueryable<float?> source) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static decimal? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal>> selector) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, double>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, long>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static decimal? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal?>> selector) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, double?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, long?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static float? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float?>> selector) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static float? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float>> selector) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); } /// <summary> /// Use this if you have the full population /// </summary> public static class StandartDeviationPopulationExtensions { public static float? StdDevP(this IEnumerable<float> source) { int count = source.Count(); if (count == 0) return null; double avg = source.Average(); double sum = source.Sum(d => (d - avg) * (d - avg)); return (float)Math.Sqrt(sum / count); } public static double? StdDevP(this IEnumerable<long?> source) => source.NotNull().Select(a => (double)a).StdDevP(); public static float? StdDevP(this IEnumerable<float?> source) => source.NotNull().StdDevP(); public static double? StdDevP(this IEnumerable<double> source) { int count = source.Count(); if (count == 0) return null; double avg = source.Average(); double sum = source.Sum(d => (d - avg) * (d - avg)); return Math.Sqrt(sum / count); } public static double? StdDevP(this IEnumerable<int> source) => source.Select(a => (double)a).StdDevP(); public static decimal? StdDevP(this IEnumerable<decimal> source) { int count = source.Count(); if (count == 0) return null; decimal avg = source.Average(); decimal sum = source.Sum(d => (d - avg) * (d - avg)); return (decimal)Math.Sqrt((double)(sum / count)); } public static decimal? StdDevP(this IEnumerable<decimal?> source) => source.NotNull().StdDevP(); public static double? StdDevP(this IEnumerable<long> source) => source.Select(a => (double)a).StdDevP(); public static double? StdDevP(this IEnumerable<double?> source) => source.NotNull().StdDevP(); public static double? StdDevP(this IEnumerable<int?> source) => source.NotNull().StdDevP(); public static decimal? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector) => source.Select(selector).StdDevP(); public static decimal? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector) => source.Select(selector).StdDevP(); public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector) => source.Select(selector).StdDevP(); public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector) => source.Select(selector).StdDevP(); public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector) => source.Select(selector).StdDevP(); public static float? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector) => source.Select(selector).StdDevP(); public static float? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector) => source.Select(selector).StdDevP(); public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector) => source.Select(selector).StdDevP(); public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector) => source.Select(selector).StdDevP(); public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) => source.Select(selector).StdDevP(); public static decimal? StdDevP(this IQueryable<decimal> source) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDevP(this IQueryable<double> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDevP(this IQueryable<int> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDevP(this IQueryable<long> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static decimal? StdDevP(this IQueryable<decimal?> source) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDevP(this IQueryable<double?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDevP(this IQueryable<int?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static double? StdDevP(this IQueryable<long?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static float? StdDevP(this IQueryable<float> source) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static float? StdDevP(this IQueryable<float?> source) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression)); public static decimal? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal>> selector) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, double>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, long>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static decimal? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal?>> selector) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, double?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, long?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static float? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float?>> selector) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); public static float? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float>> selector) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector))); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using OpenSim.Framework; using OpenMetaverse; namespace OpenSim.Services.Interfaces { public interface IGridService { /// <summary> /// Register a region with the grid service. /// </summary> /// <param name="regionInfos"> </param> /// <returns></returns> /// <exception cref="System.Exception">Thrown if region registration failed</exception> string RegisterRegion(UUID scopeID, GridRegion regionInfos); /// <summary> /// Deregister a region with the grid service. /// </summary> /// <param name="regionID"></param> /// <returns></returns> /// <exception cref="System.Exception">Thrown if region deregistration failed</exception> bool DeregisterRegion(UUID regionID); /// <summary> /// Get information about the regions neighbouring the given co-ordinates (in meters). /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID); GridRegion GetRegionByUUID(UUID scopeID, UUID regionID); /// <summary> /// Get the region at the given position (in meters) /// </summary> /// <param name="scopeID"></param> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> GridRegion GetRegionByPosition(UUID scopeID, int x, int y); /// <summary> /// Get information about a region which exactly matches the name given. /// </summary> /// <param name="scopeID"></param> /// <param name="regionName"></param> /// <returns>Returns the region information if the name matched. Null otherwise.</returns> GridRegion GetRegionByName(UUID scopeID, string regionName); /// <summary> /// Get information about regions starting with the provided name. /// </summary> /// <param name="name"> /// The name to match against. /// </param> /// <param name="maxNumber"> /// The maximum number of results to return. /// </param> /// <returns> /// A list of <see cref="RegionInfo"/>s of regions with matching name. If the /// grid-server couldn't be contacted or returned an error, return null. /// </returns> List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber); List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax); List<GridRegion> GetDefaultRegions(UUID scopeID); List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y); List<GridRegion> GetHyperlinks(UUID scopeID); /// <summary> /// Get internal OpenSimulator region flags. /// </summary> /// <remarks> /// See OpenSimulator.Framework.RegionFlags. These are not returned in the GridRegion structure - /// they currently need to be requested separately. Possibly this should change to avoid multiple service calls /// in some situations. /// </remarks> /// <returns> /// The region flags. /// </returns> /// <param name='scopeID'></param> /// <param name='regionID'></param> int GetRegionFlags(UUID scopeID, UUID regionID); } public class GridRegion { /// <summary> /// The port by which http communication occurs with the region /// </summary> public uint HttpPort { get { return m_httpPort; } set { m_httpPort = value; } } protected uint m_httpPort; /// <summary> /// A well-formed URI for the host region server (namely "http://" + ExternalHostName) /// </summary> public string ServerURI { get { if ( m_serverURI != string.Empty ) { return m_serverURI; } else { return "http://" + m_externalHostName + ":" + m_httpPort + "/"; } } set { if ( value.EndsWith("/") ) { m_serverURI = value; } else { m_serverURI = value + '/'; } } } protected string m_serverURI; public string RegionName { get { return m_regionName; } set { m_regionName = value; } } protected string m_regionName = String.Empty; protected string m_externalHostName; protected IPEndPoint m_internalEndPoint; /// <summary> /// The co-ordinate of this region. /// </summary> public int RegionCoordX { get { return RegionLocX / (int)Constants.RegionSize; } } /// <summary> /// The co-ordinate of this region /// </summary> public int RegionCoordY { get { return RegionLocY / (int)Constants.RegionSize; } } /// <summary> /// The location of this region in meters. /// </summary> public int RegionLocX { get { return m_regionLocX; } set { m_regionLocX = value; } } protected int m_regionLocX; /// <summary> /// The location of this region in meters. /// </summary> public int RegionLocY { get { return m_regionLocY; } set { m_regionLocY = value; } } protected int m_regionLocY; protected UUID m_estateOwner; public UUID EstateOwner { get { return m_estateOwner; } set { m_estateOwner = value; } } public UUID RegionID = UUID.Zero; public UUID ScopeID = UUID.Zero; public UUID TerrainImage = UUID.Zero; public UUID ParcelImage = UUID.Zero; public byte Access; public int Maturity; public string RegionSecret = string.Empty; public string Token = string.Empty; public GridRegion() { m_serverURI = string.Empty; } public GridRegion(int regionLocX, int regionLocY, IPEndPoint internalEndPoint, string externalUri) { m_regionLocX = regionLocX; m_regionLocY = regionLocY; m_internalEndPoint = internalEndPoint; m_externalHostName = externalUri; } public GridRegion(int regionLocX, int regionLocY, string externalUri, uint port) { m_regionLocX = regionLocX; m_regionLocY = regionLocY; m_externalHostName = externalUri; m_internalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)port); } public GridRegion(uint xcell, uint ycell) { m_regionLocX = (int)(xcell * Constants.RegionSize); m_regionLocY = (int)(ycell * Constants.RegionSize); } public GridRegion(RegionInfo ConvertFrom) { m_regionName = ConvertFrom.RegionName; m_regionLocX = (int)(ConvertFrom.RegionLocX * Constants.RegionSize); m_regionLocY = (int)(ConvertFrom.RegionLocY * Constants.RegionSize); m_internalEndPoint = ConvertFrom.InternalEndPoint; m_externalHostName = ConvertFrom.ExternalHostName; m_httpPort = ConvertFrom.HttpPort; RegionID = ConvertFrom.RegionID; ServerURI = ConvertFrom.ServerURI; TerrainImage = ConvertFrom.RegionSettings.TerrainImageID; ParcelImage = ConvertFrom.RegionSettings.ParcelImageID; Access = ConvertFrom.AccessLevel; Maturity = ConvertFrom.RegionSettings.Maturity; RegionSecret = ConvertFrom.regionSecret; EstateOwner = ConvertFrom.EstateSettings.EstateOwner; } public GridRegion(GridRegion ConvertFrom) { m_regionName = ConvertFrom.RegionName; m_regionLocX = ConvertFrom.RegionLocX; m_regionLocY = ConvertFrom.RegionLocY; m_internalEndPoint = ConvertFrom.InternalEndPoint; m_externalHostName = ConvertFrom.ExternalHostName; m_httpPort = ConvertFrom.HttpPort; RegionID = ConvertFrom.RegionID; ServerURI = ConvertFrom.ServerURI; TerrainImage = ConvertFrom.TerrainImage; ParcelImage = ConvertFrom.ParcelImage; Access = ConvertFrom.Access; Maturity = ConvertFrom.Maturity; RegionSecret = ConvertFrom.RegionSecret; EstateOwner = ConvertFrom.EstateOwner; } # region Definition of equality /// <summary> /// Define equality as two regions having the same, non-zero UUID. /// </summary> public bool Equals(GridRegion region) { if ((object)region == null) return false; // Return true if the non-zero UUIDs are equal: return (RegionID != UUID.Zero) && RegionID.Equals(region.RegionID); } public override bool Equals(Object obj) { if (obj == null) return false; return Equals(obj as GridRegion); } public override int GetHashCode() { return RegionID.GetHashCode() ^ TerrainImage.GetHashCode() ^ ParcelImage.GetHashCode(); } #endregion /// <value> /// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw. /// /// XXX Isn't this really doing too much to be a simple getter, rather than an explict method? /// </value> public IPEndPoint ExternalEndPoint { get { // Old one defaults to IPv6 //return new IPEndPoint(Dns.GetHostAddresses(m_externalHostName)[0], m_internalEndPoint.Port); IPAddress ia = null; // If it is already an IP, don't resolve it - just return directly if (IPAddress.TryParse(m_externalHostName, out ia)) return new IPEndPoint(ia, m_internalEndPoint.Port); // Reset for next check ia = null; try { foreach (IPAddress Adr in Dns.GetHostAddresses(m_externalHostName)) { if (ia == null) ia = Adr; if (Adr.AddressFamily == AddressFamily.InterNetwork) { ia = Adr; break; } } } catch (SocketException e) { throw new Exception( "Unable to resolve local hostname " + m_externalHostName + " innerException of type '" + e + "' attached to this exception", e); } return new IPEndPoint(ia, m_internalEndPoint.Port); } } public string ExternalHostName { get { return m_externalHostName; } set { m_externalHostName = value; } } public IPEndPoint InternalEndPoint { get { return m_internalEndPoint; } set { m_internalEndPoint = value; } } public ulong RegionHandle { get { return Util.UIntsToLong((uint)RegionLocX, (uint)RegionLocY); } } public Dictionary<string, object> ToKeyValuePairs() { Dictionary<string, object> kvp = new Dictionary<string, object>(); kvp["uuid"] = RegionID.ToString(); kvp["locX"] = RegionLocX.ToString(); kvp["locY"] = RegionLocY.ToString(); kvp["regionName"] = RegionName; kvp["serverIP"] = ExternalHostName; //ExternalEndPoint.Address.ToString(); kvp["serverHttpPort"] = HttpPort.ToString(); kvp["serverURI"] = ServerURI; kvp["serverPort"] = InternalEndPoint.Port.ToString(); kvp["regionMapTexture"] = TerrainImage.ToString(); kvp["parcelMapTexture"] = ParcelImage.ToString(); kvp["access"] = Access.ToString(); kvp["regionSecret"] = RegionSecret; kvp["owner_uuid"] = EstateOwner.ToString(); kvp["Token"] = Token.ToString(); // Maturity doesn't seem to exist in the DB return kvp; } public GridRegion(Dictionary<string, object> kvp) { if (kvp.ContainsKey("uuid")) RegionID = new UUID((string)kvp["uuid"]); if (kvp.ContainsKey("locX")) RegionLocX = Convert.ToInt32((string)kvp["locX"]); if (kvp.ContainsKey("locY")) RegionLocY = Convert.ToInt32((string)kvp["locY"]); if (kvp.ContainsKey("regionName")) RegionName = (string)kvp["regionName"]; if (kvp.ContainsKey("serverIP")) { //int port = 0; //Int32.TryParse((string)kvp["serverPort"], out port); //IPEndPoint ep = new IPEndPoint(IPAddress.Parse((string)kvp["serverIP"]), port); ExternalHostName = (string)kvp["serverIP"]; } else ExternalHostName = "127.0.0.1"; if (kvp.ContainsKey("serverPort")) { Int32 port = 0; Int32.TryParse((string)kvp["serverPort"], out port); InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), port); } if (kvp.ContainsKey("serverHttpPort")) { UInt32 port = 0; UInt32.TryParse((string)kvp["serverHttpPort"], out port); HttpPort = port; } if (kvp.ContainsKey("serverURI")) ServerURI = (string)kvp["serverURI"]; if (kvp.ContainsKey("regionMapTexture")) UUID.TryParse((string)kvp["regionMapTexture"], out TerrainImage); if (kvp.ContainsKey("parcelMapTexture")) UUID.TryParse((string)kvp["parcelMapTexture"], out ParcelImage); if (kvp.ContainsKey("access")) Access = Byte.Parse((string)kvp["access"]); if (kvp.ContainsKey("regionSecret")) RegionSecret =(string)kvp["regionSecret"]; if (kvp.ContainsKey("owner_uuid")) EstateOwner = new UUID(kvp["owner_uuid"].ToString()); if (kvp.ContainsKey("Token")) Token = kvp["Token"].ToString(); } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Encog.ML.Data.Dynamic { /// <summary> /// For support of sliding windows or other custom input and ideal collection providers. /// </summary> public class DynamicMLDataSet : IMLDataSet { /// <summary> /// Initializes a new instance of the DynamicMLDataSet class. /// </summary> /// <param name="input"> The input. </param> /// <param name="ideal"> The ideal. </param> public DynamicMLDataSet(IDynamicMLDataProvider input, IDynamicMLDataProvider ideal) { InputArgs = input; IdealArgs = ideal; Count = Math.Min(input.Count, ideal.Count); } /// <summary> /// The ideal arguments. /// </summary> public readonly IDynamicMLDataProvider InputArgs, IdealArgs; /// <summary> /// The size of the ideal data (>0 supervised), 0 if no ideal data (unsupervised) /// </summary> /// <value> /// The size of the ideal. /// </value> public int IdealSize { get { return IdealArgs.Size; } } /// <summary> /// The size of the input data. /// </summary> /// <value> /// The size of the input. /// </value> public int InputSize { get { return InputArgs.Size; } } /// <summary> /// The number of records in the data set. /// </summary> /// <value> /// The count. /// </value> public int Count { get; private set; } /// <summary> /// Return true if supervised. /// </summary> /// <value> /// true if supervised, false if not. /// </value> public bool Supervised { get { return true; } } /// <summary> /// Close this datasource and release any resources obtained by it, including any iterators /// created. /// </summary> public void Close() { // nothing to close } /// <summary> /// Get an enumerator to access the data. /// </summary> /// <returns> /// The enumerator. /// </returns> public IEnumerator<IMLDataPair> GetEnumerator() { return new DynamicMLDataSetEnumerator(this); } /// <summary> /// Dynamic ML data set enumerator. /// </summary> private class DynamicMLDataSetEnumerator: IEnumerator<IMLDataPair> { private int _position = -1; private readonly DynamicMLDataSet _ds; public DynamicMLDataSetEnumerator(DynamicMLDataSet ds) { _ds = ds; } public IMLDataPair Current { get { return _position < 0 || _position >= _ds.Count ? null : _ds[_position]; } } public void Dispose() { } object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { return ++_position < _ds.Count; } public void Reset() { _position = -1; } } /// <summary> /// eg. Clone. /// </summary> /// <returns> /// . /// </returns> public IMLDataSet OpenAdditional() { return new DynamicMLDataSet(InputArgs, IdealArgs); } /// <summary> /// Get the specified record. /// </summary> /// <value> /// The indexed item. /// </value> /// /// ### <param name="x"> The index to access. </param> /// ### <returns> /// . /// </returns> public IMLDataPair this[int x] { get { return new DynamicMLDataPair(this, x); } } /// <summary> /// Dynamic ML data pair. /// </summary> private class DynamicMLDataPair: IMLDataPair { private readonly DynamicMLDataSet _ds; private readonly int _index; public DynamicMLDataPair(DynamicMLDataSet ds, int index) { _ds = ds; _index = index; Significance = 1.0; Input = new DynamicWindowMLData(_ds.InputArgs, index); Ideal = new DynamicWindowMLData(_ds.IdealArgs, index); } public IMLData Input { get; private set; } public IMLData Ideal { get; private set; } public bool Supervised { get { return true; } } public double Significance { get; set; } /// <summary> /// Makes a deep copy of this object. /// </summary> /// <returns> /// A copy of this object. /// </returns> public object Clone() { return new DynamicMLDataPair(_ds, _index); } public Util.KMeans.ICentroid<IMLDataPair> CreateCentroid() { throw new NotImplementedException(); } private class DynamicWindowMLData: IMLData { private readonly int _index; private readonly IDynamicMLDataProvider _provider; public DynamicWindowMLData(IDynamicMLDataProvider provider, int index) { _provider = provider; _index = index; } public double this[int x] { get { return _provider[_index, x]; } } public int Count { get { return _provider.Size; } } public void CopyTo(double[] target, int targetIndex, int count) { for(int i = 0; i < count; i++) target[i + targetIndex] = this[i]; } public object Clone() { return new DynamicWindowMLData(_provider, _index); } public Util.KMeans.ICentroid<IMLData> CreateCentroid() { throw new NotImplementedException(); } } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Reactive.Linq; using Avalonia.Controls.Primitives; namespace Avalonia.Controls { /// <summary> /// A control which pops up a hint when a control is hovered. /// </summary> /// <remarks> /// You will probably not want to create a <see cref="ToolTip"/> control directly: if added to /// the tree it will act as a simple <see cref="ContentControl"/> styled to look like a tooltip. /// To add a tooltip to a control, use the <see cref="TipProperty"/> attached property, /// assigning the content that you want displayed. /// </remarks> public class ToolTip : ContentControl { /// <summary> /// Defines the ToolTip.Tip attached property. /// </summary> public static readonly AttachedProperty<object> TipProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, object>("Tip"); /// <summary> /// Defines the ToolTip.IsOpen attached property. /// </summary> public static readonly AttachedProperty<bool> IsOpenProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, bool>("IsOpen"); /// <summary> /// Defines the ToolTip.Placement property. /// </summary> public static readonly AttachedProperty<PlacementMode> PlacementProperty = AvaloniaProperty.RegisterAttached<Popup, Control, PlacementMode>("Placement", defaultValue: PlacementMode.Pointer); /// <summary> /// Defines the ToolTip.HorizontalOffset property. /// </summary> public static readonly AttachedProperty<double> HorizontalOffsetProperty = AvaloniaProperty.RegisterAttached<Popup, Control, double>("HorizontalOffset"); /// <summary> /// Defines the ToolTip.VerticalOffset property. /// </summary> public static readonly AttachedProperty<double> VerticalOffsetProperty = AvaloniaProperty.RegisterAttached<Popup, Control, double>("VerticalOffset", 20); /// <summary> /// Defines the ToolTip.ShowDelay property. /// </summary> public static readonly AttachedProperty<int> ShowDelayProperty = AvaloniaProperty.RegisterAttached<Popup, Control, int>("ShowDelay", 400); /// <summary> /// Stores the curernt <see cref="ToolTip"/> instance in the control. /// </summary> private static readonly AttachedProperty<ToolTip> ToolTipProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, ToolTip>("ToolTip"); private PopupRoot _popup; /// <summary> /// Initializes static members of the <see cref="ToolTip"/> class. /// </summary> static ToolTip() { TipProperty.Changed.Subscribe(ToolTipService.Instance.TipChanged); IsOpenProperty.Changed.Subscribe(IsOpenChanged); } /// <summary> /// Gets the value of the ToolTip.Tip attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// The content to be displayed in the control's tooltip. /// </returns> public static object GetTip(Control element) { return element.GetValue(TipProperty); } /// <summary> /// Sets the value of the ToolTip.Tip attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">The content to be displayed in the control's tooltip.</param> public static void SetTip(Control element, object value) { element.SetValue(TipProperty, value); } /// <summary> /// Gets the value of the ToolTip.IsOpen attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating whether the tool tip is visible. /// </returns> public static bool GetIsOpen(Control element) { return element.GetValue(IsOpenProperty); } /// <summary> /// Sets the value of the ToolTip.IsOpen attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating whether the tool tip is visible.</param> public static void SetIsOpen(Control element, bool value) { element.SetValue(IsOpenProperty, value); } /// <summary> /// Gets the value of the ToolTip.Placement attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating how the tool tip is positioned. /// </returns> public static PlacementMode GetPlacement(Control element) { return element.GetValue(PlacementProperty); } /// <summary> /// Sets the value of the ToolTip.Placement attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating how the tool tip is positioned.</param> public static void SetPlacement(Control element, PlacementMode value) { element.SetValue(PlacementProperty, value); } /// <summary> /// Gets the value of the ToolTip.HorizontalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating how the tool tip is positioned. /// </returns> public static double GetHorizontalOffset(Control element) { return element.GetValue(HorizontalOffsetProperty); } /// <summary> /// Sets the value of the ToolTip.HorizontalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating how the tool tip is positioned.</param> public static void SetHorizontalOffset(Control element, double value) { element.SetValue(HorizontalOffsetProperty, value); } /// <summary> /// Gets the value of the ToolTip.VerticalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating how the tool tip is positioned. /// </returns> public static double GetVerticalOffset(Control element) { return element.GetValue(VerticalOffsetProperty); } /// <summary> /// Sets the value of the ToolTip.VerticalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating how the tool tip is positioned.</param> public static void SetVerticalOffset(Control element, double value) { element.SetValue(VerticalOffsetProperty, value); } /// <summary> /// Gets the value of the ToolTip.ShowDelay attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating the time, in milliseconds, before a tool tip opens. /// </returns> public static int GetShowDelay(Control element) { return element.GetValue(ShowDelayProperty); } /// <summary> /// Sets the value of the ToolTip.ShowDelay attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating the time, in milliseconds, before a tool tip opens.</param> public static void SetShowDelay(Control element, int value) { element.SetValue(ShowDelayProperty, value); } private static void IsOpenChanged(AvaloniaPropertyChangedEventArgs e) { var control = (Control)e.Sender; if ((bool)e.NewValue) { var tip = GetTip(control); if (tip == null) return; var toolTip = control.GetValue(ToolTipProperty); if (toolTip == null || (tip != toolTip && tip != toolTip.Content)) { toolTip?.Close(); toolTip = tip as ToolTip ?? new ToolTip { Content = tip }; control.SetValue(ToolTipProperty, toolTip); } toolTip.Open(control); } else { var toolTip = control.GetValue(ToolTipProperty); toolTip?.Close(); } } private void Open(Control control) { Close(); _popup = new PopupRoot { Content = this }; ((ISetLogicalParent)_popup).SetParent(control); _popup.Position = Popup.GetPosition(control, GetPlacement(control), _popup, GetHorizontalOffset(control), GetVerticalOffset(control)); _popup.Show(); } private void Close() { if (_popup != null) { _popup.Content = null; _popup.Hide(); _popup = null; } } } }
/* * Copyright (c) Contributors, http://aurora-sim.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.IO; using System.Net; using System.Reflection; using Nini.Config; using Aurora.Framework; using OpenMetaverse; using OpenSim.Region.Framework.Scenes; namespace OpenSim.ApplicationPlugins.RegionLoaderPlugin { public class RegionLoaderFileSystem : IRegionLoader { private IConfigSource m_configSource; private bool m_default = true; private bool m_enabled = true; private ISimulationBase m_openSim; private string m_regionConfigPath = Path.Combine(Util.configDir(), "Regions"); public bool Enabled { get { return m_enabled; } } public bool Default { get { return m_default; } } public void Initialise(IConfigSource configSource, ISimulationBase openSim) { m_configSource = configSource; m_openSim = openSim; IConfig config = configSource.Configs["RegionStartup"]; if (config != null) { m_enabled = config.GetBoolean(GetType().Name + "_Enabled", m_enabled); if (!m_enabled) return; m_default = config.GetString("Default") == GetType().Name; m_regionConfigPath = config.GetString("RegionsDirectory", m_regionConfigPath).Trim(); //Add the console command if it is the default if (m_default) MainConsole.Instance.Commands.AddCommand("create region", "create region", "Create a new region.", AddRegion); } m_openSim.ApplicationRegistry.StackModuleInterface<IRegionLoader>(this); } public RegionInfo[] LoadRegions() { return InternalLoadRegions (false); } public RegionInfo[] InternalLoadRegions (bool checkOnly) { if (!Directory.Exists (m_regionConfigPath)) if (checkOnly) return null; else Directory.CreateDirectory (m_regionConfigPath); string[] configFiles = Directory.GetFiles (m_regionConfigPath, "*.xml"); string[] iniFiles = Directory.GetFiles (m_regionConfigPath, "*.ini"); if (configFiles.Length == 0 && iniFiles.Length == 0) { if (!m_default || checkOnly) return null; LoadRegionFromFile ("DEFAULT REGION CONFIG", Path.Combine (m_regionConfigPath, "Regions.ini"), false, m_configSource, ""); iniFiles = Directory.GetFiles (m_regionConfigPath, "*.ini"); } List<RegionInfo> regionInfos = new List<RegionInfo> (); int i = 0; foreach (string file in iniFiles) { IConfigSource source = new IniConfigSource (file, Nini.Ini.IniFileType.AuroraStyle); foreach (IConfig config in source.Configs) { RegionInfo regionInfo = LoadRegionFromFile ("REGION CONFIG #" + (i + 1), file, false, m_configSource, config.Name); regionInfos.Add (regionInfo); i++; } } foreach (string file in configFiles) { RegionInfo regionInfo = LoadRegionFromFile ("REGION CONFIG #" + (i + 1), file, false, m_configSource, string.Empty); regionInfos.Add (regionInfo); i++; } return regionInfos.ToArray (); } // File based loading // public RegionInfo LoadRegionFromFile(string description, string filename, bool skipConsoleConfig, IConfigSource configSource, string configName) { // m_configSource = configSource; RegionInfo region = new RegionInfo(); if (filename.ToLower().EndsWith(".ini")) { if (!File.Exists(filename)) // New region config request { IniConfigSource newFile = new IniConfigSource(); region.RegionFile = filename; ReadNiniConfig(region, newFile, configName); newFile.Save(filename); return region; } IniConfigSource m_source = new IniConfigSource(filename, Nini.Ini.IniFileType.AuroraStyle); bool saveFile = false; if (m_source.Configs[configName] == null) saveFile = true; region.RegionFile = filename; bool update = ReadNiniConfig(region, m_source, configName); if (configName != String.Empty && (saveFile || update)) m_source.Save(filename); return region; } try { // This will throw if it's not legal Nini XML format // and thereby toss it to the legacy loader // IConfigSource xmlsource = new XmlConfigSource(filename); ReadNiniConfig(region, xmlsource, configName); region.RegionFile = filename; return region; } catch (Exception) { } return null; } //Returns true if the source should be updated. Returns false if it does not. public bool ReadNiniConfig(RegionInfo region, IConfigSource source, string name) { // bool creatingNew = false; if (name == String.Empty || source.Configs.Count == 0) { MainConsole.Instance.Info ("=====================================\n"); MainConsole.Instance.Info ("We are now going to ask a couple of questions about your region.\n"); MainConsole.Instance.Info ("You can press 'enter' without typing anything to use the default\n"); MainConsole.Instance.Info ("the default is displayed between [ ] brackets.\n"); MainConsole.Instance.Info ("=====================================\n"); } bool NeedsUpdate = false; if (name == String.Empty) name = MainConsole.Instance.Prompt("New region name", name); if (name == String.Empty) throw new Exception("Cannot interactively create region with no name"); if (source.Configs.Count == 0) { source.AddConfig(name); // creatingNew = true; NeedsUpdate = true; } if (source.Configs[name] == null) { source.AddConfig(name); NeedsUpdate = true; // creatingNew = true; } IConfig config = source.Configs[name]; // UUID // string regionUUID = config.GetString("RegionUUID", string.Empty); if (regionUUID == String.Empty) { NeedsUpdate = true; UUID newID = UUID.Random(); regionUUID = MainConsole.Instance.Prompt("Region UUID for region " + name, newID.ToString()); config.Set("RegionUUID", regionUUID); } region.RegionID = new UUID(regionUUID); region.RegionName = name; string location = config.GetString("Location", String.Empty); if (location == String.Empty) { NeedsUpdate = true; location = MainConsole.Instance.Prompt("Region Location for region " + name, "1000,1000"); config.Set("Location", location); } string[] locationElements = location.Split(new[] { ',' }); region.RegionLocX = Convert.ToInt32(locationElements[0]) * Constants.RegionSize; region.RegionLocY = Convert.ToInt32(locationElements[1]) * Constants.RegionSize; int regionSizeX = config.GetInt("RegionSizeX", 0); if (regionSizeX == 0 || ((region.RegionSizeX % Constants.MinRegionSize) != 0)) { NeedsUpdate = true; while (true) { if (int.TryParse(MainConsole.Instance.Prompt("Region X Size for region " + name, "256"), out regionSizeX)) break; } config.Set("RegionSizeX", regionSizeX); } region.RegionSizeX = Convert.ToInt32(regionSizeX); int regionSizeY = config.GetInt("RegionSizeY", 0); if (regionSizeY == 0 || ((region.RegionSizeY % Constants.MinRegionSize) != 0)) { NeedsUpdate = true; while(true) { if(int.TryParse(MainConsole.Instance.Prompt("Region Y Size for region " + name, "256"), out regionSizeY)) break; } config.Set("RegionSizeY", regionSizeY); } region.RegionSizeY = regionSizeY; int regionSizeZ = config.GetInt("RegionSizeZ", 1024); //if (regionSizeZ == String.Empty) //{ // NeedsUpdate = true; // regionSizeZ = MainConsole.Instance.CmdPrompt("Region Z Size for region " + name, "1024"); // config.Set("RegionSizeZ", regionSizeZ); //} region.RegionSizeZ = regionSizeZ; // Internal IP IPAddress address; if (config.Contains("InternalAddress")) { address = IPAddress.Parse(config.GetString("InternalAddress", String.Empty)); } else { NeedsUpdate = true; address = IPAddress.Parse(MainConsole.Instance.Prompt("Internal IP address for region " + name, "0.0.0.0")); config.Set("InternalAddress", address.ToString()); } int port; if (config.Contains("InternalPort")) { port = config.GetInt("InternalPort", 9000); } else { NeedsUpdate = true; port = Convert.ToInt32(MainConsole.Instance.Prompt("Internal port for region " + name, "9000")); config.Set("InternalPort", port); } region.UDPPorts.Add (port); region.InternalEndPoint = new IPEndPoint(address, port); // External IP // string externalName; if (config.Contains("ExternalHostName")) { //Let's know our external IP (by Enrico Nirvana) externalName = config.GetString("ExternalHostName", Aurora.Framework.Utilities.GetExternalIp()); } else { NeedsUpdate = true; //Let's know our external IP (by Enrico Nirvana) externalName = MainConsole.Instance.Prompt("External host name for region " + name, Aurora.Framework.Utilities.GetExternalIp()); config.Set("ExternalHostName", externalName); //ended here (by Enrico Nirvana) } region.RegionType = config.GetString("RegionType", region.RegionType); if (region.RegionType == String.Empty) { NeedsUpdate = true; region.RegionType = MainConsole.Instance.Prompt("Region Type for region " + name, "Mainland"); config.Set("RegionType", region.RegionType); } region.AllowPhysicalPrims = config.GetBoolean("AllowPhysicalPrims", region.AllowPhysicalPrims); region.AllowScriptCrossing = config.GetBoolean("AllowScriptCrossing", region.AllowScriptCrossing); region.TrustBinariesFromForeignSims = config.GetBoolean("TrustBinariesFromForeignSims", region.TrustBinariesFromForeignSims); region.SeeIntoThisSimFromNeighbor = config.GetBoolean("SeeIntoThisSimFromNeighbor", region.SeeIntoThisSimFromNeighbor); region.ObjectCapacity = config.GetInt ("MaxPrims", region.ObjectCapacity); region.Startup = (StartupType)Enum.Parse(typeof(StartupType), config.GetString ("StartupType", region.Startup.ToString())); // Multi-tenancy // region.ScopeID = new UUID(config.GetString("ScopeID", region.ScopeID.ToString())); //Do this last so that we can save the password immediately if it doesn't exist UUID password = region.Password; //Save the pass as this TryParse will wipe it out if (!UUID.TryParse(config.GetString("NeighborPassword", ""), out region.Password)) { region.Password = password; config.Set("NeighborPassword", password); region.WriteNiniConfig(source); } return NeedsUpdate; } /// <summary> /// Creates a new region based on the parameters specified. This will ask the user questions on the console /// </summary> /// <param name="cmd">0,1,region name, region XML file</param> public void AddRegion(string[] cmd) { string fileName = MainConsole.Instance.Prompt ("File Name", "Regions.ini"); string regionName = MainConsole.Instance.Prompt ("Region Name", "New Region"); if (fileName.EndsWith (".ini")) { string regionFile = String.Format ("{0}/{1}", m_regionConfigPath, fileName); // Allow absolute and relative specifiers if (fileName.StartsWith ("/") || fileName.StartsWith ("\\") || fileName.StartsWith ("..")) regionFile = fileName; MainConsole.Instance.Debug ("[LOADREGIONS]: Creating Region: " + regionName); SceneManager manager = m_openSim.ApplicationRegistry.RequestModuleInterface<SceneManager>(); manager.AllRegions++; manager.StartNewRegion(LoadRegionFromFile(regionName, regionFile, false, m_configSource, regionName)); } else { MainConsole.Instance.Info ("The file name must end with .ini"); } } /// <summary> /// Save the changes to the RegionInfo to the file that it came from in the Regions/ directory /// </summary> /// <param name="oldName"></param> /// <param name="regionInfo"></param> public void UpdateRegionInfo(string oldName, RegionInfo regionInfo) { string regionConfigPath = Path.Combine(Util.configDir(), "Regions"); if (oldName == "") oldName = regionInfo.RegionName; try { IConfig config = m_configSource.Configs["RegionStartup"]; if (config != null) { regionConfigPath = config.GetString("RegionsDirectory", regionConfigPath).Trim(); } } catch (Exception) { // No INI setting recorded. } if (!Directory.Exists(regionConfigPath)) return; string[] iniFiles = Directory.GetFiles(regionConfigPath, "*.ini"); foreach (string file in iniFiles) { IConfigSource source = new IniConfigSource(file, Nini.Ini.IniFileType.AuroraStyle); IConfig cnf = source.Configs[oldName]; if (cnf != null) { try { source.Configs.Remove(cnf); cnf.Set("Location", regionInfo.RegionLocX / Constants.RegionSize + "," + regionInfo.RegionLocY / Constants.RegionSize); cnf.Set("RegionType", regionInfo.RegionType); cnf.Name = regionInfo.RegionName; source.Configs.Add(cnf); } catch { } source.Save(); break; } } } /// <summary> /// This deletes the region from the region.ini file or region.xml file and removes the file if there are no other regions in the file /// </summary> /// <param name="regionInfo"></param> public void DeleteRegion(RegionInfo regionInfo) { if (!String.IsNullOrEmpty(regionInfo.RegionFile)) { if (regionInfo.RegionFile.ToLower().EndsWith(".xml")) { File.Delete(regionInfo.RegionFile); MainConsole.Instance.InfoFormat("[OPENSIM]: deleting region file \"{0}\"", regionInfo.RegionFile); } if (regionInfo.RegionFile.ToLower().EndsWith(".ini")) { try { IniConfigSource source = new IniConfigSource(regionInfo.RegionFile, Nini.Ini.IniFileType.AuroraStyle); if (source.Configs[regionInfo.RegionName] != null) { source.Configs.Remove(regionInfo.RegionName); if (source.Configs.Count == 0) { File.Delete(regionInfo.RegionFile); } else { source.Save(regionInfo.RegionFile); } } } catch (Exception) { } } } } public void DeleteAllRegionFiles () { string regionConfigPath = Path.Combine (Util.configDir (), "Regions"); IConfig config = m_configSource.Configs["RegionStartup"]; if (config != null) regionConfigPath = config.GetString ("RegionsDirectory", regionConfigPath).Trim (); if (!Directory.Exists (regionConfigPath)) return; Directory.Delete (regionConfigPath); } public bool FailedToStartRegions(string reason) { //Can't deal with it return false; } public string Name { get { return "File Based Plugin"; } } public void Dispose() { } } }
namespace Files.ViewModels.FileExplorer { using System; using System.IO; using System.Windows; using System.Windows.Input; using Edi.Core.Interfaces; using Edi.Core.Interfaces.Enums; using Edi.Core.ViewModels; using FileSystemModels.Interfaces; using FileSystemModels.Models; using FolderBrowser.Interfaces; using Edi.Settings.Interfaces; using Edi.Core.ViewModels.Command; using FileSystemModels; using System.Threading; using FileSystemModels.Browse; using System.Threading.Tasks; using Files.ViewModels.FileExplorer.Tasks; /// <summary> /// This class can be used to present file based information, such as, /// Size, Path etc to the user. /// </summary> public class FileExplorerViewModel : ControllerBaseViewModel, IRegisterableToolWindow, IExplorer, ITreeListControllerViewModel { #region fields public const string ToolContentId = "<FileExplorerTool>"; protected static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private string mFilePathName = string.Empty; private Func<string, bool> mFileOpenMethod = null; private RelayCommand<object> mSyncPathWithCurrentDocumentCommand = null; private IDocumentParent mParent = null; private readonly IFileOpenService mFileOpenService; private readonly SemaphoreSlim _SlowStuffSemaphore; private readonly OneTaskLimitedScheduler _OneTaskScheduler; private readonly CancellationTokenSource _CancelTokenSourc; private bool _disposed = false; private readonly string _InitialPath; private string _SelectedFolder = string.Empty; #endregion fields #region constructor /// <summary> /// Class constructor /// </summary> public FileExplorerViewModel(ISettingsManager programSettings, IFileOpenService fileOpenService) : base("Explorer") { base.ContentId = ToolContentId; this.mFileOpenService = fileOpenService; this.OnActiveDocumentChanged(null, null); // _SlowStuffSemaphore = new SemaphoreSlim(1, 1); _OneTaskScheduler = new OneTaskLimitedScheduler(); _CancelTokenSourc = new CancellationTokenSource(); FolderItemsView = FileListView.Factory.CreateFileListViewModel(); FolderTextPath = FolderControlsLib.Factory.CreateFolderComboBoxVM(); RecentFolders = FileSystemModels.Factory.CreateBookmarksViewModel(); TreeBrowser = FolderBrowser.FolderBrowserFactory.CreateBrowserViewModel(false); // This is fired when the user selects a new folder bookmark from the drop down button RecentFolders.BrowseEvent += FolderTextPath_BrowseEvent; // This is fired when the text path in the combobox changes to another existing folder FolderTextPath.BrowseEvent += FolderTextPath_BrowseEvent; Filters = FilterControlsLib.Factory.CreateFilterComboBoxViewModel(); Filters.OnFilterChanged += this.FileViewFilter_Changed; // This is fired when the current folder in the listview changes to another existing folder this.FolderItemsView.BrowseEvent += FolderTextPath_BrowseEvent; // Event fires when the user requests to add a folder into the list of recently visited folders this.FolderItemsView.BookmarkFolder.RequestEditBookmarkedFolders += this.FolderItemsView_RequestEditBookmarkedFolders; // This event is fired when a user opens a file this.FolderItemsView.OnFileOpen += this.FolderItemsView_OnFileOpen; TreeBrowser.BrowseEvent += FolderTextPath_BrowseEvent; // Event fires when the user requests to add a folder into the list of recently visited folders TreeBrowser.BookmarkFolder.RequestEditBookmarkedFolders += this.FolderItemsView_RequestEditBookmarkedFolders; ExplorerSettingsModel settings = null; if (programSettings != null) { if (programSettings.SessionData != null) { settings = programSettings.SettingData.ExplorerSettings; } } if (settings == null) settings = new ExplorerSettingsModel(); if (programSettings.SessionData.LastActiveExplorer != null) settings.SetUserProfile(programSettings.SessionData.LastActiveExplorer); else settings.UserProfile.SetCurrentPath(@"C:"); if (settings.UserProfile.CurrentPath != null) _InitialPath = settings.UserProfile.CurrentPath.Path; this.ConfigureExplorerSettings(settings); this.mFileOpenMethod = this.mFileOpenService.FileOpen; } #endregion constructor #region properties /// <summary> /// Gets the viewmodel that drives the folder picker control. /// </summary> public IBrowserViewModel TreeBrowser { get; } public string FileName { get { if (string.IsNullOrEmpty(this.mFilePathName) == true) return string.Empty; try { return System.IO.Path.GetFileName(mFilePathName); } catch (Exception) { return string.Empty; } } } public string FilePath { get { if (string.IsNullOrEmpty(this.mFilePathName) == true) return string.Empty; try { return System.IO.Path.GetDirectoryName(mFilePathName); } catch (Exception) { return string.Empty; } } } /// <summary> /// ToolWindow Icon /// </summary> public override Uri IconSource { get { return new Uri("pack://application:,,,/FileListView;component/Images/Generic/Folder/folderopened_yellow_16.png", UriKind.RelativeOrAbsolute); } } #region Commands /// <summary> /// Can be executed to synchronize the current path with the currently active document. /// </summary> public ICommand SyncPathWithCurrentDocumentCommand { get { if (this.mSyncPathWithCurrentDocumentCommand == null) this.mSyncPathWithCurrentDocumentCommand = new RelayCommand<object>( (p) => this.SyncPathWithCurrentDocumentCommand_Executed(), (p) => string.IsNullOrEmpty(this.mFilePathName) == false); return this.mSyncPathWithCurrentDocumentCommand; } } #endregion Commands public override PaneLocation PreferredLocation { get { return PaneLocation.Right; } } #endregion properties #region methods /// <summary> /// Save the current user profile settings into the /// corresponding property of the SettingsManager. /// </summary> /// <param name="settingsManager"></param> /// <param name="vm"></param> public static void SaveSettings(ISettingsManager settingsManager, IExplorer vm) { var settings = vm.GetExplorerSettings(settingsManager.SettingData.ExplorerSettings); if (settings != null) // Explorer settings have changed { settingsManager.SettingData.IsDirty = true; settingsManager.SettingData.ExplorerSettings = settings; settingsManager.SessionData.LastActiveExplorer = settings.UserProfile; } else settingsManager.SessionData.LastActiveExplorer = vm.GetExplorerSettings(null).UserProfile; } #region IRegisterableToolWindow /// <summary> /// Set the document parent handling object to deactivation and activation /// of documents with content relevant to this tool window viewmodel. /// </summary> /// <param name="parent"></param> public void SetDocumentParent(IDocumentParent parent) { if (parent != null) parent.ActiveDocumentChanged -= this.OnActiveDocumentChanged; this.mParent = parent; // Check if active document is a log4net document to display data for... if (this.mParent != null) parent.ActiveDocumentChanged += new DocumentChangedEventHandler(this.OnActiveDocumentChanged); else this.OnActiveDocumentChanged(null, null); } /// <summary> /// Set the document parent handling object and visibility /// to enable tool window to react on deactivation and activation /// of documents with content relevant to this tool window viewmodel. /// </summary> /// <param name="parent"></param> /// <param name="isVisible"></param> public void SetToolWindowVisibility(IDocumentParent parent, bool isVisible = true) { if (IsVisible == true) this.SetDocumentParent(parent); else this.SetDocumentParent(null); base.SetToolWindowVisibility(isVisible); } #endregion IRegisterableToolWindow public void OnActiveDocumentChanged(object sender, DocumentChangedEventArgs e) { this.mFilePathName = string.Empty; if (e != null) { if (e.ActiveDocument != null) { if (e.ActiveDocument is FileBaseViewModel) { FileBaseViewModel f = e.ActiveDocument as FileBaseViewModel; if (f.IsFilePathReal == false) // Start page or somethin... return; try { if (File.Exists(f.FilePath) == true) { var fi = new FileInfo(f.FilePath); this.mFilePathName = f.FilePath; this.RaisePropertyChanged(() => this.FileName); this.RaisePropertyChanged(() => this.FilePath); } } catch { } } } } } /// <summary> /// Executes when the file open event is fired and class was constructed with statndard constructor. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void FolderItemsView_OnFileOpen(object sender, FileSystemModels.Events.FileOpenEventArgs e) { if (this.mFileOpenMethod != null) this.mFileOpenMethod(e.FileName); else MessageBox.Show("File Open (method is null):" + e.FileName); } /// <summary> /// Navigates to viewmodel to the <paramref name="directoryPath"/> folder. /// </summary> /// <param name="directoryPath"></param> public void NavigateToFolder(string directoryPath) { IPathModel location = null; try { if (System.IO.Directory.Exists(directoryPath) == false) directoryPath = System.IO.Directory.GetParent(directoryPath).FullName; if (System.IO.Directory.Exists(directoryPath) == false) return; location = PathFactory.Create(directoryPath); } catch { } NavigateToFolder(location); } private void SyncPathWithCurrentDocumentCommand_Executed() { if (string.IsNullOrEmpty(this.mFilePathName) == true) return; NavigateToFolder(this.mFilePathName); } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX /// <summary> /// Master controller interface method to navigate all views /// to the folder indicated in <paramref name="folder"/> /// - updates all related viewmodels. /// </summary> /// <param name="itemPath"></param> /// <param name="requestor"</param> public override void NavigateToFolder(IPathModel itemPath) { try { // XXX Todo Keep task reference, support cancel, and remove on end? var timeout = TimeSpan.FromSeconds(5); var actualTask = new Task(() => { var request = new BrowseRequest(itemPath, _CancelTokenSourc.Token); var t = Task.Factory.StartNew(() => NavigateToFolderAsync(request, null), request.CancelTok, TaskCreationOptions.LongRunning, _OneTaskScheduler); if (t.Wait(timeout) == true) return; _CancelTokenSourc.Cancel(); // Task timed out so lets abort it return; // Signal timeout here... }); actualTask.Start(); actualTask.Wait(); } catch (System.AggregateException e) { Logger.Error(e); } catch (Exception e) { Logger.Error(e); } } #region Disposable Interfaces /// <summary> /// Standard dispose method of the <seealso cref="IDisposable" /> interface. /// </summary> public void Dispose() { Dispose(true); } /// <summary> /// Source: http://www.codeproject.com/Articles/15360/Implementing-IDisposable-and-the-Dispose-Pattern-P /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (_disposed == false) { if (disposing == true) { // Dispose of the curently displayed content _OneTaskScheduler.Dispose(); _SlowStuffSemaphore.Dispose(); _CancelTokenSourc.Dispose(); } // There are no unmanaged resources to release, but // if we add them, they need to be released here. } _disposed = true; //// If it is available, make the call to the //// base class's Dispose(Boolean) method ////base.Dispose(disposing); } #endregion Disposable Interfaces /// <summary> /// Master controler interface method to navigate all views /// to the folder indicated in <paramref name="folder"/> /// - updates all related viewmodels. /// </summary> /// <param name="request"></param> private async Task<FinalBrowseResult> NavigateToFolderAsync(BrowseRequest request, object sender) { // Make sure the task always processes the last input but is not started twice await _SlowStuffSemaphore.WaitAsync(); try { var newPath = request.NewLocation; var cancel = request.CancelTok; if (cancel != null) cancel.ThrowIfCancellationRequested(); TreeBrowser.SetExternalBrowsingState(true); FolderItemsView.SetExternalBrowsingState(true); FolderTextPath.SetExternalBrowsingState(true); FinalBrowseResult browseResult = null; // Navigate TreeView to this file system location if (TreeBrowser != sender) { browseResult = await TreeBrowser.NavigateToAsync(request); if (cancel != null) cancel.ThrowIfCancellationRequested(); if (browseResult.Result != BrowseResult.Complete) return FinalBrowseResult.FromRequest(request, BrowseResult.InComplete); } // Navigate Folder ComboBox to this folder if (FolderTextPath != sender) { browseResult = await FolderTextPath.NavigateToAsync(request); if (cancel != null) cancel.ThrowIfCancellationRequested(); if (browseResult.Result != BrowseResult.Complete) return FinalBrowseResult.FromRequest(request, BrowseResult.InComplete); } if (cancel != null) cancel.ThrowIfCancellationRequested(); // Navigate Folder/File ListView to this folder if (FolderItemsView != sender) { browseResult = await FolderItemsView.NavigateToAsync(request); if (cancel != null) cancel.ThrowIfCancellationRequested(); if (browseResult.Result != BrowseResult.Complete) return FinalBrowseResult.FromRequest(request, BrowseResult.InComplete); } if (browseResult != null) { if (browseResult.Result == BrowseResult.Complete) { SelectedFolder = newPath.Path; // Log location into history of recent locations NaviHistory.Forward(newPath); } } return browseResult; } catch (Exception exp) { var result = FinalBrowseResult.FromRequest(request, BrowseResult.InComplete); result.UnexpectedError = exp; return result; } finally { TreeBrowser.SetExternalBrowsingState(true); FolderItemsView.SetExternalBrowsingState(false); FolderTextPath.SetExternalBrowsingState(false); _SlowStuffSemaphore.Release(); } } /// <summary> /// One of the controls has changed its location in the filesystem. /// This method is invoked to synchronize this change with all other controls. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FolderTextPath_BrowseEvent(object sender, FileSystemModels.Browse.BrowsingEventArgs e) { var location = e.Location; SelectedFolder = location.Path; if (e.IsBrowsing == false && e.Result == BrowseResult.Complete) { NavigateToFolder(location); } else { if (e.IsBrowsing == true) { // The sender has messaged: "I am chnaging location..." // So, we set this property to tell the others: // 1) Don't change your location now (eg.: Disable UI) // 2) We'll be back to tell you the location when we know it if (TreeBrowser != sender) TreeBrowser.SetExternalBrowsingState(true); if (FolderTextPath != sender) FolderTextPath.SetExternalBrowsingState(true); if (FolderItemsView != sender) FolderItemsView.SetExternalBrowsingState(true); } } } /// <summary> /// Initialize Explorer ViewModel as soon as view is loaded. /// This is required for virtualized controls, such as, treeviews /// since they won't synchronize with the viewmodel, otherwise. /// </summary> internal void InitialzeOnLoad() { try { if (_InitialPath != null) NavigateToFolder(_InitialPath); else NavigateToFolder(@"C:\"); } catch { NavigateToFolder(@"C:\"); } } #endregion methods } }
////////////////////////////////////////////////////////////////////////////// // // OpenMBase // // Copyright 2005-2017, Meta Alternative Ltd. All rights reserved. // // ////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.IO; using System.Reflection; namespace Meta.Scripting { #region S-Expr parser public class pospair { public string sfile; public int line; public int col; public string s; public pospair(string sf,int l, int c) { sfile = sf; line = l; col = c; s = null; } } public class Reader { static Symbol thequote = Symbol.make("quote"); static Symbol theunquote = Symbol.make("unquote"); static Symbol thesplicing = Symbol.make("unquote-splicing"); static Symbol thequasiquote = Symbol.make("quasiquote"); static Symbol annotatetag = Symbol.make("**with source info**"); private static Object tryNum(string s) { try { return System.Int32.Parse(s, System.Globalization.CultureInfo.InvariantCulture.NumberFormat); } catch (Exception e) { return Symbol.make(s); } } public static Object process(Object o) { if (o is string) { string s = (string)o; if (s[0] == '"') return s.Substring(1, s.Length - 2); if (s[0] == '&') { if ((s.Length > 1) && s[1] == '\"') { return Symbol.make(s.Substring(2, s.Length - 3)); } else { return Symbol.make(s); } } if (s[0] >= '0' && s[0] <= '9') return tryNum(s); if ((s[0] == '-' || s[0] == '+') && s.Length > 1 && (s[1] >= '0' && s[1] <= '9')) return tryNum(s); if (s.Equals("#f")) return Runtime._false; if (s.Equals("#t")) return Runtime._true; if (s.StartsWith("#\\")) { if (s.Length == 3) return s[2]; string ss = s.Substring(2, s.Length - 2); switch (ss) { case "Newline": return '\n'; case "Tab": return '\t'; case "Space": return ' '; case "LBR": return '('; case "RBR": return ')'; case "Semicolon": return ';'; } if (ss.Length > 5) { if (ss.Substring(0, 5).Equals("ASCII")) { return (char)(Int32.Parse(ss.Substring(5, ss.Length - 5))); } } if (s.Equals("#\\")) return '\\'; return Symbol.make("Char(" + s + ")"); } Symbol sym = Symbol.make(s); return sym; } else if (o is pospair) { pospair pp = (pospair)o; return new Pair(annotatetag, new Pair(new Pair(pp.sfile, new Pair(pp.line, new Pair(pp.col, null))), new Pair(process(pp.s), null))); } else if (o is Pair) { Pair p = (Pair)o; if (p.car != null) { string pc = null; if (p.car is string) { pc = (string)p.car; } else if (p.car is pospair) pc = ((pospair)(p.car)).s; if (pc != null) { Object oo = null; if (pc.Equals("'")) oo = thequote; else if (pc.Equals(",")) oo = theunquote; else if (pc.Equals("`")) oo = thequasiquote; else if (pc.Equals(",@")) oo = thesplicing; if (oo != null) return new Pair(new Pair(oo, new Pair(process(p.cadr()), null)), process(p.cddr())); } } p.car = process(p.car); p.cdr = process(p.cdr); return p; } return o; } private static bool popper(Stack st, Stack pos, Object ob) { try { if (pos.Count == 0) return false; // skip an operation int postn = (int)pos.Pop(); // get a position if (postn == 0) // car { Pair p = (Pair)st.Peek(); // don't remove it! p.car = ob; pos.Push(2); // by default - continue this list } else if (postn == 1) // cdr { Pair p = (Pair)st.Peek(); p.cdr = ob; pos.Push(-1); // don't update at all } else if (postn == 2) { Pair p = (Pair)st.Pop(); // don't need it any more Pair p1 = new Pair(ob, null); p.cdr = p1; st.Push(p1); pos.Push(2); // continue this way } return true; } catch (System.InvalidOperationException ex) { throw new Meta.Scripting.MBaseException(new Pair(Symbol.make("READER-ERROR-AT:"), ob)); } } public static Object aread(System.IO.TextReader r) { return aread(new ExtendedReader(r)); } public static Object aread(ExtendedReader r) { Object prev_p = null; Stack top = new Stack(); char[] c = new char[1]; bool rd = true; bool annotate = r.annotate; int state = 0; string s = ""; pospair strt = null; pospair crnt = null; System.Collections.Stack st = new System.Collections.Stack(); System.Collections.Stack pos = new System.Collections.Stack(); while (true) { char ch; if (!rd) { if (top.Count > 0) return top.Pop(); else return null; } int n = r.Read(c, 0, 1); if (annotate) crnt = new pospair(r.file, r.linepos, r.cpos); if (n == 0) { rd = false; // stop ch = ' '; // simulate end of something goto cont; } ch = c[0]; //Console.Write(ch); cont: if (state == 0) { switch(ch) { case '(': { // start a new list; Pair p = new Pair(null, null); top.Push(p); st.Push(p); pos.Push(0); // will fill car first prev_p = p; break; } case ')': { // pop a list if (top.Count < 1) { throw new Meta.Scripting.MBaseException(new Pair(Symbol.make("READER-ERROR-AT:"), prev_p)); } Object p = top.Pop(); if (p is Pair) { Pair pp = (Pair)p; if (pp.car == null && pp.cdr == null) p = null; } st.Pop(); // discard it pos.Pop(); //discard it if (!popper(st, pos, p)) { return p; } if (p != null) prev_p = p; state = 0; break; } case '.': { s = "" + ch; strt = crnt; state = 6; break; } case ';': { state = 4; // comment started break; } case ' ': case '\n': case '\t': case '\r': case '\f': { // just skip break; } case '\"': // start a string literal { s = "" + ch; strt = crnt; state = 2; break; } case '\'': case '`': // immediate { s = "" + ch; strt = crnt; if (!popper(st, pos, s)) return s; s = ""; break; } case ',': // delay { s = "" + ch; strt = crnt; state = 5; break; } case '&': // another delayed reader { s = "" + ch; strt = crnt; state = 7; break; } default: // all other chars starts atoms { s = "" + ch; // start a new one; strt = crnt; state = 1; // atom processing break; } } } else if (state == 1) { if (ch == '(' || ch == ')' || Char.IsWhiteSpace(ch) || ch == ';') { // atom ends here, sorry if (annotate) { strt.s = s; if (!popper(st, pos, strt)) return strt; } else { if (!popper(st, pos, s)) return s; } if(s!=null) prev_p = s; s = ""; state = 0; goto cont; // now process the termination character in a new state } else s = s + ch; // add a char to an atom } else if (state == 2) { if (ch == '\\') { state = 3; } else if (ch == '\"') { s = s + ch; state = 1; ch = ' '; // simulate an end of atom goto cont; } else { s = s + ch; } } else if (state == 3) { if (ch == 'n') ch = '\n'; else if (ch == 't') ch = '\t'; s = s + ch; state = 2; } else if (state == 4) { if (ch == '\n') state = 0; // comment line finished } else if (state == 5) { if (ch == '@') s += ch; if (!popper(st, pos, s)) return s; state = 0; if (ch != '@') goto cont; // otherwise read next char } else if (state == 6) { if (ch == '.') { s += ch; state = 1; } else { state = 0; pos.Pop(); pos.Push(1); // will fill cdr, not a new cons cell goto cont; } } else if (state == 7) { if (ch == '\"') { s += ch; state = 2; } else { state = 1; goto cont; } } } } } #endregion }
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved // This code can only be used under the standard Unity Asset Store End User License Agreement // A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms using System; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; namespace TMPro { [Serializable] public class TextMeshProFont : ScriptableObject { public FaceInfo fontInfo { get { return m_fontInfo; } } [SerializeField] private FaceInfo m_fontInfo; [SerializeField] public Texture2D atlas; // Should add a property to make this read-only. [SerializeField] public Material material; // Should add a property to make this read-only. public Dictionary<int, GlyphInfo> characterDictionary { get { return m_characterDictionary; } } private Dictionary<int, GlyphInfo> m_characterDictionary; public Dictionary<int, KerningPair> kerningDictionary { get { return m_kerningDictionary; } } private Dictionary<int, KerningPair> m_kerningDictionary; public KerningTable kerningInfo { get { return m_kerningInfo; } } [SerializeField] private KerningTable m_kerningInfo; [SerializeField] private List<GlyphInfo> m_glyphInfoList; [SerializeField] private KerningPair m_kerningPair; // Use for creating a new kerning pair in Editor Panel. [SerializeField] public bool propertiesChanged = false; private int[] m_characterSet; // Array containing all the characters in this font asset. public float NormalStyle = 0; public float BoldStyle = 0.75f; public byte ItalicStyle = 35; void OnEnable() { //Debug.Log("OnEnable has been called on " + this.name); if (m_characterDictionary == null) { //Debug.Log("Loading Dictionary for " + this.name); ReadFontDefinition(); } else { //Debug.Log("Dictionary for " + this.name + " has already been Initialized."); } } void OnDisable() { //Debug.Log("TextMeshPro Font Asset [" + this.name + "] has been disabled!"); } public void AddFaceInfo(FaceInfo faceInfo) { m_fontInfo = faceInfo; } public void AddGlyphInfo(GlyphInfo[] glyphInfo) { m_glyphInfoList = new List<GlyphInfo>(); m_characterSet = new int[m_fontInfo.CharacterCount]; for (int i = 0; i < m_fontInfo.CharacterCount; i++) { //Debug.Log("Glyph Info x:" + glyphInfo[i].x + " y:" + glyphInfo[i].y + " w:" + glyphInfo[i].width + " h:" + glyphInfo[i].height); GlyphInfo g = new GlyphInfo(); g.id = glyphInfo[i].id; g.x = glyphInfo[i].x; g.y = glyphInfo[i].y; g.width = glyphInfo[i].width; g.height = glyphInfo[i].height; g.xOffset = glyphInfo[i].xOffset; g.yOffset = (glyphInfo[i].yOffset) + m_fontInfo.Padding; // Padding added to keep baseline at Y = 0. g.xAdvance = glyphInfo[i].xAdvance; m_glyphInfoList.Add(g); // While iterating through list of glyphs, find the Descender & Ascender for this GlyphSet. m_fontInfo.Ascender = Mathf.Max(m_fontInfo.Ascender, glyphInfo[i].yOffset); m_fontInfo.Descender = Mathf.Min(m_fontInfo.Descender, glyphInfo[i].yOffset - glyphInfo[i].height); m_characterSet[i] = g.id; // Add Character ID to Array to make it easier to get the kerning pairs. } // Sort List by ID. m_glyphInfoList = m_glyphInfoList.OrderBy(s => s.id).ToList(); } public void AddKerningInfo(KerningTable kerningTable) { m_kerningInfo = kerningTable; } public void ReadFontDefinition() { //Debug.Log("Reading Font Definition for " + this.name + "."); // Make sure that we have a Font Asset file assigned. if (m_fontInfo == null) { return; } // Create new instance of GlyphInfo Dictionary for fast access to glyph info. m_characterDictionary = new Dictionary<int, GlyphInfo>(); foreach (GlyphInfo glyph in m_glyphInfoList) { if (!m_characterDictionary.ContainsKey(glyph.id)) m_characterDictionary.Add(glyph.id, glyph); } //Debug.Log("PRE: BaseLine:" + m_fontInfo.Baseline + " Ascender:" + m_fontInfo.Ascender + " Descender:" + m_fontInfo.Descender); // + " Centerline:" + m_fontInfo.CenterLine); GlyphInfo temp_charInfo = new GlyphInfo(); // Add Character (10) LineFeed, (13) Carriage Return & Space (32) to Dictionary if they don't exists. m_characterDictionary.TryGetValue(10, out temp_charInfo); if (temp_charInfo == null) { // Modify Character [64] to create Char[32] if (m_characterDictionary.ContainsKey(32) == false) { Debug.Log("Adding Character 32 (Space) to Dictionary for Font (" + m_fontInfo.Name + ")."); temp_charInfo = new GlyphInfo(); temp_charInfo.id = 32; temp_charInfo.x = 0; // m_characterDictionary[32].x; temp_charInfo.y = 0; // m_characterDictionary[32].y; temp_charInfo.width = 0; // m_characterDictionary[32].width; temp_charInfo.height = 0; // m_characterDictionary[32].height; temp_charInfo.xOffset = 0; // m_characterDictionary[32].xOffset; temp_charInfo.yOffset = 0; // m_characterDictionary[32].yOffset; temp_charInfo.xAdvance = m_fontInfo.PointSize / 4; // m_characterDictionary[32].xAdvance; m_characterDictionary.Add(32, temp_charInfo); //m_characterDictionary.Add(13, temp_charInfo); } temp_charInfo = new GlyphInfo(); temp_charInfo.id = 10; temp_charInfo.x = m_characterDictionary[32].x; temp_charInfo.y = m_characterDictionary[32].y; temp_charInfo.width = m_characterDictionary[32].width; temp_charInfo.height = m_characterDictionary[32].height; temp_charInfo.xOffset = m_characterDictionary[32].xOffset; temp_charInfo.yOffset = m_characterDictionary[32].yOffset; temp_charInfo.xAdvance = m_characterDictionary[32].xAdvance; m_characterDictionary.Add(10, temp_charInfo); m_characterDictionary.Add(13, temp_charInfo); } // Add Tab Character to Dictionary. Tab is Tab Size * Space Character Width. int tabSize = 10; temp_charInfo = new GlyphInfo(); temp_charInfo.id = 9; temp_charInfo.x = m_characterDictionary[32].x; temp_charInfo.y = m_characterDictionary[32].y; temp_charInfo.width = m_characterDictionary[32].width * tabSize; temp_charInfo.height = m_characterDictionary[32].height; temp_charInfo.xOffset = m_characterDictionary[32].xOffset; temp_charInfo.yOffset = m_characterDictionary[32].yOffset; temp_charInfo.xAdvance = m_characterDictionary[32].xAdvance * tabSize; m_characterDictionary.Add(9, temp_charInfo); // Centerline is located at the center of character like { or in the middle of the lowercase o. //m_fontInfo.CenterLine = m_characterDictionary[111].yOffset - m_characterDictionary[111].height * 0.5f; // Tab Width is the same the xAdvance of the letter A. (Could change this to space 32). m_fontInfo.TabWidth = m_characterDictionary[65].xAdvance; // Populate Dictionary with Kerning Information m_kerningDictionary = new Dictionary<int, KerningPair>(); List<KerningPair> pairs = m_kerningInfo.kerningPairs; //Debug.Log(m_fontInfo.Name + " has " + pairs.Count + " Kerning Pairs."); for (int i = 0; i < pairs.Count; i++) { KerningPair pair = pairs[i]; KerningPairKey uniqueKey = new KerningPairKey(pair.AscII_Left, pair.AscII_Right); if (m_kerningDictionary.ContainsKey(uniqueKey.key) == false) m_kerningDictionary.Add(uniqueKey.key, pair); else Debug.Log("Kerning Key for [" + uniqueKey.ascii_Left + "] and [" + uniqueKey.ascii_Right + "] already exists."); } } } }
// 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; using Xunit.Abstractions; using System.IO; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_GlobalTypes", Desc = "")] public class TC_SchemaSet_GlobalTypes : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_GlobalTypes(ITestOutputHelper output) { _output = output; } public XmlSchema GetSchema(string ns, string type1, string type2) { string xsd = string.Empty; if (ns.Equals(string.Empty)) xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema'><complexType name='" + type1 + "'><sequence><element name='local'/></sequence></complexType><simpleType name='" + type2 + "'><restriction base='int'/></simpleType></schema>"; else xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema' targetNamespace='" + ns + "'><complexType name='" + type1 + "'><sequence><element name='local'/></sequence></complexType><simpleType name='" + type2 + "'><restriction base='int'/></simpleType></schema>"; XmlSchema schema = XmlSchema.Read(new StringReader(xsd), null); return schema; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v1 - GlobalTypes on empty collection")] [Fact] public void v1() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaObjectTable table = sc.GlobalTypes; CError.Compare(table == null, false, "Count"); return; } //----------------------------------------------------------------------------------- // params is a pair of the following info: (namaespace, type1 type2) two schemas are made from this info //[Variation(Desc = "v2.1 - GlobalTypes with set with two schemas, both without NS", Params = new object[] { "", "t1", "t2", "", "t3", "t4" })] [InlineData("", "t1", "t2", "", "t3", "t4")] //[Variation(Desc = "v2.2 - GlobalTypes with set with two schemas, one without NS one with NS", Params = new object[] { "a", "t1", "t2", "", "t3", "t4" })] [InlineData("a", "t1", "t2", "", "t3", "t4")] //[Variation(Desc = "v2.2 - GlobalTypes with set with two schemas, both with NS", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4" })] [InlineData("a", "t1", "t2", "b", "t3", "t4")] [Theory] public void v2(object param0, object param1, object param2, object param3, object param4, object param5) { string ns1 = param0.ToString(); string ns2 = param3.ToString(); string type1 = param1.ToString(); string type2 = param2.ToString(); string type3 = param4.ToString(); string type4 = param5.ToString(); XmlSchema s1 = GetSchema(ns1, type1, type2); XmlSchema s2 = GetSchema(ns2, type3, type4); XmlSchemaSet ss = new XmlSchemaSet(); ss.Add(s1); CError.Compare(ss.GlobalTypes.Count, 0, "Types Count after add"); ss.Compile(); ss.Add(s2); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after add/compile"); //+1 for anyType ss.Compile(); //Verify CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after add/compile/add/compile"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4"); //Now reprocess one schema and check ss.Reprocess(s1); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after repr"); //+1 for anyType ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after repr/comp"); //+1 for anyType //Now Remove one schema and check ss.Remove(s1); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove"); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove/comp"); return; } // params is a pair of the following info: (namaespace, type1 type2)*, doCompile? //[Variation(Desc = "v3.1 - GlobalTypes with a set having schema (nons) to another set with schema(nons)", Params = new object[] { "", "t1", "t2", "", "t3", "t4", true })] [InlineData("", "t1", "t2", "", "t3", "t4", true)] //[Variation(Desc = "v3.2 - GlobalTypes with a set having schema (ns) to another set with schema(nons)", Params = new object[] { "a", "t1", "t2", "", "t3", "t4", true })] [InlineData("a", "t1", "t2", "", "t3", "t4", true)] //[Variation(Desc = "v3.3 - GlobalTypes with a set having schema (nons) to another set with schema(ns)", Params = new object[] { "", "t1", "t2", "a", "t3", "t4", true })] [InlineData("", "t1", "t2", "a", "t3", "t4", true)] //[Variation(Desc = "v3.4 - GlobalTypes with a set having schema (ns) to another set with schema(ns)", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4", true })] [InlineData("a", "t1", "t2", "b", "t3", "t4", true)] //[Variation(Desc = "v3.5 - GlobalTypes with a set having schema (nons) to another set with schema(nons), no compile", Params = new object[] { "", "t1", "t2", "", "t3", "t4", false })] [InlineData("", "t1", "t2", "", "t3", "t4", false)] //[Variation(Desc = "v3.6 - GlobalTypes with a set having schema (ns) to another set with schema(nons), no compile", Params = new object[] { "a", "t1", "t2", "", "t3", "t4", false })] [InlineData("a", "t1", "t2", "", "t3", "t4", false)] //[Variation(Desc = "v3.7 - GlobalTypes with a set having schema (nons) to another set with schema(ns), no compile", Params = new object[] { "", "t1", "t2", "a", "t3", "t4", false })] [InlineData("", "t1", "t2", "a", "t3", "t4", false)] //[Variation(Desc = "v3.8 - GlobalTypes with a set having schema (ns) to another set with schema(ns), no compile", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4", false })] [InlineData("a", "t1", "t2", "b", "t3", "t4", false)] [Theory] public void v3(object param0, object param1, object param2, object param3, object param4, object param5, object param6) { string ns1 = param0.ToString(); string ns2 = param3.ToString(); string type1 = param1.ToString(); string type2 = param2.ToString(); string type3 = param4.ToString(); string type4 = param5.ToString(); bool doCompile = (bool)param6; XmlSchema s1 = GetSchema(ns1, type1, type2); XmlSchema s2 = GetSchema(ns2, type3, type4); XmlSchemaSet ss1 = new XmlSchemaSet(); XmlSchemaSet ss2 = new XmlSchemaSet(); ss1.Add(s1); ss1.Compile(); ss2.Add(s2); if (doCompile) ss2.Compile(); // add one schemaset to another ss1.Add(ss2); if (!doCompile) ss1.Compile(); //Verify CError.Compare(ss1.GlobalTypes.Count, 5, "Types Count after add/comp"); //+1 for anyType CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4"); //Now reprocess one schema and check ss1.Reprocess(s1); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count repr"); //+1 for anyType ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 5, "Types Count repr/comp"); //+1 for anyType //Now Remove one schema and check ss1.Remove(s1); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count after remove"); ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count after rem/comp"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v4.1 - GlobalTypes with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B" })] [InlineData("import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B")] //[Variation(Desc = "v4.2 - GlobalTypes with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B" })] [InlineData("import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B")] [Theory] public void v4(object param0, object param1, object param2, object param3, object param4) { string uri1 = param0.ToString(); string ns1 = param1.ToString(); string type1 = param2.ToString(); string ns2 = param3.ToString(); string type2 = param4.ToString(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); XmlSchema schema1 = ss.Add(null, Path.Combine(TestData._Root, uri1)); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), true, "Contains2"); //get the SOM for the imported schema foreach (XmlSchema s in ss.Schemas(ns2)) { ss.Remove(s); } ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 2, "Types Count after Remove"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), false, "Contains2"); return; } //[Variation(Desc = "v5.1 - GlobalTypes with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B" })] [InlineData("import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B")] //[Variation(Desc = "v5.2 - GlobalTypes with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B" })] [InlineData("import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B")] [Theory] public void v5(object param0, object param1, object param2, object param3, object param4) { string uri1 = param0.ToString(); string ns1 = param1.ToString(); string type1 = param2.ToString(); string ns2 = param3.ToString(); string type2 = param4.ToString(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "xsdauthor.xsd")); XmlSchema schema1 = ss.Add(null, Path.Combine(TestData._Root, uri1)); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), true, "Contains2"); ss.RemoveRecursive(schema1); // should not need to compile for RemoveRecursive to take effect CError.Compare(ss.GlobalTypes.Count, 1, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), false, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), false, "Contains2"); return; } //----------------------------------------------------------------------------------- //REGRESSIONS //[Variation(Desc = "v100 - XmlSchemaSet: Components are not added to the global tabels if it is already compiled", Priority = 1)] [Fact] public void v100() { try { // anytype t1 t2 XmlSchema schema1 = XmlSchema.Read(new StringReader("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='a'><xs:element name='e1' type='xs:anyType'/><xs:complexType name='t1'/><xs:complexType name='t2'/></xs:schema>"), null); // anytype t3 t4 XmlSchema schema2 = XmlSchema.Read(new StringReader("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' ><xs:element name='e1' type='xs:anyType'/><xs:complexType name='t3'/><xs:complexType name='t4'/></xs:schema>"), null); XmlSchemaSet ss1 = new XmlSchemaSet(); XmlSchemaSet ss2 = new XmlSchemaSet(); ss1.Add(schema1); ss2.Add(schema2); ss2.Compile(); ss1.Add(ss2); ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 5, "Count"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName("t1", "a")), true, "Contains"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName("t2", "a")), true, "Contains"); } catch (Exception e) { _output.WriteLine(e.Message); Assert.True(false); } return; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using Xunit; namespace System.Collections.Immutable.Test { public class ImmutableSortedSetTest : ImmutableSetTest { private enum Operation { Add, Union, Remove, Except, Last, } protected override bool IncludesGetHashCodeDerivative { get { return false; } } [Fact] public void RandomOperationsTest() { int operationCount = this.RandomOperationsCount; var expected = new SortedSet<int>(); var actual = ImmutableSortedSet<int>.Empty; int seed = (int)DateTime.Now.Ticks; Console.WriteLine("Using random seed {0}", seed); var random = new Random(seed); for (int iOp = 0; iOp < operationCount; iOp++) { switch ((Operation)random.Next((int)Operation.Last)) { case Operation.Add: int value = random.Next(); Console.WriteLine("Adding \"{0}\" to the set.", value); expected.Add(value); actual = actual.Add(value); break; case Operation.Union: int inputLength = random.Next(100); int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray(); Console.WriteLine("Adding {0} elements to the set.", inputLength); expected.UnionWith(values); actual = actual.Union(values); break; case Operation.Remove: if (expected.Count > 0) { int position = random.Next(expected.Count); int element = expected.Skip(position).First(); Console.WriteLine("Removing element \"{0}\" from the set.", element); Assert.True(expected.Remove(element)); actual = actual.Remove(element); } break; case Operation.Except: var elements = expected.Where(el => random.Next(2) == 0).ToArray(); Console.WriteLine("Removing {0} elements from the set.", elements.Length); expected.ExceptWith(elements); actual = actual.Except(elements); break; } Assert.Equal<int>(expected.ToList(), actual.ToList()); } } [Fact] public void EmptyTest() { this.EmptyTestHelper(Empty<int>(), 5, null); this.EmptyTestHelper(Empty<string>().ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase); } [Fact] public void CustomSort() { this.CustomSortTestHelper( ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.Ordinal), true, new[] { "apple", "APPLE" }, new[] { "APPLE", "apple" }); this.CustomSortTestHelper( ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase), true, new[] { "apple", "APPLE" }, new[] { "apple" }); } [Fact] public void ChangeSortComparer() { var ordinalSet = ImmutableSortedSet<string>.Empty .WithComparer(StringComparer.Ordinal) .Add("apple") .Add("APPLE"); Assert.Equal(2, ordinalSet.Count); // claimed count Assert.False(ordinalSet.Contains("aPpLe")); var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase); Assert.Equal(1, ignoreCaseSet.Count); Assert.True(ignoreCaseSet.Contains("aPpLe")); } [Fact] public void ToUnorderedTest() { var result = ImmutableSortedSet<int>.Empty.Add(3).ToImmutableHashSet(); Assert.True(result.Contains(3)); } [Fact] public void ToImmutableSortedSetTest() { var set = new[] { 1, 2, 2 }.ToImmutableSortedSet(); Assert.Same(Comparer<int>.Default, set.KeyComparer); Assert.Equal(2, set.Count); } [Fact] public void IndexOfTest() { var set = ImmutableSortedSet<int>.Empty; Assert.Equal(~0, set.IndexOf(5)); set = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100 Assert.Equal(0, set.IndexOf(10)); Assert.Equal(1, set.IndexOf(20)); Assert.Equal(4, set.IndexOf(50)); Assert.Equal(8, set.IndexOf(90)); Assert.Equal(9, set.IndexOf(100)); Assert.Equal(~0, set.IndexOf(5)); Assert.Equal(~1, set.IndexOf(15)); Assert.Equal(~2, set.IndexOf(25)); Assert.Equal(~5, set.IndexOf(55)); Assert.Equal(~9, set.IndexOf(95)); Assert.Equal(~10, set.IndexOf(105)); } [Fact] public void IndexGetTest() { var set = ImmutableSortedSet<int>.Empty .Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100 int i = 0; foreach (var item in set) { AssertAreSame(item, set[i++]); } Assert.Throws<ArgumentOutOfRangeException>(() => set[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => set[set.Count]); } [Fact] public void ReverseTest() { var range = Enumerable.Range(1, 10); var set = ImmutableSortedSet<int>.Empty.Union(range); var expected = range.Reverse().ToList(); var actual = set.Reverse().ToList(); Assert.Equal<int>(expected, actual); } [Fact] public void MaxTest() { Assert.Equal(5, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Max); Assert.Equal(0, ImmutableSortedSet<int>.Empty.Max); } [Fact] public void MinTest() { Assert.Equal(1, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Min); Assert.Equal(0, ImmutableSortedSet<int>.Empty.Min); } [Fact] public void InitialBulkAdd() { Assert.Equal(1, Empty<int>().Union(new[] { 1, 1 }).Count); Assert.Equal(2, Empty<int>().Union(new[] { 1, 2 }).Count); } [Fact] public void ICollectionOfTMethods() { ICollection<string> set = ImmutableSortedSet.Create<string>(); Assert.Throws<NotSupportedException>(() => set.Add("a")); Assert.Throws<NotSupportedException>(() => set.Clear()); Assert.Throws<NotSupportedException>(() => set.Remove("a")); Assert.True(set.IsReadOnly); } [Fact] public void IListOfTMethods() { IList<string> set = ImmutableSortedSet.Create<string>("b"); Assert.Throws<NotSupportedException>(() => set.Insert(0, "a")); Assert.Throws<NotSupportedException>(() => set.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => set[0] = "a"); Assert.Equal("b", set[0]); Assert.True(set.IsReadOnly); } [Fact] public void UnionOptimizationsTest() { var set = ImmutableSortedSet.Create(1, 2, 3); var builder = set.ToBuilder(); Assert.Same(set, ImmutableSortedSet.Create<int>().Union(builder)); Assert.Same(set, set.Union(ImmutableSortedSet.Create<int>())); var smallSet = ImmutableSortedSet.Create(1); var unionSet = smallSet.Union(set); Assert.Same(set, unionSet); // adding a larger set to a smaller set is reversed, and then the smaller in this case has nothing unique } [Fact] public void Create() { var comparer = StringComparer.OrdinalIgnoreCase; var set = ImmutableSortedSet.Create<string>(); Assert.Equal(0, set.Count); Assert.Same(Comparer<string>.Default, set.KeyComparer); set = ImmutableSortedSet.Create<string>(comparer); Assert.Equal(0, set.Count); Assert.Same(comparer, set.KeyComparer); set = ImmutableSortedSet.Create("a"); Assert.Equal(1, set.Count); Assert.Same(Comparer<string>.Default, set.KeyComparer); set = ImmutableSortedSet.Create(comparer, "a"); Assert.Equal(1, set.Count); Assert.Same(comparer, set.KeyComparer); set = ImmutableSortedSet.Create("a", "b"); Assert.Equal(2, set.Count); Assert.Same(Comparer<string>.Default, set.KeyComparer); set = ImmutableSortedSet.Create(comparer, "a", "b"); Assert.Equal(2, set.Count); Assert.Same(comparer, set.KeyComparer); set = ImmutableSortedSet.CreateRange((IEnumerable<string>)new[] { "a", "b" }); Assert.Equal(2, set.Count); Assert.Same(Comparer<string>.Default, set.KeyComparer); set = ImmutableSortedSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" }); Assert.Equal(2, set.Count); Assert.Same(comparer, set.KeyComparer); } [Fact] public void IListMethods() { IList list = ImmutableSortedSet.Create("a", "b"); Assert.True(list.Contains("a")); Assert.Equal("a", list[0]); Assert.Equal("b", list[1]); Assert.Equal(0, list.IndexOf("a")); Assert.Equal(1, list.IndexOf("b")); Assert.Throws<NotSupportedException>(() => list.Add("b")); Assert.Throws<NotSupportedException>(() => list[3] = "c"); Assert.Throws<NotSupportedException>(() => list.Clear()); Assert.Throws<NotSupportedException>(() => list.Insert(0, "b")); Assert.Throws<NotSupportedException>(() => list.Remove("a")); Assert.Throws<NotSupportedException>(() => list.RemoveAt(0)); Assert.True(list.IsFixedSize); Assert.True(list.IsReadOnly); } [Fact] public void TryGetValueTest() { this.TryGetValueTestHelper(ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase)); } [Fact] public void EnumeratorRecyclingMisuse() { var collection = ImmutableSortedSet.Create<int>(); var enumerator = collection.GetEnumerator(); var enumeratorCopy = enumerator; Assert.False(enumerator.MoveNext()); enumerator.Dispose(); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current); enumerator.Dispose(); // double-disposal should not throw enumeratorCopy.Dispose(); // We expect that acquiring a new enumerator will use the same underlying Stack<T> object, // but that it will not throw exceptions for the new enumerator. enumerator = collection.GetEnumerator(); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Dispose(); } protected override IImmutableSet<T> Empty<T>() { return ImmutableSortedSet<T>.Empty; } protected ImmutableSortedSet<T> EmptyTyped<T>() { return ImmutableSortedSet<T>.Empty; } protected override ISet<T> EmptyMutable<T>() { return new SortedSet<T>(); } /// <summary> /// Tests various aspects of a sorted set. /// </summary> /// <typeparam name="T">The type of element stored in the set.</typeparam> /// <param name="emptySet">The empty set.</param> /// <param name="value">A value that could be placed in the set.</param> /// <param name="comparer">The comparer used to obtain the empty set, if any.</param> private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IComparer<T> comparer) { Contract.Requires(emptySet != null); this.EmptyTestHelper(emptySet); Assert.Same(emptySet, emptySet.ToImmutableSortedSet(comparer)); Assert.Same(comparer ?? Comparer<T>.Default, ((ISortKeyCollection<T>)emptySet).KeyComparer); var reemptied = emptySet.Add(value).Clear(); Assert.Same(reemptied, reemptied.ToImmutableSortedSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer."); } } }
// // Copyright 2012, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; using Xamarin.Utilities; #if PLATFORM_IOS using AuthenticateUIType = MonoTouch.UIKit.UIViewController; #elif PLATFORM_ANDROID using AuthenticateUIType = Android.Content.Intent; using UIContext = Android.Content.Context; #else using AuthenticateUIType = System.Object; #endif namespace Xamarin.Auth { /// <summary> /// A process and user interface to authenticate a user. /// </summary> #if XAMARIN_AUTH_INTERNAL internal abstract class Authenticator #else public abstract class Authenticator #endif { /// <summary> /// Title of any UI elements that need to be presented for this authenticator. /// </summary> public string Title { get; set; } /// <summary> /// Occurs when authentication has been successfully or unsuccessfully completed. /// Consult the <see cref="AuthenticatorCompletedEventArgs.IsAuthenticated"/> event argument to determine if /// authentication was successful. /// </summary> public event EventHandler<AuthenticatorCompletedEventArgs> Completed; /// <summary> /// Occurs when there an error is encountered when authenticating. /// </summary> public event EventHandler<AuthenticatorErrorEventArgs> Error; /// <summary> /// Whether this authenticator has completed its interaction with the user. /// </summary> public bool HasCompleted { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.Authenticator"/> class. /// </summary> public Authenticator () { Title = "Authenticate"; HasCompleted = false; } #if PLATFORM_ANDROID UIContext context; public AuthenticateUIType GetUI (UIContext context) { this.context = context; return GetPlatformUI (context); } protected abstract AuthenticateUIType GetPlatformUI (UIContext context); #else /// <summary> /// Gets the UI for this authenticator. /// </summary> /// <returns> /// The UI that needs to be presented. /// </returns> public AuthenticateUIType GetUI () { return GetPlatformUI (); } /// <summary> /// Gets the UI for this authenticator. /// </summary> /// <returns> /// The UI that needs to be presented. /// </returns> protected abstract AuthenticateUIType GetPlatformUI (); #endif /// <summary> /// Implementations must call this function when they have successfully authenticated. /// </summary> /// <param name='account'> /// The authenticated account. /// </param> public void OnSucceeded (Account account) { if (HasCompleted) return; HasCompleted = true; BeginInvokeOnUIThread (delegate { var ev = Completed; if (ev != null) { ev (this, new AuthenticatorCompletedEventArgs (account)); } }); } /// <summary> /// Implementations must call this function when they have successfully authenticated. /// </summary> /// <param name='username'> /// User name of the account. /// </param> /// <param name='accountProperties'> /// Additional data, such as access tokens, that need to be stored with the account. This /// information is secured. /// </param> public void OnSucceeded (string username, IDictionary<string, string> accountProperties) { OnSucceeded (new Account (username, accountProperties)); } /// <summary> /// Implementations must call this function when they have cancelled the operation. /// </summary> public void OnCancelled () { if (HasCompleted) return; HasCompleted = true; BeginInvokeOnUIThread (delegate { var ev = Completed; if (ev != null) { ev (this, new AuthenticatorCompletedEventArgs (null)); } }); } /// <summary> /// Implementations must call this function when they have failed to authenticate. /// </summary> /// <param name='message'> /// The reason that this authentication has failed. /// </param> public void OnError (string message) { BeginInvokeOnUIThread (delegate { var ev = Error; if (ev != null) { ev (this, new AuthenticatorErrorEventArgs (message)); } }); } /// <summary> /// Implementations must call this function when they have failed to authenticate. /// </summary> /// <param name='exception'> /// The reason that this authentication has failed. /// </param> public void OnError (Exception exception) { BeginInvokeOnUIThread (delegate { var ev = Error; if (ev != null) { ev (this, new AuthenticatorErrorEventArgs (exception)); } }); } void BeginInvokeOnUIThread (Action action) { #if PLATFORM_IOS MonoTouch.UIKit.UIApplication.SharedApplication.BeginInvokeOnMainThread (delegate { action (); }); #elif PLATFORM_ANDROID var a = context as Android.App.Activity; if (a != null) { a.RunOnUiThread (action); } else { action (); } #else action (); #endif } } /// <summary> /// Authenticator completed event arguments. /// </summary> #if XAMARIN_AUTH_INTERNAL internal class AuthenticatorCompletedEventArgs : EventArgs #else public class AuthenticatorCompletedEventArgs : EventArgs #endif { /// <summary> /// Whether the authentication succeeded and there is a valid <see cref="Account"/>. /// </summary> /// <value> /// <see langword="true"/> if the user is authenticated; otherwise, <see langword="false"/>. /// </value> public bool IsAuthenticated { get { return Account != null; } } /// <summary> /// Gets the account created that represents this authentication. /// </summary> /// <value> /// The account. /// </value> public Account Account { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorCompletedEventArgs"/> class. /// </summary> /// <param name='account'> /// The account created or <see langword="null"/> if authentication failed or was canceled. /// </param> public AuthenticatorCompletedEventArgs (Account account) { Account = account; } } /// <summary> /// Authenticator error event arguments. /// </summary> #if XAMARIN_AUTH_INTERNAL internal class AuthenticatorErrorEventArgs : EventArgs #else public class AuthenticatorErrorEventArgs : EventArgs #endif { /// <summary> /// Gets a message describing the error. /// </summary> /// <value> /// The message. /// </value> public string Message { get; private set; } /// <summary> /// Gets the exception that signaled the error if there was one. /// </summary> /// <value> /// The exception or <see langword="null"/>. /// </value> public Exception Exception { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorErrorEventArgs"/> class /// with a message but no exception. /// </summary> /// <param name='message'> /// A message describing the error. /// </param> public AuthenticatorErrorEventArgs (string message) { Message = message; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorErrorEventArgs"/> class with an exception. /// </summary> /// <param name='exception'> /// The exception signaling the error. The message of this object is retrieved from this exception or /// its inner exceptions. /// </param> public AuthenticatorErrorEventArgs (Exception exception) { Message = exception.GetUserMessage (); Exception = exception; } } }
#if !READ_ONLY using System; using System.Collections.Generic; using System.IO; using System.Linq; using SR = System.Reflection; using System.Runtime.CompilerServices; using Mono.Cecil.Cil; using NUnit.Framework; namespace Mono.Cecil.Tests { [TestFixture] public class ImportCecilTests : BaseTestFixture { [Test] public void ImportStringByRef () { var get_string = Compile<Func<string, string>> ((module, body) => { var type = module.Types [1]; var method_by_ref = new MethodDefinition { Name = "ModifyString", IsPrivate = true, IsStatic = true, }; type.Methods.Add (method_by_ref); method_by_ref.MethodReturnType.ReturnType = module.ImportReference (typeof (void).ToDefinition ()); method_by_ref.Parameters.Add (new ParameterDefinition (module.ImportReference (typeof (string).ToDefinition ()))); method_by_ref.Parameters.Add (new ParameterDefinition (module.ImportReference (new ByReferenceType (typeof (string).ToDefinition ())))); var m_il = method_by_ref.Body.GetILProcessor (); m_il.Emit (OpCodes.Ldarg_1); m_il.Emit (OpCodes.Ldarg_0); m_il.Emit (OpCodes.Stind_Ref); m_il.Emit (OpCodes.Ret); var v_0 = new VariableDefinition (module.ImportReference (typeof (string).ToDefinition ())); body.Variables.Add (v_0); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Stloc, v_0); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldloca, v_0); il.Emit (OpCodes.Call, method_by_ref); il.Emit (OpCodes.Ldloc_0); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("foo", get_string ("foo")); } [Test] public void ImportStringArray () { var identity = Compile<Func<string [,], string [,]>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ret); }); var array = new string [2, 2]; Assert.AreEqual (array, identity (array)); } [Test] public void ImportFieldStringEmpty () { var get_empty = Compile<Func<string>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldsfld, module.ImportReference (typeof (string).GetField ("Empty").ToDefinition ())); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("", get_empty ()); } [Test] public void ImportStringConcat () { var concat = Compile<Func<string, string, string>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Call, module.ImportReference (typeof (string).GetMethod ("Concat", new [] { typeof (string), typeof (string) }).ToDefinition ())); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("FooBar", concat ("Foo", "Bar")); } public class Generic<T> { public T Field; public T Method (T t) { return t; } public TS GenericMethod<TS> (T t, TS s) { return s; } public Generic<TS> ComplexGenericMethod<TS> (T t, TS s) { return new Generic<TS> { Field = s }; } } [Test] public void ImportGenericField () { var get_field = Compile<Func<Generic<string>, string>> ((module, body) => { var generic_def = module.ImportReference (typeof (Generic<>)).Resolve (); var field_def = generic_def.Fields.Where (f => f.Name == "Field").First (); var field_string = field_def.MakeGeneric (module.ImportReference (typeof (string))); var field_ref = module.ImportReference (field_string); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldfld, field_ref); il.Emit (OpCodes.Ret); }); var generic = new Generic<string> { Field = "foo", }; Assert.AreEqual ("foo", get_field (generic)); } [Test] public void ImportGenericMethod () { var generic_identity = Compile<Func<Generic<int>, int, int>> ((module, body) => { var generic_def = module.ImportReference (typeof (Generic<>)).Resolve (); var method_def = generic_def.Methods.Where (m => m.Name == "Method").First (); var method_int = method_def.MakeGeneric (module.ImportReference (typeof (int))); var method_ref = module.ImportReference (method_int); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Callvirt, method_ref); il.Emit (OpCodes.Ret); }); Assert.AreEqual (42, generic_identity (new Generic<int> (), 42)); } [Test] public void ImportGenericMethodSpec () { var gen_spec_id = Compile<Func<Generic<string>, int, int>> ((module, body) => { var generic_def = module.ImportReference (typeof (Generic<>)).Resolve (); var method_def = generic_def.Methods.Where (m => m.Name == "GenericMethod").First (); var method_string = method_def.MakeGeneric (module.ImportReference (typeof (string))); var method_instance = method_string.MakeGenericMethod (module.ImportReference (typeof (int))); var method_ref = module.ImportReference (method_instance); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Callvirt, method_ref); il.Emit (OpCodes.Ret); }); Assert.AreEqual (42, gen_spec_id (new Generic<string> (), 42)); } [Test] public void ImportComplexGenericMethodSpec () { var gen_spec_id = Compile<Func<Generic<string>, int, int>> ((module, body) => { var generic_def = module.ImportReference (typeof (Generic<>)).Resolve (); var method_def = generic_def.Methods.Where (m => m.Name == "ComplexGenericMethod").First (); var method_string = method_def.MakeGeneric (module.ImportReference (typeof (string))); var method_instance = method_string.MakeGenericMethod (module.ImportReference (typeof (int))); var method_ref = module.ImportReference (method_instance); var field_def = generic_def.Fields.Where (f => f.Name == "Field").First (); var field_int = field_def.MakeGeneric (module.ImportReference (typeof (int))); var field_ref = module.ImportReference (field_int); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Callvirt, method_ref); il.Emit (OpCodes.Ldfld, field_ref); il.Emit (OpCodes.Ret); }); Assert.AreEqual (42, gen_spec_id (new Generic<string> (), 42)); } [Test] public void ImportMethodOnOpenGeneric () { var generic = typeof (Generic<>).ToDefinition (); using (var module = ModuleDefinition.CreateModule ("foo", ModuleKind.Dll)) { var method = module.ImportReference (generic.GetMethod ("Method")); Assert.AreEqual ("T Mono.Cecil.Tests.ImportCecilTests/Generic`1::Method(T)", method.FullName); } } public class ContextGeneric1Method2<G1> { public G1 GenericMethod<R1, S1> (R1 r, S1 s) { return default (G1); } } public class ContextGeneric2Method1<G2, H2> { public R2 GenericMethod<R2> (G2 g, H2 h) { return default (R2); } } public class NestedGenericsA<A> { public class NestedGenericsB<B> { public class NestedGenericsC<C> { public A GenericMethod (B b, C c) { return default (A); } } } } [Test] public void ContextGenericTest () { if (Platform.OnCoreClr) return; var module = ModuleDefinition.ReadModule (typeof (ContextGeneric1Method2<>).Module.FullyQualifiedName); // by mixing open generics with 2 & 1 parameters, we make sure the right context is used (because otherwise, an exception will be thrown) var type = typeof (ContextGeneric1Method2<>).MakeGenericType (typeof (ContextGeneric2Method1<,>)); var meth = type.GetMethod ("GenericMethod"); var imported_type = module.ImportReference (type); var method = module.ImportReference (meth, imported_type); Assert.AreEqual ("G1 Mono.Cecil.Tests.ImportCecilTests/ContextGeneric1Method2`1<Mono.Cecil.Tests.ImportCecilTests/ContextGeneric2Method1`2<G2,H2>>::GenericMethod<R1,S1>(R1,S1)", method.FullName); // and the other way around type = typeof (ContextGeneric2Method1<,>).MakeGenericType (typeof (ContextGeneric1Method2<>), typeof (IList<>)); meth = type.GetMethod ("GenericMethod"); imported_type = module.ImportReference (type); method = module.ImportReference (meth, imported_type); Assert.AreEqual ("R2 Mono.Cecil.Tests.ImportCecilTests/ContextGeneric2Method1`2<Mono.Cecil.Tests.ImportCecilTests/ContextGeneric1Method2`1<G1>,System.Collections.Generic.IList`1<T>>::GenericMethod<R2>(G2,H2)", method.FullName); // not sure about this one type = typeof (NestedGenericsA<string>.NestedGenericsB<int>.NestedGenericsC<float>); meth = type.GetMethod ("GenericMethod"); imported_type = module.ImportReference (type); method = module.ImportReference (meth, imported_type); Assert.AreEqual ("A Mono.Cecil.Tests.ImportCecilTests/NestedGenericsA`1/NestedGenericsB`1/NestedGenericsC`1<System.String,System.Int32,System.Single>::GenericMethod(B,C)", method.FullName); // We need both the method & type ! type = typeof (Generic<>).MakeGenericType (typeof (string)); meth = type.GetMethod ("ComplexGenericMethod"); imported_type = module.ImportReference (type); method = module.ImportReference (meth, imported_type); Assert.AreEqual ("Mono.Cecil.Tests.ImportCecilTests/Generic`1<TS> Mono.Cecil.Tests.ImportCecilTests/Generic`1<System.String>::ComplexGenericMethod<TS>(T,TS)", method.FullName); } delegate void Emitter (ModuleDefinition module, MethodBody body); static TDelegate Compile<TDelegate> (Emitter emitter, [CallerMemberName] string testMethodName = null) where TDelegate : class { var name = "ImportCecil_" + testMethodName; var module = CreateTestModule<TDelegate> (name, emitter); var assembly = LoadTestModule (module); return CreateRunDelegate<TDelegate> (GetTestCase (name, assembly)); } static TDelegate CreateRunDelegate<TDelegate> (Type type) where TDelegate : class { return (TDelegate) (object) Delegate.CreateDelegate (typeof (TDelegate), type.GetMethod ("Run")); } static Type GetTestCase (string name, SR.Assembly assembly) { return assembly.GetType (name); } static SR.Assembly LoadTestModule (ModuleDefinition module) { using (var stream = new MemoryStream ()) { module.Write (stream); File.WriteAllBytes (Path.Combine (Path.Combine (Path.GetTempPath (), "cecil"), module.Name + ".dll"), stream.ToArray ()); return SR.Assembly.Load (stream.ToArray ()); } } static ModuleDefinition CreateTestModule<TDelegate> (string name, Emitter emitter) { var module = CreateModule (name); var type = new TypeDefinition ( "", name, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract, module.ImportReference (typeof (object))); module.Types.Add (type); var method = CreateMethod (type, typeof (TDelegate).GetMethod ("Invoke")); emitter (module, method.Body); return module; } static MethodDefinition CreateMethod (TypeDefinition type, SR.MethodInfo pattern) { var module = type.Module; var method = new MethodDefinition { Name = "Run", IsPublic = true, IsStatic = true, }; type.Methods.Add (method); method.MethodReturnType.ReturnType = module.ImportReference (pattern.ReturnType); foreach (var parameter_pattern in pattern.GetParameters ()) method.Parameters.Add (new ParameterDefinition (module.ImportReference (parameter_pattern.ParameterType))); return method; } static ModuleDefinition CreateModule (string name) { return ModuleDefinition.CreateModule (name, ModuleKind.Dll); } } } #endif
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using UnityEngine; using System; using System.Collections; using System.Collections.Generic; /* GoogleAnalyticsAndroidV3 handles building hits using the Android SDK. Developers should call the methods in GoogleAnalyticsV3, which will call the appropriate methods in this class if the application is built for Android. */ public class GoogleAnalyticsAndroidV3 : IDisposable { #if UNITY_ANDROID && !UNITY_EDITOR private string trackingCode; private string appVersion; private string appName; private string bundleIdentifier; private int dispatchPeriod; private int sampleFrequency; private GoogleAnalyticsV3.DebugMode logLevel; private bool anonymizeIP; private bool dryRun; private int sessionTimeout; private AndroidJavaObject tracker; private AndroidJavaObject logger; private AndroidJavaObject currentActivityObject; private AndroidJavaObject googleAnalyticsSingleton; private AndroidJavaObject gaServiceManagerSingleton; private AndroidJavaClass analyticsTrackingFields; private bool startSessionOnNextHit = false; private bool endSessionOnNextHit = false; internal void InitializeTracker() { Debug.Log("Initializing Google Analytics Android Tracker."); analyticsTrackingFields = new AndroidJavaClass( "com.google.analytics.tracking.android.Fields"); using (AndroidJavaObject googleAnalyticsClass = new AndroidJavaClass( "com.google.analytics.tracking.android.GoogleAnalytics")) using (AndroidJavaClass googleAnalyticsServiceManagerClass = new AndroidJavaClass( "com.google.analytics.tracking.android.GAServiceManager")) using (AndroidJavaClass jc = new AndroidJavaClass( "com.unity3d.player.UnityPlayer")) { currentActivityObject = jc.GetStatic<AndroidJavaObject>( "currentActivity"); googleAnalyticsSingleton = googleAnalyticsClass. CallStatic<AndroidJavaObject>("getInstance", currentActivityObject); gaServiceManagerSingleton = googleAnalyticsServiceManagerClass. CallStatic<AndroidJavaObject>("getInstance"); gaServiceManagerSingleton.Call( "setLocalDispatchPeriod", dispatchPeriod); tracker = googleAnalyticsSingleton.Call<AndroidJavaObject>( "getTracker", trackingCode); SetTrackerVal(Fields.SAMPLE_RATE, sampleFrequency.ToString()); SetTrackerVal(Fields.APP_NAME, appName); SetTrackerVal(Fields.APP_ID, bundleIdentifier); SetTrackerVal(Fields.APP_VERSION, appVersion); if (anonymizeIP) { SetTrackerVal(Fields.ANONYMIZE_IP, "1"); } googleAnalyticsSingleton.Call("setDryRun", dryRun); SetLogLevel(logLevel); } } internal void SetTrackerVal(Field fieldName, object value) { object[] args = new object[] { fieldName.ToString(), value }; tracker.Call(GoogleAnalyticsV3.SET, args); } public void SetSampleFrequency(int sampleFrequency) { this.sampleFrequency = sampleFrequency; } private void SetLogLevel(GoogleAnalyticsV3.DebugMode logLevel) { using (logger = googleAnalyticsSingleton. Call<AndroidJavaObject>("getLogger")) using (AndroidJavaClass log = new AndroidJavaClass( "com.google.analytics.tracking.android.Logger$LogLevel")) { switch(logLevel) { case GoogleAnalyticsV3.DebugMode.ERROR: using (AndroidJavaObject level = log.GetStatic<AndroidJavaObject>("ERROR")){ logger.Call("setLogLevel", level); } break; case GoogleAnalyticsV3.DebugMode.VERBOSE: using (AndroidJavaObject level = log.GetStatic<AndroidJavaObject>("VERBOSE")){ logger.Call("setLogLevel", level); } break; case GoogleAnalyticsV3.DebugMode.INFO: using (AndroidJavaObject level = log.GetStatic<AndroidJavaObject>("INFO")){ logger.Call("setLogLevel", level); } break; default: using (AndroidJavaObject level = log.GetStatic<AndroidJavaObject>("WARNING")){ logger.Call("setLogLevel", level); } break; } } } private void SetSessionOnBuilder(AndroidJavaObject hitBuilder) { if (startSessionOnNextHit) { object[] args = {Fields.SESSION_CONTROL.ToString(), "start"}; hitBuilder.Call<AndroidJavaObject>("set", args); startSessionOnNextHit = false; } else if (endSessionOnNextHit) { object[] args = {Fields.SESSION_CONTROL.ToString(), "end"}; hitBuilder.Call<AndroidJavaObject>("set", args); endSessionOnNextHit = false; } } private AndroidJavaObject BuildMap(string methodName) { using (AndroidJavaClass mapBuilder = new AndroidJavaClass( "com.google.analytics.tracking.android.MapBuilder")) using (AndroidJavaObject hitMapBuilder = mapBuilder. CallStatic<AndroidJavaObject>(methodName)) { SetSessionOnBuilder(hitMapBuilder); return hitMapBuilder.Call<AndroidJavaObject>("build"); } } private AndroidJavaObject BuildMap (string methodName, object[] args) { using (AndroidJavaClass mapBuilder = new AndroidJavaClass( "com.google.analytics.tracking.android.MapBuilder")) using (AndroidJavaObject hitMapBuilder = mapBuilder. CallStatic<AndroidJavaObject>(methodName, args)) { SetSessionOnBuilder(hitMapBuilder); return hitMapBuilder.Call<AndroidJavaObject>("build"); } } private AndroidJavaObject BuildMap(string methodName, Dictionary<AndroidJavaObject,string> parameters) { return BuildMap(methodName, null, parameters); } private AndroidJavaObject BuildMap(string methodName, object[] simpleArgs, Dictionary<AndroidJavaObject,string> parameters) { using (AndroidJavaObject hashMap = new AndroidJavaObject("java.util.HashMap")) using (AndroidJavaClass mapBuilder = new AndroidJavaClass( "com.google.analytics.tracking.android.MapBuilder")) { IntPtr putMethod = AndroidJNIHelper.GetMethodID( hashMap.GetRawClass(), "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); object[] args = new object[2]; foreach (KeyValuePair<AndroidJavaObject, string> kvp in parameters) { using (AndroidJavaObject k = kvp.Key) { using (AndroidJavaObject v = new AndroidJavaObject( "java.lang.String", kvp.Value)) { args [0] = k; args [1] = v; AndroidJNI.CallObjectMethod(hashMap.GetRawObject(), putMethod, AndroidJNIHelper.CreateJNIArgArray(args)); } } } if (simpleArgs != null) { using (AndroidJavaObject hitMapBuilder = mapBuilder.CallStatic<AndroidJavaObject>(methodName, simpleArgs)) { hitMapBuilder.Call<AndroidJavaObject>(GoogleAnalyticsV3.SET_ALL, hashMap); SetSessionOnBuilder(hitMapBuilder); return hitMapBuilder.Call<AndroidJavaObject>("build"); } } else { using (AndroidJavaObject hitMapBuilder = mapBuilder.CallStatic<AndroidJavaObject>(methodName)) { hitMapBuilder.Call<AndroidJavaObject>(GoogleAnalyticsV3.SET_ALL, hashMap); SetSessionOnBuilder(hitMapBuilder); return hitMapBuilder.Call<AndroidJavaObject>("build"); } } } } private Dictionary<AndroidJavaObject, string> AddCustomVariablesAndCampaignParameters<T>(HitBuilder<T> builder) { Dictionary<AndroidJavaObject, string> parameters = new Dictionary<AndroidJavaObject, string>(); AndroidJavaObject fieldName; foreach (KeyValuePair<int, string> entry in builder.GetCustomDimensions()) { fieldName = analyticsTrackingFields.CallStatic<AndroidJavaObject>( "customDimension", entry.Key); parameters.Add(fieldName, entry.Value); } foreach (KeyValuePair<int, string> entry in builder.GetCustomMetrics()) { fieldName = analyticsTrackingFields.CallStatic<AndroidJavaObject>( "customMetric", entry.Key); parameters.Add(fieldName, entry.Value); } if (parameters.Keys.Count > 0) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log("Added custom variables to hit."); } } if (!String.IsNullOrEmpty(builder.GetCampaignSource())) { fieldName = analyticsTrackingFields. GetStatic<AndroidJavaObject>("CAMPAIGN_SOURCE"); parameters.Add(fieldName, builder.GetCampaignSource()); fieldName = analyticsTrackingFields. GetStatic<AndroidJavaObject>("CAMPAIGN_MEDIUM"); parameters.Add(fieldName, builder.GetCampaignMedium()); fieldName = analyticsTrackingFields. GetStatic<AndroidJavaObject>("CAMPAIGN_NAME"); parameters.Add(fieldName, builder.GetCampaignName()); fieldName = analyticsTrackingFields. GetStatic<AndroidJavaObject>("CAMPAIGN_CONTENT"); parameters.Add(fieldName, builder.GetCampaignContent()); fieldName = analyticsTrackingFields. GetStatic<AndroidJavaObject>("CAMPAIGN_KEYWORD"); parameters.Add(fieldName, builder.GetCampaignKeyword()); fieldName = analyticsTrackingFields. GetStatic<AndroidJavaObject>("CAMPAIGN_ID"); parameters.Add(fieldName, builder.GetCampaignID()); fieldName = analyticsTrackingFields. GetStatic<AndroidJavaObject>("GCLID"); parameters.Add(fieldName, builder.GetGclid()); fieldName = analyticsTrackingFields. GetStatic<AndroidJavaObject>("DCLID"); parameters.Add(fieldName, builder.GetDclid()); if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log("Added campaign parameters to hit."); } } if (parameters.Keys.Count > 0) { return parameters; } return null; } internal void StartSession() { startSessionOnNextHit = true; } internal void StopSession() { endSessionOnNextHit = true; } public void SetOptOut(bool optOut) { googleAnalyticsSingleton.Call("setAppOptOut", optOut); } internal void LogScreen (AppViewHitBuilder builder) { using (AndroidJavaObject screenName = analyticsTrackingFields. GetStatic<AndroidJavaObject>("SCREEN_NAME")) { object[] args = new object[] { screenName, builder.GetScreenName() }; tracker.Call (GoogleAnalyticsV3.SET, args); } Dictionary<AndroidJavaObject, string> parameters = AddCustomVariablesAndCampaignParameters(builder); if (parameters != null) { object map = BuildMap(GoogleAnalyticsV3.APP_VIEW, parameters); tracker.Call(GoogleAnalyticsV3.SEND, map); } else { object[] args = new object[] { BuildMap(GoogleAnalyticsV3.APP_VIEW) }; tracker.Call(GoogleAnalyticsV3.SEND, args); } } internal void LogEvent(EventHitBuilder builder) { using (AndroidJavaObject valueObj = new AndroidJavaObject ( "java.lang.Long", builder.GetEventValue())) { object[] args = new object[4]; args[0] = builder.GetEventCategory(); args[1] = builder.GetEventAction(); args[2] = builder.GetEventLabel(); args[3] = valueObj; object map; Dictionary<AndroidJavaObject, string> parameters = AddCustomVariablesAndCampaignParameters(builder); if (parameters != null) { map = BuildMap(GoogleAnalyticsV3.EVENT_HIT, args, parameters); } else { map = BuildMap(GoogleAnalyticsV3.EVENT_HIT, args); } tracker.Call (GoogleAnalyticsV3.SEND, map); } } internal void LogTransaction(TransactionHitBuilder builder) { AndroidJavaObject[] valueObj = new AndroidJavaObject[3]; valueObj[0] = new AndroidJavaObject("java.lang.Double", builder.GetRevenue()); valueObj[1] = new AndroidJavaObject("java.lang.Double", builder.GetTax()); valueObj[2] = new AndroidJavaObject("java.lang.Double", builder.GetShipping()); object[] args = new object[6]; args[0] = builder.GetTransactionID(); args[1] = builder.GetAffiliation(); args[2] = valueObj[0]; args[3] = valueObj[1]; args[4] = valueObj[2]; if (builder.GetCurrencyCode() == null) { args[5] = GoogleAnalyticsV3.currencySymbol; } else { args[5] = builder.GetCurrencyCode(); } object map; Dictionary<AndroidJavaObject, string> parameters = AddCustomVariablesAndCampaignParameters(builder); if (parameters != null){ map = BuildMap(GoogleAnalyticsV3.TRANSACTION_HIT, args, parameters); } else { map = BuildMap(GoogleAnalyticsV3.TRANSACTION_HIT, args); } tracker.Call(GoogleAnalyticsV3.SEND, map); } internal void LogItem(ItemHitBuilder builder) { object[] args; if (builder.GetCurrencyCode() != null) { args = new object[7]; args[6] = builder.GetCurrencyCode(); } else { args = new object[6]; } args[0] = builder.GetTransactionID(); args[1] = builder.GetName(); args[2] = builder.GetSKU(); args[3] = builder.GetCategory(); args[4] = new AndroidJavaObject("java.lang.Double", builder.GetPrice()); args[5] = new AndroidJavaObject("java.lang.Long", builder.GetQuantity()); object map; Dictionary<AndroidJavaObject, string> parameters = AddCustomVariablesAndCampaignParameters(builder); if (parameters != null) { map = BuildMap(GoogleAnalyticsV3.ITEM_HIT, args, parameters); } else { map = BuildMap(GoogleAnalyticsV3.ITEM_HIT, args); } tracker.Call(GoogleAnalyticsV3.SEND, map); } public void LogException(ExceptionHitBuilder builder) { object[] args = new object[2]; args[0] = builder.GetExceptionDescription(); args[1] = new AndroidJavaObject("java.lang.Boolean", builder.IsFatal()); object map; Dictionary<AndroidJavaObject, string> parameters = AddCustomVariablesAndCampaignParameters(builder); if (parameters != null) { map = BuildMap(GoogleAnalyticsV3.EXCEPTION_HIT, args, parameters); } else { map = BuildMap(GoogleAnalyticsV3.EXCEPTION_HIT, args); } tracker.Call(GoogleAnalyticsV3.SEND, map); } public void DispatchHits() { gaServiceManagerSingleton.Call("dispatchLocalHits"); } public void LogSocial(SocialHitBuilder builder) { object[] args = new object[3]; args[0] = builder.GetSocialNetwork(); args[1] = builder.GetSocialAction(); args[2] = builder.GetSocialTarget(); object map; Dictionary<AndroidJavaObject, string> parameters = AddCustomVariablesAndCampaignParameters(builder); if (parameters != null) { map = BuildMap(GoogleAnalyticsV3.SOCIAL_HIT, args, parameters); } else { map = BuildMap(GoogleAnalyticsV3.SOCIAL_HIT, args); } tracker.Call(GoogleAnalyticsV3.SEND, map); } public void LogTiming(TimingHitBuilder builder) { using (AndroidJavaObject valueObj = new AndroidJavaObject("java.lang.Long", builder.GetTimingInterval())) { object[] args = new object[4]; args[0] = builder.GetTimingCategory(); args[1] = valueObj; args[2] = builder.GetTimingName(); args[3] = builder.GetTimingLabel(); object map; Dictionary<AndroidJavaObject, string> parameters = AddCustomVariablesAndCampaignParameters(builder); if (parameters != null) { map = BuildMap(GoogleAnalyticsV3.TIMING_HIT, args, parameters); } else { map = BuildMap(GoogleAnalyticsV3.TIMING_HIT, args); } tracker.Call(GoogleAnalyticsV3.SEND, map); } } public void ClearUserIDOverride() { SetTrackerVal(Fields.USER_ID, null); } public void SetTrackingCode(string trackingCode) { this.trackingCode = trackingCode; } public void SetAppName(string appName) { this.appName = appName; } public void SetBundleIdentifier(string bundleIdentifier) { this.bundleIdentifier = bundleIdentifier; } public void SetAppVersion(string appVersion) { this.appVersion = appVersion; } public void SetDispatchPeriod(int dispatchPeriod) { this.dispatchPeriod = dispatchPeriod; } public void SetLogLevelValue(GoogleAnalyticsV3.DebugMode logLevel) { this.logLevel = logLevel; } public void SetAnonymizeIP(bool anonymizeIP) { this.anonymizeIP = anonymizeIP; } public void SetDryRun(bool dryRun) { this.dryRun = dryRun; } #endif public void Dispose() { #if UNITY_ANDROID && !UNITY_EDITOR googleAnalyticsSingleton.Dispose(); tracker.Dispose(); analyticsTrackingFields.Dispose(); #endif } }
// // AudioFile.cs: Provides tagging and properties support for MPEG-1, MPEG-2, and // MPEG-2.5 audio files. // // Author: // Brian Nickel ([email protected]) // // Original Source: // mpegfile.cpp from TagLib // // Copyright (C) 2005-2007 Brian Nickel // Copyright (C) 2002, 2003 by Scott Wheeler (Original Implementation) // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // using System; namespace TagLib.Mpeg { /// <summary> /// This class extends <see cref="TagLib.NonContainer.File" /> to /// provide tagging and properties support for MPEG-1, MPEG-2, and /// MPEG-2.5 audio files. /// </summary> /// <remarks> /// A <see cref="TagLib.Id3v1.Tag" /> and <see /// cref="TagLib.Id3v2.Tag" /> will be added automatically to any /// file that doesn't contain one. This change does not effect the /// file until it is saved and can be reversed using the following /// method: /// <code>file.RemoveTags (file.TagTypes &amp; ~file.TagTypesOnDisk);</code> /// </remarks> [SupportedMimeType("taglib/mp3", "mp3")] [SupportedMimeType("audio/x-mp3")] [SupportedMimeType("application/x-id3")] [SupportedMimeType("audio/mpeg")] [SupportedMimeType("audio/x-mpeg")] [SupportedMimeType("audio/x-mpeg-3")] [SupportedMimeType("audio/mpeg3")] [SupportedMimeType("audio/mp3")] [SupportedMimeType("taglib/m2a", "m2a")] [SupportedMimeType("taglib/mp2", "mp2")] [SupportedMimeType("taglib/mp1", "mp1")] [SupportedMimeType("audio/x-mp2")] [SupportedMimeType("audio/x-mp1")] public class AudioFile : TagLib.NonContainer.File { #region Private Fields /// <summary> /// Contains the first audio header. /// </summary> private AudioHeader first_header; #endregion #region Constructors /// <summary> /// Constructs and initializes a new instance of <see /// cref="AudioFile" /> for a specified path in the local /// file system and specified read style. /// </summary> /// <param name="path"> /// A <see cref="string" /> object containing the path of the /// file to use in the new instance. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path" /> is <see langword="null" />. /// </exception> public AudioFile (string path, ReadStyle propertiesStyle) : base (path, propertiesStyle) { } /// <summary> /// Constructs and initializes a new instance of <see /// cref="AudioFile" /> for a specified path in the local /// file system with an average read style. /// </summary> /// <param name="path"> /// A <see cref="string" /> object containing the path of the /// file to use in the new instance. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path" /> is <see langword="null" />. /// </exception> public AudioFile (string path) : base (path) { } /// <summary> /// Constructs and initializes a new instance of <see /// cref="AudioFile" /> for a specified file abstraction and /// specified read style. /// </summary> /// <param name="abstraction"> /// A <see cref="TagLib.File.IFileAbstraction" /> object to use when /// reading from and writing to the file. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="abstraction" /> is <see langword="null" /// />. /// </exception> public AudioFile (File.IFileAbstraction abstraction, ReadStyle propertiesStyle) : base (abstraction, propertiesStyle) { } /// <summary> /// Constructs and initializes a new instance of <see /// cref="AudioFile" /> for a specified file abstraction with /// an average read style. /// </summary> /// <param name="abstraction"> /// A <see cref="TagLib.File.IFileAbstraction" /> object to use when /// reading from and writing to the file. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="abstraction" /> is <see langword="null" /// />. /// </exception> public AudioFile (File.IFileAbstraction abstraction) : base (abstraction) { } #endregion #region Public Methods /// <summary> /// Gets a tag of a specified type from the current instance, /// optionally creating a new tag if possible. /// </summary> /// <param name="type"> /// A <see cref="TagLib.TagTypes" /> value indicating the /// type of tag to read. /// </param> /// <param name="create"> /// A <see cref="bool" /> value specifying whether or not to /// try and create the tag if one is not found. /// </param> /// <returns> /// A <see cref="Tag" /> object containing the tag that was /// found in or added to the current instance. If no /// matching tag was found and none was created, <see /// langword="null" /> is returned. /// </returns> /// <remarks> /// If a <see cref="TagLib.Id3v2.Tag" /> is added to the /// current instance, it will be placed at the start of the /// file. On the other hand, <see cref="TagLib.Id3v1.Tag" /> /// <see cref="TagLib.Ape.Tag" /> will be added to the end of /// the file. All other tag types will be ignored. /// </remarks> public override TagLib.Tag GetTag (TagTypes type, bool create) { Tag t = (Tag as TagLib.NonContainer.Tag).GetTag (type); if (t != null || !create) return t; switch (type) { case TagTypes.Id3v1: return EndTag.AddTag (type, Tag); case TagTypes.Id3v2: return StartTag.AddTag (type, Tag); case TagTypes.Ape: return EndTag.AddTag (type, Tag); default: return null; } } #endregion #region Protected Methods /// <summary> /// Reads format specific information at the start of the /// file. /// </summary> /// <param name="start"> /// A <see cref="long" /> value containing the seek position /// at which the tags end and the media data begins. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> /// <remarks> /// This method only searches for an audio header in the /// first 16384 bytes of code to avoid searching forever in /// corrupt files. /// </remarks> protected override void ReadStart (long start, ReadStyle propertiesStyle) { // Only check the first 16 bytes so we're not stuck // reading a bad file forever. if (propertiesStyle != ReadStyle.None && !AudioHeader.Find (out first_header, this, start, 0x4000)) throw new CorruptFileException ( "MPEG audio header not found."); } /// <summary> /// Reads format specific information at the end of the /// file. /// </summary> /// <param name="end"> /// A <see cref="long" /> value containing the seek position /// at which the media data ends and the tags begin. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> protected override void ReadEnd (long end, ReadStyle propertiesStyle) { // Make sure we have ID3v1 and ID3v2 tags. GetTag (TagTypes.Id3v1, true); GetTag (TagTypes.Id3v2, true); } /// <summary> /// Reads the audio properties from the file represented by /// the current instance. /// </summary> /// <param name="start"> /// A <see cref="long" /> value containing the seek position /// at which the tags end and the media data begins. /// </param> /// <param name="end"> /// A <see cref="long" /> value containing the seek position /// at which the media data ends and the tags begin. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> /// <returns> /// A <see cref="TagLib.Properties" /> object describing the /// media properties of the file represented by the current /// instance. /// </returns> protected override Properties ReadProperties (long start, long end, ReadStyle propertiesStyle) { first_header.SetStreamLength (end - start); return new Properties (TimeSpan.Zero, first_header); } #endregion } }
// 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.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Reflection.Emit.Tests { public class TypeBuilderCreateType3 { private const int MinAsmName = 1; private const int MaxAsmName = 260; private const int MinModName = 1; private const int MaxModName = 260; private const int MinTypName = 1; private const int MaxTypName = 1024; private const int NumLoops = 5; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); private TypeAttributes[] _typesPos = new TypeAttributes[17] { TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.AnsiClass | TypeAttributes.NestedPublic, TypeAttributes.AutoClass | TypeAttributes.NestedPublic, TypeAttributes.AutoLayout | TypeAttributes.NestedPublic, TypeAttributes.BeforeFieldInit | TypeAttributes.NestedPublic, TypeAttributes.Class | TypeAttributes.NestedPublic, TypeAttributes.ClassSemanticsMask | TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.ExplicitLayout | TypeAttributes.NestedPublic, TypeAttributes.Import | TypeAttributes.NestedPublic, TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.Sealed | TypeAttributes.NestedPublic, TypeAttributes.SequentialLayout | TypeAttributes.NestedPublic, TypeAttributes.Serializable | TypeAttributes.NestedPublic, TypeAttributes.SpecialName | TypeAttributes.NestedPublic, TypeAttributes.StringFormatMask | TypeAttributes.NestedPublic, TypeAttributes.UnicodeClass | TypeAttributes.NestedPublic, TypeAttributes.VisibilityMask, }; [Fact] public void TestDefineNestedType() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; TypeBuilder nestedType = null; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls typeBuilder = modBuilder.DefineType(typeName); for (int i = 0; i < NumLoops; i++) { nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls // create nested type if (null != nestedType && 0 == (_generator.GetInt32() % 2)) { nestedType.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, typeBuilder.GetType()); } else { nestedType = typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, typeBuilder.GetType()); } } newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } [Fact] public void TestWithEmbeddedNullsInName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; for (int i = 0; i < NumLoops; i++) { modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName / 4) + '\0' + _generator.GetString(true, MinTypName, MaxTypName / 4) + '\0' + _generator.GetString(true, MinTypName, MaxTypName / 4); typeBuilder = modBuilder.DefineType(typeName); // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, typeBuilder.GetType()); newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } } [Fact] public void TestWithTypeAttributesSet() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; TypeBuilder nestedType = null; Type newType; string typeName = ""; string nestedTypeName = ""; TypeAttributes typeAttrib = (TypeAttributes)0; int i = 0; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls typeBuilder = modBuilder.DefineType(typeName, typeAttrib); for (i = 0; i < _typesPos.Length; i++) { typeAttrib = _typesPos[i]; nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls // create nested type if (null != nestedType && 0 == (_generator.GetInt32() % 2)) { nestedType.DefineNestedType(nestedTypeName, _typesPos[i], typeBuilder.GetType()); } else { nestedType = typeBuilder.DefineNestedType(nestedTypeName, _typesPos[i], typeBuilder.GetType()); } } newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } [Fact] public void TestWithNullParentType() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; TypeBuilder nestedType = null; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls typeBuilder = modBuilder.DefineType(typeName); nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls // create nested type nestedType = typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, null); newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } [Fact] public void TestThrowsExceptionForNullname() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = null; typeBuilder = modBuilder.DefineType(typeName); Assert.Throws<ArgumentNullException>(() => { // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class, typeBuilder.GetType()); newType = typeBuilder.CreateTypeInfo().AsType(); }); } [Fact] public void TestThrowsExcetpionForEmptyName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = string.Empty; typeBuilder = modBuilder.DefineType(typeName); Assert.Throws<ArgumentException>(() => { // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class, typeBuilder.GetType()); newType = typeBuilder.CreateTypeInfo().AsType(); }); } public ModuleBuilder CreateModule(string assemblyName, string modName) { AssemblyName asmName; AssemblyBuilder asmBuilder; ModuleBuilder modBuilder; // create the dynamic module asmName = new AssemblyName(assemblyName); asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); modBuilder = TestLibrary.Utilities.GetModuleBuilder(asmBuilder, "Module1"); return modBuilder; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** Purpose: This class will encapsulate an unsigned long and ** provide an Object representation of it. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { // Wrapper for unsigned 64 bit integers. [CLSCompliant(false)] [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct UInt64 : IComparable, IFormattable, IComparable<UInt64>, IEquatable<UInt64>, IConvertible { private ulong _value; public const ulong MaxValue = (ulong)0xffffffffffffffffL; public const ulong MinValue = 0x0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt64, this method throws an ArgumentException. // int IComparable.CompareTo(Object value) { if (value == null) { return 1; } if (value is UInt64) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. ulong i = (ulong)value; if (_value < i) return -1; if (_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeUInt64); } public int CompareTo(UInt64 value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (_value < value) return -1; if (_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is UInt64)) { return false; } return _value == ((UInt64)obj)._value; } [NonVersionable] public bool Equals(UInt64 obj) { return _value == obj; } // The value of the lower 32 bits XORed with the uppper 32 bits. public override int GetHashCode() { return ((int)_value) ^ (int)(_value >> 32); } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt64(_value, null, null); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt64(_value, null, provider); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt64(_value, format, null); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt64(_value, format, provider); } [CLSCompliant(false)] public static ulong Parse(String s) { return FormatProvider.ParseUInt64(s, NumberStyles.Integer, null); } [CLSCompliant(false)] public static ulong Parse(String s, NumberStyles style) { UInt32.ValidateParseStyleInteger(style); return FormatProvider.ParseUInt64(s, style, null); } [CLSCompliant(false)] public static ulong Parse(string s, IFormatProvider provider) { return FormatProvider.ParseUInt64(s, NumberStyles.Integer, provider); } [CLSCompliant(false)] public static ulong Parse(String s, NumberStyles style, IFormatProvider provider) { UInt32.ValidateParseStyleInteger(style); return FormatProvider.ParseUInt64(s, style, provider); } [CLSCompliant(false)] public static Boolean TryParse(String s, out UInt64 result) { return FormatProvider.TryParseUInt64(s, NumberStyles.Integer, null, out result); } [CLSCompliant(false)] public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt64 result) { UInt32.ValidateParseStyleInteger(style); return FormatProvider.TryParseUInt64(s, style, provider, out result); } // // IConvertible implementation // TypeCode IConvertible.GetTypeCode() { return TypeCode.UInt64; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(_value); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return _value; } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "UInt64", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System.Collections; using System.Diagnostics; internal sealed class SchemaNames { private readonly XmlNameTable _nameTable; public string NsDataType; public string NsDataTypeAlias; public string NsDataTypeOld; public string NsXml; public string NsXmlNs; public string NsXdr; public string NsXdrAlias; public string NsXs; public string NsXsi; public string XsiType; public string XsiNil; public string XsiSchemaLocation; public string XsiNoNamespaceSchemaLocation; public string XsdSchema; public string XdrSchema; public XmlQualifiedName QnPCData; public XmlQualifiedName QnXml; public XmlQualifiedName QnXmlNs; public XmlQualifiedName QnDtDt; public XmlQualifiedName QnXmlLang; public XmlQualifiedName QnName; public XmlQualifiedName QnType; public XmlQualifiedName QnMaxOccurs; public XmlQualifiedName QnMinOccurs; public XmlQualifiedName QnInfinite; public XmlQualifiedName QnModel; public XmlQualifiedName QnOpen; public XmlQualifiedName QnClosed; public XmlQualifiedName QnContent; public XmlQualifiedName QnMixed; public XmlQualifiedName QnEmpty; public XmlQualifiedName QnEltOnly; public XmlQualifiedName QnTextOnly; public XmlQualifiedName QnOrder; public XmlQualifiedName QnSeq; public XmlQualifiedName QnOne; public XmlQualifiedName QnMany; public XmlQualifiedName QnRequired; public XmlQualifiedName QnYes; public XmlQualifiedName QnNo; public XmlQualifiedName QnString; public XmlQualifiedName QnID; public XmlQualifiedName QnIDRef; public XmlQualifiedName QnIDRefs; public XmlQualifiedName QnEntity; public XmlQualifiedName QnEntities; public XmlQualifiedName QnNmToken; public XmlQualifiedName QnNmTokens; public XmlQualifiedName QnEnumeration; public XmlQualifiedName QnDefault; public XmlQualifiedName QnXdrSchema; public XmlQualifiedName QnXdrElementType; public XmlQualifiedName QnXdrElement; public XmlQualifiedName QnXdrGroup; public XmlQualifiedName QnXdrAttributeType; public XmlQualifiedName QnXdrAttribute; public XmlQualifiedName QnXdrDataType; public XmlQualifiedName QnXdrDescription; public XmlQualifiedName QnXdrExtends; public XmlQualifiedName QnXdrAliasSchema; public XmlQualifiedName QnDtType; public XmlQualifiedName QnDtValues; public XmlQualifiedName QnDtMaxLength; public XmlQualifiedName QnDtMinLength; public XmlQualifiedName QnDtMax; public XmlQualifiedName QnDtMin; public XmlQualifiedName QnDtMinExclusive; public XmlQualifiedName QnDtMaxExclusive; // For XSD Schema public XmlQualifiedName QnTargetNamespace; public XmlQualifiedName QnVersion; public XmlQualifiedName QnFinalDefault; public XmlQualifiedName QnBlockDefault; public XmlQualifiedName QnFixed; public XmlQualifiedName QnAbstract; public XmlQualifiedName QnBlock; public XmlQualifiedName QnSubstitutionGroup; public XmlQualifiedName QnFinal; public XmlQualifiedName QnNillable; public XmlQualifiedName QnRef; public XmlQualifiedName QnBase; public XmlQualifiedName QnDerivedBy; public XmlQualifiedName QnNamespace; public XmlQualifiedName QnProcessContents; public XmlQualifiedName QnRefer; public XmlQualifiedName QnPublic; public XmlQualifiedName QnSystem; public XmlQualifiedName QnSchemaLocation; public XmlQualifiedName QnValue; public XmlQualifiedName QnUse; public XmlQualifiedName QnForm; public XmlQualifiedName QnElementFormDefault; public XmlQualifiedName QnAttributeFormDefault; public XmlQualifiedName QnItemType; public XmlQualifiedName QnMemberTypes; public XmlQualifiedName QnXPath; public XmlQualifiedName QnXsdSchema; public XmlQualifiedName QnXsdAnnotation; public XmlQualifiedName QnXsdInclude; public XmlQualifiedName QnXsdImport; public XmlQualifiedName QnXsdElement; public XmlQualifiedName QnXsdAttribute; public XmlQualifiedName QnXsdAttributeGroup; public XmlQualifiedName QnXsdAnyAttribute; public XmlQualifiedName QnXsdGroup; public XmlQualifiedName QnXsdAll; public XmlQualifiedName QnXsdChoice; public XmlQualifiedName QnXsdSequence; public XmlQualifiedName QnXsdAny; public XmlQualifiedName QnXsdNotation; public XmlQualifiedName QnXsdSimpleType; public XmlQualifiedName QnXsdComplexType; public XmlQualifiedName QnXsdUnique; public XmlQualifiedName QnXsdKey; public XmlQualifiedName QnXsdKeyRef; public XmlQualifiedName QnXsdSelector; public XmlQualifiedName QnXsdField; public XmlQualifiedName QnXsdMinExclusive; public XmlQualifiedName QnXsdMinInclusive; public XmlQualifiedName QnXsdMaxInclusive; public XmlQualifiedName QnXsdMaxExclusive; public XmlQualifiedName QnXsdTotalDigits; public XmlQualifiedName QnXsdFractionDigits; public XmlQualifiedName QnXsdLength; public XmlQualifiedName QnXsdMinLength; public XmlQualifiedName QnXsdMaxLength; public XmlQualifiedName QnXsdEnumeration; public XmlQualifiedName QnXsdPattern; public XmlQualifiedName QnXsdDocumentation; public XmlQualifiedName QnXsdAppinfo; public XmlQualifiedName QnSource; public XmlQualifiedName QnXsdComplexContent; public XmlQualifiedName QnXsdSimpleContent; public XmlQualifiedName QnXsdRestriction; public XmlQualifiedName QnXsdExtension; public XmlQualifiedName QnXsdUnion; public XmlQualifiedName QnXsdList; public XmlQualifiedName QnXsdWhiteSpace; public XmlQualifiedName QnXsdRedefine; public XmlQualifiedName QnXsdAnyType; internal XmlQualifiedName[] TokenToQName = new XmlQualifiedName[(int)Token.XmlLang + 1]; public SchemaNames(XmlNameTable nameTable) { _nameTable = nameTable; NsDataType = nameTable.Add(XmlReservedNs.NsDataType); NsDataTypeAlias = nameTable.Add(XmlReservedNs.NsDataTypeAlias); NsDataTypeOld = nameTable.Add(XmlReservedNs.NsDataTypeOld); NsXml = nameTable.Add(XmlReservedNs.NsXml); NsXmlNs = nameTable.Add(XmlReservedNs.NsXmlNs); NsXdr = nameTable.Add(XmlReservedNs.NsXdr); NsXdrAlias = nameTable.Add(XmlReservedNs.NsXdrAlias); NsXs = nameTable.Add(XmlReservedNs.NsXs); NsXsi = nameTable.Add(XmlReservedNs.NsXsi); XsiType = nameTable.Add("type"); XsiNil = nameTable.Add("nil"); XsiSchemaLocation = nameTable.Add("schemaLocation"); XsiNoNamespaceSchemaLocation = nameTable.Add("noNamespaceSchemaLocation"); XsdSchema = nameTable.Add("schema"); XdrSchema = nameTable.Add("Schema"); QnPCData = new XmlQualifiedName(nameTable.Add("#PCDATA")); QnXml = new XmlQualifiedName(nameTable.Add("xml")); QnXmlNs = new XmlQualifiedName(nameTable.Add("xmlns"), NsXmlNs); QnDtDt = new XmlQualifiedName(nameTable.Add("dt"), NsDataType); QnXmlLang = new XmlQualifiedName(nameTable.Add("lang"), NsXml); // Empty namespace QnName = new XmlQualifiedName(nameTable.Add("name")); QnType = new XmlQualifiedName(nameTable.Add("type")); QnMaxOccurs = new XmlQualifiedName(nameTable.Add("maxOccurs")); QnMinOccurs = new XmlQualifiedName(nameTable.Add("minOccurs")); QnInfinite = new XmlQualifiedName(nameTable.Add("*")); QnModel = new XmlQualifiedName(nameTable.Add("model")); QnOpen = new XmlQualifiedName(nameTable.Add("open")); QnClosed = new XmlQualifiedName(nameTable.Add("closed")); QnContent = new XmlQualifiedName(nameTable.Add("content")); QnMixed = new XmlQualifiedName(nameTable.Add("mixed")); QnEmpty = new XmlQualifiedName(nameTable.Add("empty")); QnEltOnly = new XmlQualifiedName(nameTable.Add("eltOnly")); QnTextOnly = new XmlQualifiedName(nameTable.Add("textOnly")); QnOrder = new XmlQualifiedName(nameTable.Add("order")); QnSeq = new XmlQualifiedName(nameTable.Add("seq")); QnOne = new XmlQualifiedName(nameTable.Add("one")); QnMany = new XmlQualifiedName(nameTable.Add("many")); QnRequired = new XmlQualifiedName(nameTable.Add("required")); QnYes = new XmlQualifiedName(nameTable.Add("yes")); QnNo = new XmlQualifiedName(nameTable.Add("no")); QnString = new XmlQualifiedName(nameTable.Add("string")); QnID = new XmlQualifiedName(nameTable.Add("id")); QnIDRef = new XmlQualifiedName(nameTable.Add("idref")); QnIDRefs = new XmlQualifiedName(nameTable.Add("idrefs")); QnEntity = new XmlQualifiedName(nameTable.Add("entity")); QnEntities = new XmlQualifiedName(nameTable.Add("entities")); QnNmToken = new XmlQualifiedName(nameTable.Add("nmtoken")); QnNmTokens = new XmlQualifiedName(nameTable.Add("nmtokens")); QnEnumeration = new XmlQualifiedName(nameTable.Add("enumeration")); QnDefault = new XmlQualifiedName(nameTable.Add("default")); //For XSD Schema QnTargetNamespace = new XmlQualifiedName(nameTable.Add("targetNamespace")); QnVersion = new XmlQualifiedName(nameTable.Add("version")); QnFinalDefault = new XmlQualifiedName(nameTable.Add("finalDefault")); QnBlockDefault = new XmlQualifiedName(nameTable.Add("blockDefault")); QnFixed = new XmlQualifiedName(nameTable.Add("fixed")); QnAbstract = new XmlQualifiedName(nameTable.Add("abstract")); QnBlock = new XmlQualifiedName(nameTable.Add("block")); QnSubstitutionGroup = new XmlQualifiedName(nameTable.Add("substitutionGroup")); QnFinal = new XmlQualifiedName(nameTable.Add("final")); QnNillable = new XmlQualifiedName(nameTable.Add("nillable")); QnRef = new XmlQualifiedName(nameTable.Add("ref")); QnBase = new XmlQualifiedName(nameTable.Add("base")); QnDerivedBy = new XmlQualifiedName(nameTable.Add("derivedBy")); QnNamespace = new XmlQualifiedName(nameTable.Add("namespace")); QnProcessContents = new XmlQualifiedName(nameTable.Add("processContents")); QnRefer = new XmlQualifiedName(nameTable.Add("refer")); QnPublic = new XmlQualifiedName(nameTable.Add("public")); QnSystem = new XmlQualifiedName(nameTable.Add("system")); QnSchemaLocation = new XmlQualifiedName(nameTable.Add("schemaLocation")); QnValue = new XmlQualifiedName(nameTable.Add("value")); QnUse = new XmlQualifiedName(nameTable.Add("use")); QnForm = new XmlQualifiedName(nameTable.Add("form")); QnAttributeFormDefault = new XmlQualifiedName(nameTable.Add("attributeFormDefault")); QnElementFormDefault = new XmlQualifiedName(nameTable.Add("elementFormDefault")); QnSource = new XmlQualifiedName(nameTable.Add("source")); QnMemberTypes = new XmlQualifiedName(nameTable.Add("memberTypes")); QnItemType = new XmlQualifiedName(nameTable.Add("itemType")); QnXPath = new XmlQualifiedName(nameTable.Add("xpath")); // XDR namespace QnXdrSchema = new XmlQualifiedName(XdrSchema, NsXdr); QnXdrElementType = new XmlQualifiedName(nameTable.Add("ElementType"), NsXdr); QnXdrElement = new XmlQualifiedName(nameTable.Add("element"), NsXdr); QnXdrGroup = new XmlQualifiedName(nameTable.Add("group"), NsXdr); QnXdrAttributeType = new XmlQualifiedName(nameTable.Add("AttributeType"), NsXdr); QnXdrAttribute = new XmlQualifiedName(nameTable.Add("attribute"), NsXdr); QnXdrDataType = new XmlQualifiedName(nameTable.Add("datatype"), NsXdr); QnXdrDescription = new XmlQualifiedName(nameTable.Add("description"), NsXdr); QnXdrExtends = new XmlQualifiedName(nameTable.Add("extends"), NsXdr); // XDR alias namespace QnXdrAliasSchema = new XmlQualifiedName(nameTable.Add("Schema"), NsDataTypeAlias); // DataType namespace QnDtType = new XmlQualifiedName(nameTable.Add("type"), NsDataType); QnDtValues = new XmlQualifiedName(nameTable.Add("values"), NsDataType); QnDtMaxLength = new XmlQualifiedName(nameTable.Add("maxLength"), NsDataType); QnDtMinLength = new XmlQualifiedName(nameTable.Add("minLength"), NsDataType); QnDtMax = new XmlQualifiedName(nameTable.Add("max"), NsDataType); QnDtMin = new XmlQualifiedName(nameTable.Add("min"), NsDataType); QnDtMinExclusive = new XmlQualifiedName(nameTable.Add("minExclusive"), NsDataType); QnDtMaxExclusive = new XmlQualifiedName(nameTable.Add("maxExclusive"), NsDataType); // XSD namespace QnXsdSchema = new XmlQualifiedName(XsdSchema, NsXs); QnXsdAnnotation = new XmlQualifiedName(nameTable.Add("annotation"), NsXs); QnXsdInclude = new XmlQualifiedName(nameTable.Add("include"), NsXs); QnXsdImport = new XmlQualifiedName(nameTable.Add("import"), NsXs); QnXsdElement = new XmlQualifiedName(nameTable.Add("element"), NsXs); QnXsdAttribute = new XmlQualifiedName(nameTable.Add("attribute"), NsXs); QnXsdAttributeGroup = new XmlQualifiedName(nameTable.Add("attributeGroup"), NsXs); QnXsdAnyAttribute = new XmlQualifiedName(nameTable.Add("anyAttribute"), NsXs); QnXsdGroup = new XmlQualifiedName(nameTable.Add("group"), NsXs); QnXsdAll = new XmlQualifiedName(nameTable.Add("all"), NsXs); QnXsdChoice = new XmlQualifiedName(nameTable.Add("choice"), NsXs); QnXsdSequence = new XmlQualifiedName(nameTable.Add("sequence"), NsXs); QnXsdAny = new XmlQualifiedName(nameTable.Add("any"), NsXs); QnXsdNotation = new XmlQualifiedName(nameTable.Add("notation"), NsXs); QnXsdSimpleType = new XmlQualifiedName(nameTable.Add("simpleType"), NsXs); QnXsdComplexType = new XmlQualifiedName(nameTable.Add("complexType"), NsXs); QnXsdUnique = new XmlQualifiedName(nameTable.Add("unique"), NsXs); QnXsdKey = new XmlQualifiedName(nameTable.Add("key"), NsXs); QnXsdKeyRef = new XmlQualifiedName(nameTable.Add("keyref"), NsXs); QnXsdSelector = new XmlQualifiedName(nameTable.Add("selector"), NsXs); QnXsdField = new XmlQualifiedName(nameTable.Add("field"), NsXs); QnXsdMinExclusive = new XmlQualifiedName(nameTable.Add("minExclusive"), NsXs); QnXsdMinInclusive = new XmlQualifiedName(nameTable.Add("minInclusive"), NsXs); QnXsdMaxInclusive = new XmlQualifiedName(nameTable.Add("maxInclusive"), NsXs); QnXsdMaxExclusive = new XmlQualifiedName(nameTable.Add("maxExclusive"), NsXs); QnXsdTotalDigits = new XmlQualifiedName(nameTable.Add("totalDigits"), NsXs); QnXsdFractionDigits = new XmlQualifiedName(nameTable.Add("fractionDigits"), NsXs); QnXsdLength = new XmlQualifiedName(nameTable.Add("length"), NsXs); QnXsdMinLength = new XmlQualifiedName(nameTable.Add("minLength"), NsXs); QnXsdMaxLength = new XmlQualifiedName(nameTable.Add("maxLength"), NsXs); QnXsdEnumeration = new XmlQualifiedName(nameTable.Add("enumeration"), NsXs); QnXsdPattern = new XmlQualifiedName(nameTable.Add("pattern"), NsXs); QnXsdDocumentation = new XmlQualifiedName(nameTable.Add("documentation"), NsXs); QnXsdAppinfo = new XmlQualifiedName(nameTable.Add("appinfo"), NsXs); QnXsdComplexContent = new XmlQualifiedName(nameTable.Add("complexContent"), NsXs); QnXsdSimpleContent = new XmlQualifiedName(nameTable.Add("simpleContent"), NsXs); QnXsdRestriction = new XmlQualifiedName(nameTable.Add("restriction"), NsXs); QnXsdExtension = new XmlQualifiedName(nameTable.Add("extension"), NsXs); QnXsdUnion = new XmlQualifiedName(nameTable.Add("union"), NsXs); QnXsdList = new XmlQualifiedName(nameTable.Add("list"), NsXs); QnXsdWhiteSpace = new XmlQualifiedName(nameTable.Add("whiteSpace"), NsXs); QnXsdRedefine = new XmlQualifiedName(nameTable.Add("redefine"), NsXs); QnXsdAnyType = new XmlQualifiedName(nameTable.Add("anyType"), NsXs); //Create token to Qname table CreateTokenToQNameTable(); } public void CreateTokenToQNameTable() { TokenToQName[(int)Token.SchemaName] = QnName; TokenToQName[(int)Token.SchemaType] = QnType; TokenToQName[(int)Token.SchemaMaxOccurs] = QnMaxOccurs; TokenToQName[(int)Token.SchemaMinOccurs] = QnMinOccurs; TokenToQName[(int)Token.SchemaInfinite] = QnInfinite; TokenToQName[(int)Token.SchemaModel] = QnModel; TokenToQName[(int)Token.SchemaOpen] = QnOpen; TokenToQName[(int)Token.SchemaClosed] = QnClosed; TokenToQName[(int)Token.SchemaContent] = QnContent; TokenToQName[(int)Token.SchemaMixed] = QnMixed; TokenToQName[(int)Token.SchemaEmpty] = QnEmpty; TokenToQName[(int)Token.SchemaElementOnly] = QnEltOnly; TokenToQName[(int)Token.SchemaTextOnly] = QnTextOnly; TokenToQName[(int)Token.SchemaOrder] = QnOrder; TokenToQName[(int)Token.SchemaSeq] = QnSeq; TokenToQName[(int)Token.SchemaOne] = QnOne; TokenToQName[(int)Token.SchemaMany] = QnMany; TokenToQName[(int)Token.SchemaRequired] = QnRequired; TokenToQName[(int)Token.SchemaYes] = QnYes; TokenToQName[(int)Token.SchemaNo] = QnNo; TokenToQName[(int)Token.SchemaString] = QnString; TokenToQName[(int)Token.SchemaId] = QnID; TokenToQName[(int)Token.SchemaIdref] = QnIDRef; TokenToQName[(int)Token.SchemaIdrefs] = QnIDRefs; TokenToQName[(int)Token.SchemaEntity] = QnEntity; TokenToQName[(int)Token.SchemaEntities] = QnEntities; TokenToQName[(int)Token.SchemaNmtoken] = QnNmToken; TokenToQName[(int)Token.SchemaNmtokens] = QnNmTokens; TokenToQName[(int)Token.SchemaEnumeration] = QnEnumeration; TokenToQName[(int)Token.SchemaDefault] = QnDefault; TokenToQName[(int)Token.XdrRoot] = QnXdrSchema; TokenToQName[(int)Token.XdrElementType] = QnXdrElementType; TokenToQName[(int)Token.XdrElement] = QnXdrElement; TokenToQName[(int)Token.XdrGroup] = QnXdrGroup; TokenToQName[(int)Token.XdrAttributeType] = QnXdrAttributeType; TokenToQName[(int)Token.XdrAttribute] = QnXdrAttribute; TokenToQName[(int)Token.XdrDatatype] = QnXdrDataType; TokenToQName[(int)Token.XdrDescription] = QnXdrDescription; TokenToQName[(int)Token.XdrExtends] = QnXdrExtends; TokenToQName[(int)Token.SchemaXdrRootAlias] = QnXdrAliasSchema; TokenToQName[(int)Token.SchemaDtType] = QnDtType; TokenToQName[(int)Token.SchemaDtValues] = QnDtValues; TokenToQName[(int)Token.SchemaDtMaxLength] = QnDtMaxLength; TokenToQName[(int)Token.SchemaDtMinLength] = QnDtMinLength; TokenToQName[(int)Token.SchemaDtMax] = QnDtMax; TokenToQName[(int)Token.SchemaDtMin] = QnDtMin; TokenToQName[(int)Token.SchemaDtMinExclusive] = QnDtMinExclusive; TokenToQName[(int)Token.SchemaDtMaxExclusive] = QnDtMaxExclusive; TokenToQName[(int)Token.SchemaTargetNamespace] = QnTargetNamespace; TokenToQName[(int)Token.SchemaVersion] = QnVersion; TokenToQName[(int)Token.SchemaFinalDefault] = QnFinalDefault; TokenToQName[(int)Token.SchemaBlockDefault] = QnBlockDefault; TokenToQName[(int)Token.SchemaFixed] = QnFixed; TokenToQName[(int)Token.SchemaAbstract] = QnAbstract; TokenToQName[(int)Token.SchemaBlock] = QnBlock; TokenToQName[(int)Token.SchemaSubstitutionGroup] = QnSubstitutionGroup; TokenToQName[(int)Token.SchemaFinal] = QnFinal; TokenToQName[(int)Token.SchemaNillable] = QnNillable; TokenToQName[(int)Token.SchemaRef] = QnRef; TokenToQName[(int)Token.SchemaBase] = QnBase; TokenToQName[(int)Token.SchemaDerivedBy] = QnDerivedBy; TokenToQName[(int)Token.SchemaNamespace] = QnNamespace; TokenToQName[(int)Token.SchemaProcessContents] = QnProcessContents; TokenToQName[(int)Token.SchemaRefer] = QnRefer; TokenToQName[(int)Token.SchemaPublic] = QnPublic; TokenToQName[(int)Token.SchemaSystem] = QnSystem; TokenToQName[(int)Token.SchemaSchemaLocation] = QnSchemaLocation; TokenToQName[(int)Token.SchemaValue] = QnValue; TokenToQName[(int)Token.SchemaItemType] = QnItemType; TokenToQName[(int)Token.SchemaMemberTypes] = QnMemberTypes; TokenToQName[(int)Token.SchemaXPath] = QnXPath; TokenToQName[(int)Token.XsdSchema] = QnXsdSchema; TokenToQName[(int)Token.XsdAnnotation] = QnXsdAnnotation; TokenToQName[(int)Token.XsdInclude] = QnXsdInclude; TokenToQName[(int)Token.XsdImport] = QnXsdImport; TokenToQName[(int)Token.XsdElement] = QnXsdElement; TokenToQName[(int)Token.XsdAttribute] = QnXsdAttribute; TokenToQName[(int)Token.xsdAttributeGroup] = QnXsdAttributeGroup; TokenToQName[(int)Token.XsdAnyAttribute] = QnXsdAnyAttribute; TokenToQName[(int)Token.XsdGroup] = QnXsdGroup; TokenToQName[(int)Token.XsdAll] = QnXsdAll; TokenToQName[(int)Token.XsdChoice] = QnXsdChoice; TokenToQName[(int)Token.XsdSequence] = QnXsdSequence; TokenToQName[(int)Token.XsdAny] = QnXsdAny; TokenToQName[(int)Token.XsdNotation] = QnXsdNotation; TokenToQName[(int)Token.XsdSimpleType] = QnXsdSimpleType; TokenToQName[(int)Token.XsdComplexType] = QnXsdComplexType; TokenToQName[(int)Token.XsdUnique] = QnXsdUnique; TokenToQName[(int)Token.XsdKey] = QnXsdKey; TokenToQName[(int)Token.XsdKeyref] = QnXsdKeyRef; TokenToQName[(int)Token.XsdSelector] = QnXsdSelector; TokenToQName[(int)Token.XsdField] = QnXsdField; TokenToQName[(int)Token.XsdMinExclusive] = QnXsdMinExclusive; TokenToQName[(int)Token.XsdMinInclusive] = QnXsdMinInclusive; TokenToQName[(int)Token.XsdMaxExclusive] = QnXsdMaxExclusive; TokenToQName[(int)Token.XsdMaxInclusive] = QnXsdMaxInclusive; TokenToQName[(int)Token.XsdTotalDigits] = QnXsdTotalDigits; TokenToQName[(int)Token.XsdFractionDigits] = QnXsdFractionDigits; TokenToQName[(int)Token.XsdLength] = QnXsdLength; TokenToQName[(int)Token.XsdMinLength] = QnXsdMinLength; TokenToQName[(int)Token.XsdMaxLength] = QnXsdMaxLength; TokenToQName[(int)Token.XsdEnumeration] = QnXsdEnumeration; TokenToQName[(int)Token.XsdPattern] = QnXsdPattern; TokenToQName[(int)Token.XsdWhitespace] = QnXsdWhiteSpace; TokenToQName[(int)Token.XsdDocumentation] = QnXsdDocumentation; TokenToQName[(int)Token.XsdAppInfo] = QnXsdAppinfo; TokenToQName[(int)Token.XsdComplexContent] = QnXsdComplexContent; TokenToQName[(int)Token.XsdComplexContentRestriction] = QnXsdRestriction; TokenToQName[(int)Token.XsdSimpleContentRestriction] = QnXsdRestriction; TokenToQName[(int)Token.XsdSimpleTypeRestriction] = QnXsdRestriction; TokenToQName[(int)Token.XsdComplexContentExtension] = QnXsdExtension; TokenToQName[(int)Token.XsdSimpleContentExtension] = QnXsdExtension; TokenToQName[(int)Token.XsdSimpleContent] = QnXsdSimpleContent; TokenToQName[(int)Token.XsdSimpleTypeUnion] = QnXsdUnion; TokenToQName[(int)Token.XsdSimpleTypeList] = QnXsdList; TokenToQName[(int)Token.XsdRedefine] = QnXsdRedefine; TokenToQName[(int)Token.SchemaSource] = QnSource; TokenToQName[(int)Token.SchemaUse] = QnUse; TokenToQName[(int)Token.SchemaForm] = QnForm; TokenToQName[(int)Token.SchemaElementFormDefault] = QnElementFormDefault; TokenToQName[(int)Token.SchemaAttributeFormDefault] = QnAttributeFormDefault; TokenToQName[(int)Token.XmlLang] = QnXmlLang; TokenToQName[(int)Token.Empty] = XmlQualifiedName.Empty; } public SchemaType SchemaTypeFromRoot(string localName, string ns) { if (IsXSDRoot(localName, ns)) { return SchemaType.XSD; } else if (IsXDRRoot(localName, XmlSchemaDatatype.XdrCanonizeUri(ns, _nameTable, this))) { return SchemaType.XDR; } else { return SchemaType.None; } } public bool IsXSDRoot(string localName, string ns) { return Ref.Equal(ns, NsXs) && Ref.Equal(localName, XsdSchema); } public bool IsXDRRoot(string localName, string ns) { return Ref.Equal(ns, NsXdr) && Ref.Equal(localName, XdrSchema); } public enum Token { Empty, SchemaName, SchemaType, SchemaMaxOccurs, SchemaMinOccurs, SchemaInfinite, SchemaModel, SchemaOpen, SchemaClosed, SchemaContent, SchemaMixed, SchemaEmpty, SchemaElementOnly, SchemaTextOnly, SchemaOrder, SchemaSeq, SchemaOne, SchemaMany, SchemaRequired, SchemaYes, SchemaNo, SchemaString, SchemaId, SchemaIdref, SchemaIdrefs, SchemaEntity, SchemaEntities, SchemaNmtoken, SchemaNmtokens, SchemaEnumeration, SchemaDefault, XdrRoot, XdrElementType, XdrElement, XdrGroup, XdrAttributeType, XdrAttribute, XdrDatatype, XdrDescription, XdrExtends, SchemaXdrRootAlias, SchemaDtType, SchemaDtValues, SchemaDtMaxLength, SchemaDtMinLength, SchemaDtMax, SchemaDtMin, SchemaDtMinExclusive, SchemaDtMaxExclusive, SchemaTargetNamespace, SchemaVersion, SchemaFinalDefault, SchemaBlockDefault, SchemaFixed, SchemaAbstract, SchemaBlock, SchemaSubstitutionGroup, SchemaFinal, SchemaNillable, SchemaRef, SchemaBase, SchemaDerivedBy, SchemaNamespace, SchemaProcessContents, SchemaRefer, SchemaPublic, SchemaSystem, SchemaSchemaLocation, SchemaValue, SchemaSource, SchemaAttributeFormDefault, SchemaElementFormDefault, SchemaUse, SchemaForm, XsdSchema, XsdAnnotation, XsdInclude, XsdImport, XsdElement, XsdAttribute, xsdAttributeGroup, XsdAnyAttribute, XsdGroup, XsdAll, XsdChoice, XsdSequence, XsdAny, XsdNotation, XsdSimpleType, XsdComplexType, XsdUnique, XsdKey, XsdKeyref, XsdSelector, XsdField, XsdMinExclusive, XsdMinInclusive, XsdMaxExclusive, XsdMaxInclusive, XsdTotalDigits, XsdFractionDigits, XsdLength, XsdMinLength, XsdMaxLength, XsdEnumeration, XsdPattern, XsdDocumentation, XsdAppInfo, XsdComplexContent, XsdComplexContentExtension, XsdComplexContentRestriction, XsdSimpleContent, XsdSimpleContentExtension, XsdSimpleContentRestriction, XsdSimpleTypeList, XsdSimpleTypeRestriction, XsdSimpleTypeUnion, XsdWhitespace, XsdRedefine, SchemaItemType, SchemaMemberTypes, SchemaXPath, XmlLang }; }; }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Sync; namespace Umbraco.Cms.Infrastructure.Sync { /// <summary> /// Provides a base class for all <see cref="IServerMessenger"/> implementations. /// </summary> public abstract class ServerMessengerBase : IServerMessenger { protected bool DistributedEnabled { get; set; } protected ServerMessengerBase(bool distributedEnabled) { DistributedEnabled = distributedEnabled; } /// <summary> /// Determines whether to make distributed calls when messaging a cache refresher. /// </summary> /// <param name="servers">The registered servers.</param> /// <param name="refresher">The cache refresher.</param> /// <param name="messageType">The message type.</param> /// <returns>true if distributed calls are required; otherwise, false, all we have is the local server.</returns> protected virtual bool RequiresDistributed(ICacheRefresher refresher, MessageType messageType) { return DistributedEnabled; } // ensures that all items in the enumerable are of the same type, either int or Guid. protected static bool GetArrayType(IEnumerable<object> ids, out Type arrayType) { arrayType = null; if (ids == null) return true; foreach (var id in ids) { // only int and Guid are supported if ((id is int) == false && ((id is Guid) == false)) return false; // initialize with first item if (arrayType == null) arrayType = id.GetType(); // check remaining items if (arrayType != id.GetType()) return false; } return true; } #region IServerMessenger public void QueueRefresh<TPayload>(ICacheRefresher refresher, TPayload[] payload) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (payload == null) throw new ArgumentNullException(nameof(payload)); Deliver(refresher, payload); } public void PerformRefresh(ICacheRefresher refresher, string jsonPayload) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (jsonPayload == null) throw new ArgumentNullException(nameof(jsonPayload)); Deliver(refresher, MessageType.RefreshByJson, json: jsonPayload); } public void QueueRefresh<T>(ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (getNumericId == null) throw new ArgumentNullException(nameof(getNumericId)); if (instances == null || instances.Length == 0) return; Func<T, object> getId = x => getNumericId(x); Deliver(refresher, MessageType.RefreshByInstance, getId, instances); } public void QueueRefresh<T>(ICacheRefresher refresher, Func<T, Guid> getGuidId, params T[] instances) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (getGuidId == null) throw new ArgumentNullException(nameof(getGuidId)); if (instances == null || instances.Length == 0) return; Func<T, object> getId = x => getGuidId(x); Deliver(refresher, MessageType.RefreshByInstance, getId, instances); } public void QueueRemove<T>(ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (getNumericId == null) throw new ArgumentNullException(nameof(getNumericId)); if (instances == null || instances.Length == 0) return; Func<T, object> getId = x => getNumericId(x); Deliver(refresher, MessageType.RemoveByInstance, getId, instances); } public void QueueRemove(ICacheRefresher refresher, params int[] numericIds) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (numericIds == null || numericIds.Length == 0) return; Deliver(refresher, MessageType.RemoveById, numericIds.Cast<object>()); } public void QueueRefresh(ICacheRefresher refresher, params int[] numericIds) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (numericIds == null || numericIds.Length == 0) return; Deliver(refresher, MessageType.RefreshById, numericIds.Cast<object>()); } public void QueueRefresh(ICacheRefresher refresher, params Guid[] guidIds) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (guidIds == null || guidIds.Length == 0) return; Deliver(refresher, MessageType.RefreshById, guidIds.Cast<object>()); } public void QueueRefreshAll(ICacheRefresher refresher) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); Deliver(refresher, MessageType.RefreshAll); } //public void PerformNotify(ICacheRefresher refresher, object payload) //{ // if (servers == null) throw new ArgumentNullException("servers"); // if (refresher == null) throw new ArgumentNullException("refresher"); // Deliver(refresher, payload); //} #endregion #region Deliver protected void DeliverLocal<TPayload>(ICacheRefresher refresher, TPayload[] payload) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); StaticApplicationLogging.Logger.LogDebug("Invoking refresher {RefresherType} on local server for message type RefreshByPayload", refresher.GetType()); var payloadRefresher = refresher as IPayloadCacheRefresher<TPayload>; if (payloadRefresher == null) throw new InvalidOperationException("The cache refresher " + refresher.GetType() + " is not of type " + typeof(IPayloadCacheRefresher<TPayload>)); payloadRefresher.Refresh(payload); } /// <summary> /// Executes the non strongly typed <see cref="ICacheRefresher"/> on the local/current server /// </summary> /// <param name="refresher"></param> /// <param name="messageType"></param> /// <param name="ids"></param> /// <param name="json"></param> /// <remarks> /// Since this is only for non strongly typed <see cref="ICacheRefresher"/> it will throw for message types that by instance /// </remarks> protected void DeliverLocal(ICacheRefresher refresher, MessageType messageType, IEnumerable<object> ids = null, string json = null) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); StaticApplicationLogging.Logger.LogDebug("Invoking refresher {RefresherType} on local server for message type {MessageType}", refresher.GetType(), messageType); switch (messageType) { case MessageType.RefreshAll: refresher.RefreshAll(); break; case MessageType.RefreshById: if (ids != null) foreach (var id in ids) { if (id is int) refresher.Refresh((int) id); else if (id is Guid) refresher.Refresh((Guid) id); else throw new InvalidOperationException("The id must be either an int or a Guid."); } break; case MessageType.RefreshByJson: var jsonRefresher = refresher as IJsonCacheRefresher; if (jsonRefresher == null) throw new InvalidOperationException("The cache refresher " + refresher.GetType() + " is not of type " + typeof(IJsonCacheRefresher)); jsonRefresher.Refresh(json); break; case MessageType.RemoveById: if (ids != null) foreach (var id in ids) { if (id is int) refresher.Remove((int) id); else throw new InvalidOperationException("The id must be an int."); } break; default: //case MessageType.RefreshByInstance: //case MessageType.RemoveByInstance: throw new NotSupportedException("Invalid message type " + messageType); } } /// <summary> /// Executes the strongly typed <see cref="ICacheRefresher{T}"/> on the local/current server /// </summary> /// <typeparam name="T"></typeparam> /// <param name="refresher"></param> /// <param name="messageType"></param> /// <param name="getId"></param> /// <param name="instances"></param> /// <remarks> /// Since this is only for strongly typed <see cref="ICacheRefresher{T}"/> it will throw for message types that are not by instance /// </remarks> protected void DeliverLocal<T>(ICacheRefresher refresher, MessageType messageType, Func<T, object> getId, IEnumerable<T> instances) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); StaticApplicationLogging.Logger.LogDebug("Invoking refresher {RefresherType} on local server for message type {MessageType}", refresher.GetType(), messageType); var typedRefresher = refresher as ICacheRefresher<T>; switch (messageType) { case MessageType.RefreshAll: refresher.RefreshAll(); break; case MessageType.RefreshByInstance: if (typedRefresher == null) throw new InvalidOperationException("The refresher must be a typed refresher."); foreach (var instance in instances) typedRefresher.Refresh(instance); break; case MessageType.RemoveByInstance: if (typedRefresher == null) throw new InvalidOperationException("The cache refresher " + refresher.GetType() + " is not a typed refresher."); foreach (var instance in instances) typedRefresher.Remove(instance); break; default: //case MessageType.RefreshById: //case MessageType.RemoveById: //case MessageType.RefreshByJson: throw new NotSupportedException("Invalid message type " + messageType); } } //protected void DeliverLocal(ICacheRefresher refresher, object payload) //{ // if (refresher == null) throw new ArgumentNullException("refresher"); // Current.Logger.LogDebug("Invoking refresher {0} on local server for message type Notify", // () => refresher.GetType()); // refresher.Notify(payload); //} protected abstract void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable<object> ids = null, string json = null); //protected abstract void DeliverRemote(ICacheRefresher refresher, object payload); protected virtual void Deliver<TPayload>(ICacheRefresher refresher, TPayload[] payload) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); // deliver local DeliverLocal(refresher, payload); // distribute? if (RequiresDistributed(refresher, MessageType.RefreshByJson) == false) return; // deliver remote var json = JsonConvert.SerializeObject(payload); DeliverRemote(refresher, MessageType.RefreshByJson, null, json); } protected virtual void Deliver(ICacheRefresher refresher, MessageType messageType, IEnumerable<object> ids = null, string json = null) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); var idsA = ids?.ToArray(); // deliver local DeliverLocal(refresher, messageType, idsA, json); // distribute? if (RequiresDistributed(refresher, messageType) == false) return; // deliver remote DeliverRemote(refresher, messageType, idsA, json); } protected virtual void Deliver<T>(ICacheRefresher refresher, MessageType messageType, Func<T, object> getId, IEnumerable<T> instances) { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); var instancesA = instances.ToArray(); // deliver local DeliverLocal(refresher, messageType, getId, instancesA); // distribute? if (RequiresDistributed(refresher, messageType) == false) return; // deliver remote // map ByInstance to ById as there's no remote instances if (messageType == MessageType.RefreshByInstance) messageType = MessageType.RefreshById; if (messageType == MessageType.RemoveByInstance) messageType = MessageType.RemoveById; // convert instances to identifiers var idsA = instancesA.Select(getId).ToArray(); DeliverRemote(refresher, messageType, idsA); } //protected virtual void Deliver(ICacheRefresher refresher, object payload) //{ // if (servers == null) throw new ArgumentNullException("servers"); // if (refresher == null) throw new ArgumentNullException("refresher"); // var serversA = servers.ToArray(); // // deliver local // DeliverLocal(refresher, payload); // // distribute? // if (RequiresDistributed(serversA, refresher, messageType) == false) // return; // // deliver remote // DeliverRemote(serversA, refresher, payload); //} #endregion public abstract void Sync(); public abstract void SendMessages(); } }
#region Licence /**************************************************************************** Copyright 1999-2015 Vincent J. Jacquet. All rights reserved. Permission is granted to anyone to use this software for any purpose on any computer system, and to alter it and redistribute it, subject to the following restrictions: 1. The author is not responsible for the consequences of use of this software, no matter how awful, even if they arise from flaws in it. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. Since few users ever read sources, credits must appear in the documentation. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. Since few users ever read sources, credits must appear in the documentation. 4. This notice may not be removed or altered. ****************************************************************************/ #endregion using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Xml; using System.Xml.Schema; using WmcSoft.CustomTools.Design; using WmcSoft.CodeBuilders; using System.Resources; namespace WmcSoft.CustomTools { [Guid("ddd7d995-7b4f-4ff6-9173-bb66ddd4ab77")] [CustomTool("WmcSoft.CodeGenerator", true)] [SupportedCategory(SupportedCategoryAttribute.CSharpCategory)] [SupportedCategory(SupportedCategoryAttribute.VBCategory)] [SupportedVersion("8.0")] [SupportedVersion("9.0")] [SupportedVersion("10.0")] [SupportedVersion("11.0")] [SupportedVersion("12.0")] [ComVisible(true)] public class CodeGenerator : CustomToolBase { #region Lifecycle public CodeGenerator() { } public CodeGenerator(CodeDomProvider codeProvider) { this.CodeProvider = codeProvider; } #endregion #region Generation method #if OLD private CodeCommentStatement Generate(XmlSchemaAnnotation annotation) { CodeCommentStatement comment = new CodeCommentStatement(); StringBuilder builder = new StringBuilder(); builder.AppendLine("<summary>"); foreach (XmlSchemaDocumentation documentation in annotation.Items) { foreach (XmlNode node in documentation.Markup) { node.Normalize(); TextReader reader = new StringReader(node.InnerText); while (reader.Peek() != -1) { string line = reader.ReadLine().Trim(); if (!String.IsNullOrEmpty(line)) { builder.Append(' '); builder.AppendLine(line); } } } } builder.Append(" </summary>"); comment.Comment = new CodeComment(builder.ToString(), true); return comment; } private CodeTypeReference Generate(XmlSchemaSimpleType type) { CodeTypeReference codeTypeReference = GetReference(type.Name); if (type.Content is XmlSchemaSimpleTypeRestriction) { XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)type.Content; if (restriction.BaseTypeName.Name == "token" || restriction.BaseTypeName.Name == "NMTOKEN") { bool isEnumeration = false; int minLength = -1; int maxLength = -1; foreach (XmlSchemaObject item in restriction.Facets) { if (item is XmlSchemaMinLengthFacet) { minLength = Int16.Parse(((XmlSchemaMinLengthFacet)item).Value); } else if (item is XmlSchemaMaxLengthFacet) { maxLength = Int16.Parse(((XmlSchemaMaxLengthFacet)item).Value); } else if (item is XmlSchemaEnumerationFacet) { isEnumeration = true; break; } } if (isEnumeration) { CodeTypeDeclaration codeType = new CodeTypeDeclaration(type.Name); codeType.IsEnum = true; codeType.IsPartial = true; codeType.Comments.Add(Generate(type.Annotation)); codeNamespace.Types.Add(codeType); foreach (XmlSchemaEnumerationFacet item in restriction.Facets) { CodeTypeMember member = new CodeMemberField(); member.Name = String.Join("", item.Value.Split(' ', '-', '/')); codeType.Members.Add(member); } codeTypeReference.BaseType = codeType.Name; } else if (minLength == 1 && maxLength == 1) { codeTypeReference.BaseType = "System.Char"; } else { codeTypeReference.BaseType = "System.String"; } } else if (restriction.BaseTypeName.Name == "int") { codeTypeReference.BaseType = "System.Int32"; } restriction = null; } return codeTypeReference; } private CodeTypeReference GetReference(string name) { CodeTypeReference codeTypeReference = null; if (references.ContainsKey(name)) { codeTypeReference = references[name]; } else { codeTypeReference = new CodeTypeReference("System.Object"); references[name] = codeTypeReference; } return codeTypeReference; } private CodeTypeDeclaration Generate(XmlSchemaComplexType type) { CodeTypeDeclaration codeType = new CodeTypeDeclaration(type.Name); codeType.IsClass = true; codeType.IsPartial = true; codeType.Comments.Add(Generate(type.Annotation)); if (type.IsAbstract) { codeType.TypeAttributes |= TypeAttributes.Abstract; } if (type.Particle is XmlSchemaSequence) { XmlSchemaSequence sequence = (XmlSchemaSequence)type.Particle; foreach (XmlSchemaObject item in sequence.Items) { XmlSchemaElement element = item as XmlSchemaElement; if (element != null) { CodeMemberField field = new CodeMemberField(); field.Name = element.Name; field.Attributes |= MemberAttributes.Public; if (element.SchemaType != null) { field.Type = new CodeTypeReference("System.String"); } else { field.Type = GetReference(element.SchemaTypeName.Name); } codeType.Members.Add(field); } } } return codeType; } private CodeCompileUnit Generate(XmlSchema schema) { CodeCompileUnit compileUnit = new CodeCompileUnit(); this.compileUnit = compileUnit; CodeNamespace codeNamespace = new CodeNamespace("Broadsoft"); compileUnit.Namespaces.Add(codeNamespace); this.codeNamespace = codeNamespace; // Add the new namespace import for the System namespace. // codeNamespace.Imports.Add(new CodeNamespaceImport("System")); // Generate the complex types // foreach (XmlSchemaObject item in schema.Items) { if (item is XmlSchemaSimpleType) { Generate((XmlSchemaSimpleType)item); } else if (item is XmlSchemaComplexType) { CodeTypeDeclaration codeType = Generate((XmlSchemaComplexType)item); codeNamespace.Types.Add(codeType); } else { base.GeneratorErrorCallback(true, 1000, "Unhandled schema object", item.LineNumber, item.LinePosition); } } return compileUnit; } #endif #endregion #region Custom Tool public override string GetDefaultExtension() { return ".CodeGen" + base.GetDefaultExtension(); } protected override string OnGenerateCode(string inputFileName, string inputFileContent) { var writer = new StringWriter(); var options = new CodeGeneratorOptions { BlankLinesBetweenMembers = false, ElseOnClosing = true, }; // read the input... var settings = new XmlReaderSettings(); var resourceManager = new ResourceManager(typeof(CodeBuilder)); using (var stream = typeof(CodeBuilder).Assembly.GetManifestResourceStream("WmcSoft.CodeBuilders.CodeGenerator.xsd")) { var schema = XmlSchema.Read(stream, new ValidationEventHandler(SchemaValidationCallback)); settings.Schemas.Add(schema); settings.ValidationType = ValidationType.Schema; } CodeBuilderContext context = new CodeBuilderContext(this); using (XmlReader reader = XmlReader.Create(new StringReader(inputFileContent), settings)) { if (reader.Read()) { reader.MoveToContent(); Debug.Assert(reader.Name == "codeGenerator"); CodeGeneratorBuilder builder = new CodeGeneratorBuilder(); builder.Parse(reader, context); } } // then generate the code CodeProvider.GenerateCodeFromCompileUnit(context.CurrentCompileUnit, writer, options); return writer.ToString(); } public static void SchemaValidationCallback(object sender, ValidationEventArgs args) { Console.WriteLine(args.Message); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.Azure.Management.EventGrid; using Microsoft.Azure.Management.EventGrid.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using EventGrid.Tests.TestHelper; using Xunit; namespace EventGrid.Tests.ScenarioTests { public partial class ScenarioTests { const string AzureFunctionEndpointUrl = "https://eventgridrunnerfunction.azurewebsites.net/api/HttpTriggerCSharp1?code=<HIDDEN>"; [Fact] public void EventSubscriptionCreateGetUpdateDelete() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { this.InitializeClients(context); var location = this.ResourceManagementClient.GetLocationFromProvider(); var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location); if (string.IsNullOrWhiteSpace(resourceGroup)) { resourceGroup = TestUtilities.GenerateName(EventGridManagementHelper.ResourceGroupPrefix); this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup); } var topicName = TestUtilities.GenerateName(EventGridManagementHelper.TopicPrefix); var createTopicResponse = this.EventGridManagementClient.Topics.CreateOrUpdateAsync(resourceGroup, topicName, new Topic() { Location = location, Tags = new Dictionary<string, string>() { {"tag1", "value1"}, {"tag2", "value2"} } }).Result; Assert.NotNull(createTopicResponse); Assert.Equal(createTopicResponse.Name, topicName); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Get the created topic var getTopicResponse = EventGridManagementClient.Topics.Get(resourceGroup, topicName); if (string.Compare(getTopicResponse.ProvisioningState, "Succeeded", true) != 0) { TestUtilities.Wait(TimeSpan.FromSeconds(5)); } getTopicResponse = EventGridManagementClient.Topics.Get(resourceGroup, topicName); Assert.NotNull(getTopicResponse); Assert.Equal("Succeeded", getTopicResponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase); Assert.Equal(location, getTopicResponse.Location, StringComparer.CurrentCultureIgnoreCase); // Create an event subscription to this topic var eventSubscriptionName = TestUtilities.GenerateName(EventGridManagementHelper.EventSubscriptionPrefix); string scope = $"/subscriptions/55f3dcd4-cac7-43b4-990b-a139d62a1eb2/resourceGroups/{resourceGroup}/providers/Microsoft.EventGrid/topics/{topicName}"; EventSubscription eventSubscription = new EventSubscription() { Destination = new WebHookEventSubscriptionDestination() { EndpointUrl = AzureFunctionEndpointUrl }, Filter = new EventSubscriptionFilter() { IncludedEventTypes = new List<string>() { "All" }, IsSubjectCaseSensitive = true, SubjectBeginsWith = "TestPrefix", SubjectEndsWith = "TestSuffix" }, Labels = new List<string>() { "TestLabel1", "TestLabel2" } }; var eventSubscriptionResponse = this.EventGridManagementClient.EventSubscriptions.CreateOrUpdateAsync(scope, eventSubscriptionName, eventSubscription).Result; Assert.NotNull(eventSubscriptionResponse); Assert.Equal(eventSubscriptionResponse.Name, eventSubscriptionName); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Get the created event subscription eventSubscriptionResponse = EventGridManagementClient.EventSubscriptions.Get(scope, eventSubscriptionName); if (string.Compare(eventSubscriptionResponse.ProvisioningState, "Succeeded", true) != 0) { TestUtilities.Wait(TimeSpan.FromSeconds(5)); } eventSubscriptionResponse = EventGridManagementClient.EventSubscriptions.Get(scope, eventSubscriptionName); Assert.NotNull(eventSubscriptionResponse); Assert.Equal("Succeeded", eventSubscriptionResponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase); Assert.Equal("TestPrefix", eventSubscriptionResponse.Filter.SubjectBeginsWith, StringComparer.CurrentCultureIgnoreCase); Assert.Equal("TestSuffix", eventSubscriptionResponse.Filter.SubjectEndsWith, StringComparer.CurrentCultureIgnoreCase); // Update the event subscription var eventSubscriptionUpdateParameters = new EventSubscriptionUpdateParameters() { Destination = new WebHookEventSubscriptionDestination() { EndpointUrl = AzureFunctionEndpointUrl, }, Filter = new EventSubscriptionFilter() { IncludedEventTypes = new List<string>() { "Event1", "Event2" }, SubjectEndsWith = ".jpg", SubjectBeginsWith = "TestPrefix" }, Labels = new List<string>() { "UpdatedLabel1", "UpdatedLabel2", } }; eventSubscriptionResponse = this.eventGridManagementClient.EventSubscriptions.UpdateAsync(scope, eventSubscriptionName, eventSubscriptionUpdateParameters).Result; Assert.Equal(".jpg", eventSubscriptionResponse.Filter.SubjectEndsWith, StringComparer.CurrentCultureIgnoreCase); Assert.Contains(eventSubscriptionResponse.Labels, label => label == "UpdatedLabel1"); // List event subscriptions var eventSubscriptionsList = this.EventGridManagementClient.EventSubscriptions.ListRegionalByResourceGroupAsync(resourceGroup, location).Result; Assert.Contains(eventSubscriptionsList, es => es.Name == eventSubscriptionName); // Delete the event subscription EventGridManagementClient.EventSubscriptions.DeleteAsync(scope, eventSubscriptionName).Wait(); // Delete the topic EventGridManagementClient.Topics.DeleteAsync(resourceGroup, topicName).Wait(); } } [Fact] public void EventSubscriptionToAzureSubscriptionCreateGetUpdateDelete() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { InitializeClients(context); // Create an event subscription to an Azure subscription var eventSubscriptionName = TestUtilities.GenerateName(EventGridManagementHelper.EventSubscriptionPrefix); string scope = $"/subscriptions/55f3dcd4-cac7-43b4-990b-a139d62a1eb2"; EventSubscription eventSubscription = new EventSubscription() { Destination = new WebHookEventSubscriptionDestination() { EndpointUrl = AzureFunctionEndpointUrl }, Filter = new EventSubscriptionFilter() { IncludedEventTypes = new List<string>() { "All" }, IsSubjectCaseSensitive = false, SubjectBeginsWith = "TestPrefix", SubjectEndsWith = "TestSuffix" }, Labels = new List<string>() { "TestLabel1", "TestLabel2" } }; var eventSubscriptionResponse = this.EventGridManagementClient.EventSubscriptions.CreateOrUpdateAsync(scope, eventSubscriptionName, eventSubscription).Result; Assert.NotNull(eventSubscriptionResponse); Assert.Equal(eventSubscriptionResponse.Name, eventSubscriptionName); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Get the created event subscription eventSubscriptionResponse = EventGridManagementClient.EventSubscriptions.Get(scope, eventSubscriptionName); if (string.Compare(eventSubscriptionResponse.ProvisioningState, "Succeeded", true) != 0) { TestUtilities.Wait(TimeSpan.FromSeconds(5)); } eventSubscriptionResponse = EventGridManagementClient.EventSubscriptions.Get(scope, eventSubscriptionName); Assert.NotNull(eventSubscriptionResponse); Assert.Equal("Succeeded", eventSubscriptionResponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase); // List event subscriptions by Azure subscription var eventSubscriptionsList = this.EventGridManagementClient.EventSubscriptions.ListGlobalBySubscriptionAsync().Result; Assert.Contains(eventSubscriptionsList, es => es.Name == eventSubscriptionName); // Delete the event subscription EventGridManagementClient.EventSubscriptions.DeleteAsync(scope, eventSubscriptionName).Wait(); } } [Fact] public void EventSubscriptionToResourceGroupCreateGetUpdateDelete() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { InitializeClients(context); var location = this.ResourceManagementClient.GetLocationFromProvider(); var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location); if (string.IsNullOrWhiteSpace(resourceGroup)) { resourceGroup = TestUtilities.GenerateName(EventGridManagementHelper.ResourceGroupPrefix); this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup); } // Create an event subscription to a resource group var eventSubscriptionName = TestUtilities.GenerateName(EventGridManagementHelper.EventSubscriptionPrefix); string scope = $"/subscriptions/55f3dcd4-cac7-43b4-990b-a139d62a1eb2/resourceGroups/{resourceGroup}"; EventSubscription eventSubscription = new EventSubscription() { Destination = new WebHookEventSubscriptionDestination() { EndpointUrl = AzureFunctionEndpointUrl }, Filter = new EventSubscriptionFilter() { IncludedEventTypes = new List<string>() { "All" }, IsSubjectCaseSensitive = false, SubjectBeginsWith = "TestPrefix", SubjectEndsWith = "TestSuffix" }, Labels = new List<string>() { "TestLabel1", "TestLabel2" } }; var eventSubscriptionResponse = this.EventGridManagementClient.EventSubscriptions.CreateOrUpdateAsync(scope, eventSubscriptionName, eventSubscription).Result; Assert.NotNull(eventSubscriptionResponse); Assert.Equal(eventSubscriptionResponse.Name, eventSubscriptionName); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Get the created event subscription eventSubscriptionResponse = EventGridManagementClient.EventSubscriptions.Get(scope, eventSubscriptionName); if (string.Compare(eventSubscriptionResponse.ProvisioningState, "Succeeded", true) != 0) { TestUtilities.Wait(TimeSpan.FromSeconds(5)); } eventSubscriptionResponse = EventGridManagementClient.EventSubscriptions.Get(scope, eventSubscriptionName); Assert.NotNull(eventSubscriptionResponse); Assert.Equal("Succeeded", eventSubscriptionResponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase); // List the event subscriptions by resource group var eventSubscriptionsList = this.EventGridManagementClient.EventSubscriptions.ListGlobalByResourceGroup(resourceGroup); Assert.Contains(eventSubscriptionsList, es => es.Name == eventSubscriptionName); // Delete the event subscription EventGridManagementClient.EventSubscriptions.DeleteAsync(scope, eventSubscriptionName).Wait(); } } [Fact] public void EventSubscriptionCreateGetUpdateDeleteWithDeadLettering() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { this.InitializeClients(context); var location = this.ResourceManagementClient.GetLocationFromProvider(); var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location); if (string.IsNullOrWhiteSpace(resourceGroup)) { resourceGroup = TestUtilities.GenerateName(EventGridManagementHelper.ResourceGroupPrefix); this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup); } var topicName = TestUtilities.GenerateName(EventGridManagementHelper.TopicPrefix); var createTopicResponse = this.EventGridManagementClient.Topics.CreateOrUpdateAsync(resourceGroup, topicName, new Topic() { Location = location }).Result; Assert.NotNull(createTopicResponse); Assert.Equal(createTopicResponse.Name, topicName); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Get the created topic var getTopicResponse = EventGridManagementClient.Topics.Get(resourceGroup, topicName); if (string.Compare(getTopicResponse.ProvisioningState, "Succeeded", true) != 0) { TestUtilities.Wait(TimeSpan.FromSeconds(5)); } getTopicResponse = EventGridManagementClient.Topics.Get(resourceGroup, topicName); Assert.NotNull(getTopicResponse); Assert.Equal("Succeeded", getTopicResponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase); Assert.Equal(location, getTopicResponse.Location, StringComparer.CurrentCultureIgnoreCase); // Create an event subscription to this topic var eventSubscriptionName = TestUtilities.GenerateName(EventGridManagementHelper.EventSubscriptionPrefix); string scope = $"/subscriptions/55f3dcd4-cac7-43b4-990b-a139d62a1eb2/resourceGroups/{resourceGroup}/providers/Microsoft.EventGrid/topics/{topicName}"; EventSubscription eventSubscription = new EventSubscription() { Destination = new WebHookEventSubscriptionDestination() { EndpointUrl = AzureFunctionEndpointUrl }, Filter = new EventSubscriptionFilter() { IncludedEventTypes = new List<string>() { "All" }, IsSubjectCaseSensitive = true, SubjectBeginsWith = "TestPrefix", SubjectEndsWith = "TestSuffix" }, Labels = new List<string>() { "TestLabel1", "TestLabel2" }, DeadLetterDestination = new StorageBlobDeadLetterDestination() { ResourceId = "/subscriptions/55f3dcd4-cac7-43b4-990b-a139d62a1eb2/resourceGroups/kalstest/providers/Microsoft.Storage/storageAccounts/kalsdemo", BlobContainerName = "dlq" }, RetryPolicy = new RetryPolicy() { EventTimeToLiveInMinutes = 20, MaxDeliveryAttempts = 10 } }; var eventSubscriptionResponse = this.EventGridManagementClient.EventSubscriptions.CreateOrUpdateAsync(scope, eventSubscriptionName, eventSubscription).Result; Assert.NotNull(eventSubscriptionResponse); Assert.Equal(eventSubscriptionResponse.Name, eventSubscriptionName); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Get the created event subscription eventSubscriptionResponse = EventGridManagementClient.EventSubscriptions.Get(scope, eventSubscriptionName); if (string.Compare(eventSubscriptionResponse.ProvisioningState, "Succeeded", true) != 0) { TestUtilities.Wait(TimeSpan.FromSeconds(5)); } eventSubscriptionResponse = EventGridManagementClient.EventSubscriptions.Get(scope, eventSubscriptionName); Assert.NotNull(eventSubscriptionResponse); Assert.Equal("Succeeded", eventSubscriptionResponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase); Assert.Equal("TestPrefix", eventSubscriptionResponse.Filter.SubjectBeginsWith, StringComparer.CurrentCultureIgnoreCase); Assert.Equal("TestSuffix", eventSubscriptionResponse.Filter.SubjectEndsWith, StringComparer.CurrentCultureIgnoreCase); // Delete the event subscription EventGridManagementClient.EventSubscriptions.DeleteAsync(scope, eventSubscriptionName).Wait(); // Delete the topic EventGridManagementClient.Topics.DeleteAsync(resourceGroup, topicName).Wait(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using DertInfo.WEB.Models; using DertInfo.WEB.ViewModels.EventVMs; using DertInfo.WEB.Controllers.Base; using System.Configuration; using DertInfo.WEB.Core.Session; using DertInfo.WEB.ViewModels.ImageVMs; using WebMatrix.WebData; using DertInfo.WEB.Core.AssetManagement; using DertInfo.WEB.Core; using DertInfo.WEB.BLL; namespace DertInfo.WEB.Controllers { [Authorize(Roles = "Admin,Config")] public class EventController : DertControllerBase { #region Dependency Injection private readonly IAccessKeyService accessKeyServ; private readonly IEventService eventServ; private readonly IRegistrationService registrationServ; private readonly IEventRepository eventRepo; private readonly IRegistrationRepository registrationRepo; private readonly IUserProfileRepository userProfileRepo; private readonly ITeamRepository teamRepo; private readonly IImageRepository imageRepo; private readonly IAccessValidation accessValidation; #endregion public EventController(IEventService eventService, IAccessKeyService accessKeyService,IRegistrationService registrationService, IEventRepository eventRepository, IRegistrationRepository registrationRepository, IUserProfileRepository userProfileRepository, ITeamRepository teamRepository, IImageRepository imageRepository, IAccessValidation accessValidation) { this.eventServ = eventService; this.accessKeyServ = accessKeyService; this.registrationServ = registrationService; this.eventRepo = eventRepository; this.registrationRepo = registrationRepository; this.userProfileRepo = userProfileRepository; this.teamRepo = teamRepository; this.imageRepo = imageRepository; this.accessValidation = accessValidation; } #region Pages // GET: /Event/Details/5 [Authorize(Roles = "Admin")] public ActionResult Details(int id) { //Get the requested object(s) Event myEvent = eventRepo.Find(id); if (myEvent != null) { //Test permission accessValidation.Validate(this.CurrentUser, myEvent.AccessToken); if (!accessValidation.ViewPermitted()) { return RedirectToAction("Error401", "Error"); } //Apply logic //Build the View Model EventDetailsViewModel eventDetailsViewModel = new EventDetailsViewModel(myEvent, registrationServ); //Return the View base.ApplyBreadcrumbItem(eventDetailsViewModel, id, eventDetailsViewModel.EventVM.Name, true); return View(eventDetailsViewModel); } else { //Log not found //Return 404 return RedirectToAction("Error404", "Error"); } } // GET: /Event/Create public ActionResult Create() { int userId = WebSecurity.GetUserId(this.CurrentUser); string userFullName = userProfileRepo.Find(userId).YourName; ViewBag.ImageValidationFailed = false; EventCreateViewModel eventCreateVM = new EventCreateViewModel(); eventCreateVM.Prepare(userFullName); base.ApplyBreadcrumbItem(eventCreateVM, 0, "Create New Event"); return View(eventCreateVM); } // POST: /Event/Create [HttpPost] public ActionResult Create(EventCreateViewModel eventCreateVM) //Upload Image file takes the file submission. { var file = eventCreateVM.ImageUploadVM.UploadImageFile; ViewBag.ImageValidationFailed = false; if (file == null) { ViewBag.ImageValidationFailed = true; return View(eventCreateVM); } //Create the event Event myEvent = eventCreateVM.EventVM.ToModel(); //Create a new Access Token AccessKey accessKey = accessKeyServ.New(); accessKeyServ.AddPermission(accessKey.AccessKeyRef, this.CurrentUser, true, true, true); myEvent.AccessToken = accessKey.AccessKeyRef.ToString(); myEvent.IsDeleted = false; eventRepo.InsertOrUpdate(myEvent); eventRepo.Save(); //todo - Automagically create stub information for an event. switch(eventCreateVM.EventTemplateSelectionVM.SelectedTemplateRef) { case "Basic": eventServ.Apply_Minimal_Template_ToEvent(myEvent); break; case "DERT": eventServ.Apply_Dert_Template_ToEvent(myEvent); break; } //Handle to posted Image if (file != null) { int imageId = 0; ImageStorage imageStorage = new ImageStorage("~/_temp/", "Images_EventImages_"); imageStorage.SaveImageToLocalTemp(eventCreateVM.ImageUploadVM.UploadImageFile); imageStorage.UploadToAzure(); imageId = imageStorage.CreateImageReference(eventCreateVM.EventVM.Name); imageStorage.CleanUp(); imageRepo.ApplyEventImage(myEvent.Id, imageId,true); } return RedirectToAction("Details", "Event", new { id = myEvent.Id }); } public ActionResult PublishResults(int id) { eventServ.Publish_Event_Results(id); return RedirectToAction("Details",new {id=id}); } public ActionResult UnPublishResults(int id) { eventServ.UnPublish_Event_Results(id); return RedirectToAction("Details", new { id = id }); } public ActionResult EmailResults(int id) { eventServ.Email_Results(id); return RedirectToAction("Details", new { id = id }); } #endregion #region Partials public ActionResult Detail_Partial(int id) { Event myEvent = eventRepo.Find(id); EventViewModel eventVM = new EventViewModel(myEvent); return PartialView("P_Detail", eventVM); } public ActionResult Edit_Partial(int id) { Event myEvent = eventRepo.Find(id); EventViewModel eventVM = new EventViewModel(myEvent); return PartialView("P_Edit", eventVM); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit_Partial(EventViewModel eventVM) { Models.Event myEvent = eventVM.ToModel(); eventRepo.InsertOrUpdate(myEvent); eventRepo.Save(); //Update the values from the save eventVM.EventId = myEvent.Id; eventVM.AccessToken = myEvent.AccessToken; eventVM.AccessTokenVM = new ViewModels.AccessTokenVMs.AccessTokenViewModel(this.CurrentUser,eventVM.AccessToken); eventVM.DateCreated = myEvent.DateCreated; eventVM.DateModified = myEvent.DateModified; eventVM.CreatedBy = myEvent.CreatedBy; eventVM.ModifiedBy = myEvent.ModifiedBy; eventVM.IsDeleted = myEvent.IsDeleted; //Notify Success Of Save base.AddNotification(Core.Enumerations.NotificationTypes.Green, "Event Information Updated"); //Return View base.PostSectionMessage("success", "swapbox_event_detail", "Your changes have been saved."); return PartialView("P_Detail", eventVM); } #endregion #region Json [HttpPost] public ActionResult CloseEvent_Json(int id) { //Get the requested object(s) Event myEvent = eventRepo.Find(id); if (myEvent != null) { //Test permission accessValidation.Validate(this.CurrentUser, myEvent.AccessToken); if (!accessValidation.EditPermitted()) { return Json(new { HttpStatus=401, Error= "You do not have permission to perform this action." } ); } eventServ.Close_Event(myEvent.Id); //Removed as event service introduced. ////Apply logic //List<Registration> registrations = registrationRepo.AllByEventIdIncluding(myEvent.Id,r => r.AttendingMembers).ToList(); //foreach(Registration registration in registrations) //{ // //Change the access token to not permit any edits // Guid accessToken = Guid.Parse(registration.AccessToken); // accessKeyServ.ChangePermissionAllUsers(accessToken, true, false, false); // registration.FlowState = Enumerations.RegistrationState.Closed; // //Should Apply to relevant objects // //Member Attendnace // //Team Attendance // //Dances // //Compeitition Entry //} ////wip - continue here ////foreach(Registration registration in registrations) ////{ //// //Create //// registration.FlowState = Enumerations.RegistrationState.Closed; //// foreach(MemberAttendance memberAttendance in registration.AttendingMembers) //// { //// memberAttendance. //// } ////} } return Json(new {}); } #endregion #region Private protected override void Dispose(bool disposing) { if (disposing) { eventServ.Dispose(); eventRepo.Dispose(); registrationRepo.Dispose(); userProfileRepo.Dispose(); teamRepo.Dispose(); imageRepo.Dispose(); } base.Dispose(disposing); } #endregion #region Removed //public ViewResult Index() //{ // return View(eventRepository.AllIncluding(myEvent => myEvent.Registrations)); //} // // GET: /Event/ // // //[HttpPost] //public ActionResult CreateXXX(EventViewModel eventVM, HttpPostedFileBase postedImage) //{ // ViewBag.ImageValidationFailed = false; // if (postedImage == null) // ViewBag.ImageValidationFailed = true; // if (!ModelState.IsValid || postedImage == null) // { // return View(); // } // Event myEvent = eventVM.ToModel(); // myEvent.IsDeleted = Core.Enumerations.ObjectState.Populated; // eventRepository.InsertOrUpdate(myEvent); // eventRepository.Save(); // BLL.EventService eventService = new BLL.EventService(); // eventService.FilloutNewEvent(myEvent); // if (postedImage != null) // { // //Upload and save the file. // string storageContainerUrl = ConfigurationSettings.AppSettings["StorageContainerUrl"].ToString(); // string azureFileName = Core.AzureStorage.Images.HandleImagePost(postedImage, "EventImage_" + this.SystemDertYear + "_"); // //Create New Image Object // //todo apply image repository pattern to images // Image image = new Image(storageContainerUrl + azureFileName, myEvent.Name); // //Attach file reference in the database // EventImage eventImage = new EventImage(); // eventImage.Image = image; // eventImage.EventId = myEvent.Id; // eventImage.SaveChanges(this.CurrentUser); // } // return RedirectToAction("Details", "Event", new { id = myEvent.Id }); //} // // GET: /Event/Edit/5 //public ActionResult Edit(int id) //{ // return View(eventRepository.Find(id)); //} //// //// POST: /Event/Edit/5 //[HttpPost] //public ActionResult Edit(Event myEvent) //{ // if (ModelState.IsValid) { // eventRepository.InsertOrUpdate(myEvent); // eventRepository.Save(); // return RedirectToAction("Index"); // } else { // return View(); // } //} // // GET: /Event/Delete/5 //public ActionResult Delete(int id) //{ // return View(eventRepository.Find(id)); //} // // POST: /Event/Delete/5 //[HttpPost, ActionName("Delete")] //public ActionResult DeleteConfirmed(int id) //{ // eventRepository.Delete(id); // eventRepository.Save(); // return RedirectToAction("Index"); //} #endregion } }
//------------------------------------------------------------------------------ // <copyright file="HtmlTable.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.HtmlControls { using System; using System.Reflection; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Web; using System.Web.UI; using System.Security.Permissions; /// <devdoc> /// <para>Defines the properties, methods, and events for the /// <see cref='System.Web.UI.HtmlControls.HtmlTable'/> /// control that allows programmatic access on the /// server to the HTML &lt;table&gt; element.</para> /// </devdoc> [ ParseChildren(true, "Rows") ] public class HtmlTable : HtmlContainerControl { HtmlTableRowCollection rows; /// <devdoc> /// Initializes a new instance of the <see cref='System.Web.UI.HtmlControls.HtmlTable'/> class. /// </devdoc> public HtmlTable() : base("table") { } /// <devdoc> /// <para>Gets or sets the alignment of content within the <see cref='System.Web.UI.HtmlControls.HtmlTable'/> /// control.</para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Align { get { string s = Attributes["align"]; return((s != null) ? s : String.Empty); } set { Attributes["align"] = MapStringAttributeToString(value); } } /// <devdoc> /// <para>Gets or sets the background color of an <see cref='System.Web.UI.HtmlControls.HtmlTable'/> /// control.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string BgColor { get { string s = Attributes["bgcolor"]; return((s != null) ? s : String.Empty); } set { Attributes["bgcolor"] = MapStringAttributeToString(value); } } /// <devdoc> /// <para>Gets or sets the width of the border, in pixels, of an /// <see cref='System.Web.UI.HtmlControls.HtmlTable'/> control.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(-1), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public int Border { get { string s = Attributes["border"]; return((s != null) ? Int32.Parse(s, CultureInfo.InvariantCulture) : -1); } set { Attributes["border"] = MapIntegerAttributeToString(value); } } /// <devdoc> /// <para>Gets or sets the border color of an <see cref='System.Web.UI.HtmlControls.HtmlTable'/> control.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string BorderColor { get { string s = Attributes["bordercolor"]; return((s != null) ? s : String.Empty); } set { Attributes["bordercolor"] = MapStringAttributeToString(value); } } /// <devdoc> /// <para> /// Gets or sets the cell padding, in pixels, for an <see langword='HtmlTable'/> control. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public int CellPadding { get { string s = Attributes["cellpadding"]; return((s != null) ? Int32.Parse(s, CultureInfo.InvariantCulture) : -1); } set { Attributes["cellpadding"] = MapIntegerAttributeToString(value); } } /// <devdoc> /// <para> /// Gets or sets the cell spacing, in pixels, for an <see langword='HtmlTable'/> control. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public int CellSpacing { get { string s = Attributes["cellspacing"]; return((s != null) ? Int32.Parse(s, CultureInfo.InvariantCulture) : -1); } set { Attributes["cellspacing"] = MapIntegerAttributeToString(value); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override string InnerHtml { get { throw new NotSupportedException(SR.GetString(SR.InnerHtml_not_supported, this.GetType().Name)); } set { throw new NotSupportedException(SR.GetString(SR.InnerHtml_not_supported, this.GetType().Name)); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override string InnerText { get { throw new NotSupportedException(SR.GetString(SR.InnerText_not_supported, this.GetType().Name)); } set { throw new NotSupportedException(SR.GetString(SR.InnerText_not_supported, this.GetType().Name)); } } /// <devdoc> /// <para> /// Gets or sets the height of an <see langword='HtmlTable'/> /// control. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Height { get { string s = Attributes["height"]; return((s != null) ? s : String.Empty); } set { Attributes["height"] = MapStringAttributeToString(value); } } /// <devdoc> /// <para> /// Gets or sets the width of an <see langword='HtmlTable'/> control. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Width { get { string s = Attributes["width"]; return((s != null) ? s : String.Empty); } set { Attributes["width"] = MapStringAttributeToString(value); } } /// <devdoc> /// <para> /// Gets a collection that contains all of the rows in an /// <see langword='HtmlTable'/> control. An empty collection is returned if no /// &lt;tr&gt; elements are contained within the control. /// </para> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), IgnoreUnknownContent() ] public virtual HtmlTableRowCollection Rows { get { if (rows == null) rows = new HtmlTableRowCollection(this); return rows; } } /// <internalonly/> /// <devdoc> /// </devdoc> protected internal override void RenderChildren(HtmlTextWriter writer) { writer.WriteLine(); writer.Indent++; base.RenderChildren(writer); writer.Indent--; } /// <internalonly/> /// <devdoc> /// </devdoc> protected override void RenderEndTag(HtmlTextWriter writer) { base.RenderEndTag(writer); writer.WriteLine(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override ControlCollection CreateControlCollection() { return new HtmlTableRowControlCollection(this); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected class HtmlTableRowControlCollection : ControlCollection { internal HtmlTableRowControlCollection (Control owner) : base(owner) { } /// <devdoc> /// <para>Adds the specified <see cref='System.Web.UI.Control'/> object to the collection. The new control is added /// to the end of the array.</para> /// </devdoc> public override void Add(Control child) { if (child is HtmlTableRow) base.Add(child); else throw new ArgumentException(SR.GetString(SR.Cannot_Have_Children_Of_Type, "HtmlTable", child.GetType().Name.ToString(CultureInfo.InvariantCulture))); // throw an exception here } /// <devdoc> /// <para>Adds the specified <see cref='System.Web.UI.Control'/> object to the collection. The new control is added /// to the array at the specified index location.</para> /// </devdoc> public override void AddAt(int index, Control child) { if (child is HtmlTableRow) base.AddAt(index, child); else throw new ArgumentException(SR.GetString(SR.Cannot_Have_Children_Of_Type, "HtmlTable", child.GetType().Name.ToString(CultureInfo.InvariantCulture))); // throw an exception here } } // class HtmlTableRowControlCollection } }
// Copyright 2018-2020 Andrew White // // 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. #if NETCOREAPP2_1 using System; using System.Threading.Tasks; using Finbuckle.MultiTenant; using Finbuckle.MultiTenant.Strategies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Moq; using Xunit; public class RouteStrategyShould { internal void configTestRoute(Microsoft.AspNetCore.Routing.IRouteBuilder routes) { routes.MapRoute("Defaut", "{__tenant__=}/{controller=Home}/{action=Index}"); } [Theory] [InlineData("/initech", "initech", "initech")] [InlineData("/", "initech", "")] public async Task ReturnExpectedIdentifier(string path, string identifier, string expected) { Action<IRouteBuilder> configRoutes = (IRouteBuilder rb) => rb.MapRoute("testRoute", "{__tenant__}"); IWebHostBuilder hostBuilder = GetTestHostBuilder(identifier, configRoutes); using (var server = new TestServer(hostBuilder)) { var client = server.CreateClient(); var response = await client.GetStringAsync(path); Assert.Equal(expected, response); } } [Fact] public void ThrowIfContextIsNotHttpContext() { var context = new Object(); var adcp = new Mock<IActionDescriptorCollectionProvider>().Object; var strategy = new RouteStrategy("__tenant__", configTestRoute, adcp); Assert.Throws<AggregateException>(() => strategy.GetIdentifierAsync(context).Result); } [Fact] public async Task ReturnNullIfNoRouteParamMatch() { Action<IRouteBuilder> configRoutes = (IRouteBuilder rb) => rb.MapRoute("testRoute", "{controller}"); IWebHostBuilder hostBuilder = GetTestHostBuilder("test_tenant", configRoutes); using (var server = new TestServer(hostBuilder)) { var client = server.CreateClient(); var response = await client.GetStringAsync("/test_tenant"); Assert.Equal("", response); } } [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public void ThrowIfRouteParamIsNullOrWhitespace(string testString) { var adcp = new Mock<IActionDescriptorCollectionProvider>().Object; Assert.Throws<ArgumentException>(() => new RouteStrategy(testString, configTestRoute, adcp)); } private static IWebHostBuilder GetTestHostBuilder(string identifier, Action<IRouteBuilder> configRoutes) { return new WebHostBuilder() .ConfigureServices(services => { services.AddMultiTenant<TenantInfo>().WithRouteStrategy(configRoutes).WithInMemoryStore(); services.AddMvc(); }) .Configure(app => { app.UseMultiTenant(); app.Run(async context => { if (context.GetMultiTenantContext<TenantInfo>()?.TenantInfo != null) { await context.Response.WriteAsync(context.GetMultiTenantContext<TenantInfo>()?.TenantInfo.Id); } }); var store = app.ApplicationServices.GetRequiredService<IMultiTenantStore<TenantInfo>>(); store.TryAddAsync(new TenantInfo { Id = identifier, Identifier = identifier }).Wait(); }); } } #else using System; using System.Threading.Tasks; using Finbuckle.MultiTenant; using Finbuckle.MultiTenant.Strategies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Xunit; public class RouteStrategyShould { [Theory] [InlineData("/initech", "initech", "initech")] [InlineData("/", "initech", "")] public async Task ReturnExpectedIdentifier(string path, string identifier, string expected) { IWebHostBuilder hostBuilder = GetTestHostBuilder(identifier, "{__tenant__=}"); using (var server = new TestServer(hostBuilder)) { var client = server.CreateClient(); var response = await client.GetStringAsync(path); Assert.Equal(expected, response); } } [Fact] public void ThrowIfContextIsNotHttpContext() { var context = new Object(); var strategy = new RouteStrategy("__tenant__"); Assert.Throws<AggregateException>(() => strategy.GetIdentifierAsync(context).Result); } [Fact] public async Task ReturnNullIfNoRouteParamMatch() { IWebHostBuilder hostBuilder = GetTestHostBuilder("test_tenant", "{controller}"); using (var server = new TestServer(hostBuilder)) { var client = server.CreateClient(); var response = await client.GetStringAsync("/test_tenant"); Assert.Equal("", response); } } [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public void ThrowIfRouteParamIsNullOrWhitespace(string testString) { Assert.Throws<ArgumentException>(() => new RouteStrategy(testString)); } private static IWebHostBuilder GetTestHostBuilder(string identifier, string routePattern) { return new WebHostBuilder() .ConfigureServices(services => { services.AddMultiTenant<TenantInfo>().WithRouteStrategy().WithInMemoryStore(); services.AddMvc(); }) .Configure(app => { app.UseRouting(); app.UseMultiTenant(); app.UseEndpoints(endpoints => { endpoints.Map(routePattern, async context => { if (context.GetMultiTenantContext<TenantInfo>()?.TenantInfo != null) { await context.Response.WriteAsync(context.GetMultiTenantContext<TenantInfo>().TenantInfo.Id); } }); }); var store = app.ApplicationServices.GetRequiredService<IMultiTenantStore<TenantInfo>>(); store.TryAddAsync(new TenantInfo { Id = identifier, Identifier = identifier }).Wait(); }); } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace UnitTest.Interfaces { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Bond.Comm; using NUnit.Framework; [TestFixture] public class LoggerTests { public static readonly Logger BlackHole = new Logger(null, includeDebug: false); private class TestLogSink : ILogSink { public LogSeverity? LastMessageSeverity; public string LastMessage; public Exception LastException; public int MessagesReceived; public void Log(string message, LogSeverity severity, Exception exception) { LastMessageSeverity = severity; LastMessage = message; LastException = exception; MessagesReceived++; } public void Clear() { LastMessageSeverity = null; LastMessage = null; LastException = null; } } private TestLogSink sink = new TestLogSink(); private Logger logger; /// <summary> /// Carries a <see cref="LogSeverity"/> so we can tell which invocation produced it. /// </summary> private class TestException : Exception { public readonly LogSeverity Severity; public TestException(LogSeverity severity) { Severity = severity; } } private readonly List<LogSeverity> allSeverities = Enum.GetValues(typeof(LogSeverity)).Cast<LogSeverity>().OrderBy(x => x).ToList(); private readonly Dictionary<LogSeverity, Action<Logger, string, object[]>> levelLoggers = new Dictionary<LogSeverity, Action<Logger, string, object[]>> { { LogSeverity.Debug, (logger, message, args) => logger.Site().Debug(message, args) }, { LogSeverity.Information, (logger, message, args) => logger.Site().Information(message, args) }, { LogSeverity.Warning, (logger, message, args) => logger.Site().Warning(message, args) }, { LogSeverity.Error, (logger, message, args) => logger.Site().Error(message, args) }, { LogSeverity.Fatal, (logger, message, args) => logger.Site().Fatal(message, args) }, }; private readonly Dictionary<LogSeverity, Action<Logger, Exception, string, object[]>> exceptionLevelLoggers = new Dictionary<LogSeverity, Action<Logger, Exception, string, object[]>> { { LogSeverity.Debug, (logger, ex, message, args) => logger.Site().Debug(ex, message, args) }, { LogSeverity.Information, (logger, ex, message, args) => logger.Site().Information(ex, message, args) }, { LogSeverity.Warning, (logger, ex, message, args) => logger.Site().Warning(ex, message, args) }, { LogSeverity.Error, (logger, ex, message, args) => logger.Site().Error(ex, message, args) }, { LogSeverity.Fatal, (logger, ex, message, args) => logger.Site().Fatal(ex, message, args) }, }; private static Tuple<string, object[]> MakeMessage(LogSeverity severity, bool withException) { var args = new object[] { severity, withException ? "" : "out" }; return new Tuple<string, object[]>("logged at {0} with{1} an Exception", args); } [SetUp] public void SetUp() { sink = new TestLogSink(); // Tests that exercise filtering enable it themselves. logger = new Logger(sink, includeDebug: true); } [TearDown] public void TearDown() { logger = null; } [Test] public void SeveritiesAreSorted() { // Assumes allSeverities is sorted. var numSeverities = allSeverities.Count; var lower = allSeverities.GetRange(0, numSeverities - 1); var higher = allSeverities.GetRange(1, numSeverities - 1); var pairs = lower.Zip(higher, (l, h) => new Tuple<LogSeverity, LogSeverity>(l, h)); foreach (var pair in pairs) { Assert.Less(pair.Item1, pair.Item2); } } [Test] public void LoggingWithNullHandlerIsANoOp() { // Clear the Sink registered by SetUp(). logger = new Logger(null, includeDebug: false); logger.Site().Information("no-op"); } [Test] public void Levels() { // Make sure we're testing all severities. CollectionAssert.AreEquivalent(allSeverities, levelLoggers.Keys); CollectionAssert.AreEquivalent(allSeverities, exceptionLevelLoggers.Keys); var messagesLogged = 0; foreach (var severity in allSeverities) { var logIt = levelLoggers[severity]; var logItEx = exceptionLevelLoggers[severity]; var exception = new TestException(severity); var formatArgs = MakeMessage(severity, withException: false); var format = formatArgs.Item1; var args = formatArgs.Item2; var message = string.Format(format, args); logIt(logger, format, args); Assert.AreEqual(severity, sink.LastMessageSeverity); StringAssert.Contains(message, sink.LastMessage); Assert.IsNull(sink.LastException); Assert.AreEqual(messagesLogged + 1, sink.MessagesReceived); messagesLogged++; sink.Clear(); formatArgs = MakeMessage(severity, withException: true); format = formatArgs.Item1; args = formatArgs.Item2; message = string.Format(format, args); logItEx(logger, exception, format, args); Assert.AreEqual(severity, sink.LastMessageSeverity); StringAssert.Contains(message, sink.LastMessage); Assert.NotNull(sink.LastException); Assert.AreEqual(severity, ((TestException)sink.LastException).Severity); Assert.AreEqual(messagesLogged + 1, sink.MessagesReceived); messagesLogged++; sink.Clear(); } } [Test] public void FilterDebugging() { logger = new Logger(sink, includeDebug: false); var messagesHandled = sink.MessagesReceived; // Assumes allSeverities is sorted. foreach (var severity in allSeverities) { var message = "level " + severity; levelLoggers[severity](logger, message, new object[0]); if (severity == LogSeverity.Debug) { Assert.Null(sink.LastMessage); Assert.Null(sink.LastMessageSeverity); Assert.AreEqual(messagesHandled, sink.MessagesReceived); } else { StringAssert.Contains(message, sink.LastMessage); Assert.AreEqual(severity, sink.LastMessageSeverity); Assert.AreEqual(messagesHandled + 1, sink.MessagesReceived); messagesHandled = sink.MessagesReceived; } } } [Test] public void LogContext() { // There are two statements on this line so that expectedLineNumber will be correct for the Warning(). logger.Site().Warning("context"); var expectedLineNumber = new StackFrame(0, true).GetFileLineNumber(); StringAssert.Contains(nameof(LoggerTests) + ".cs:" + expectedLineNumber, sink.LastMessage); StringAssert.Contains(nameof(LogContext), sink.LastMessage); } [Test] public void FatalWithFormatted() { var messagesLogged = 0; var exception = new TestException(LogSeverity.Fatal); var formatArgs = MakeMessage(LogSeverity.Fatal, withException: false); var format = formatArgs.Item1; var args = formatArgs.Item2; var formatted = string.Format(format, args); var messageReturned = logger.Site().FatalAndReturnFormatted(format, args); Assert.AreEqual(LogSeverity.Fatal, sink.LastMessageSeverity); StringAssert.Contains(formatted, sink.LastMessage); StringAssert.Contains(messageReturned, sink.LastMessage); Assert.IsNull(sink.LastException); Assert.AreEqual(messagesLogged + 1, sink.MessagesReceived); messagesLogged++; sink.Clear(); formatArgs = MakeMessage(LogSeverity.Fatal, withException: true); format = formatArgs.Item1; args = formatArgs.Item2; formatted = string.Format(format, args); messageReturned = logger.Site().FatalAndReturnFormatted(exception, format, args); Assert.AreEqual(LogSeverity.Fatal, sink.LastMessageSeverity); StringAssert.Contains(formatted, sink.LastMessage); StringAssert.Contains(messageReturned, sink.LastMessage); Assert.NotNull(sink.LastException); Assert.AreEqual(LogSeverity.Fatal, ((TestException)sink.LastException).Severity); Assert.AreEqual(messagesLogged + 1, sink.MessagesReceived); } [Test] public void FormatExceptionIsSuppressedAndLogged() { const string format = "{0}, but there's nothing to put here: {1}"; const string somestr = "any string goes here"; // Messages below Error should be raised to Error. logger.Site().Debug(format, somestr); Assert.AreEqual(LogSeverity.Error, sink.LastMessageSeverity); Assert.Null(sink.LastException); StringAssert.Contains(format, sink.LastMessage); StringAssert.Contains(somestr, sink.LastMessage); StringAssert.Contains("Log call threw", sink.LastMessage); // Messages above Error should be left at their original severity. logger.Site().Fatal(format, somestr); Assert.AreEqual(LogSeverity.Fatal, sink.LastMessageSeverity); Assert.Null(sink.LastException); StringAssert.Contains(format, sink.LastMessage); StringAssert.Contains(somestr, sink.LastMessage); StringAssert.Contains("Log call threw", sink.LastMessage); } [Test] public void LogInstanceReuseThrows() { var logInstance = logger.Site(); logInstance.Warning("This should be fine."); Assert.Throws<InvalidOperationException>(() => logInstance.Warning("This should throw.")); } } }
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Xml; using Nop.Core; using Nop.Core.Caching; using Nop.Core.Data; using Nop.Core.Domain.Common; using Nop.Core.Domain.Localization; using Nop.Data; using Nop.Services.Events; using Nop.Services.Logging; namespace Nop.Services.Localization { /// <summary> /// Provides information about localization /// </summary> public partial class LocalizationService : ILocalizationService { #region Constants /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : language ID /// </remarks> private const string LOCALSTRINGRESOURCES_ALL_KEY = "Nop.lsr.all-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : language ID /// {1} : resource key /// </remarks> private const string LOCALSTRINGRESOURCES_BY_RESOURCENAME_KEY = "Nop.lsr.{0}-{1}"; /// <summary> /// Key pattern to clear cache /// </summary> private const string LOCALSTRINGRESOURCES_PATTERN_KEY = "Nop.lsr."; #endregion #region Fields private readonly IRepository<LocaleStringResource> _lsrRepository; private readonly IWorkContext _workContext; private readonly ILogger _logger; private readonly ILanguageService _languageService; private readonly ICacheManager _cacheManager; private readonly IDataProvider _dataProvider; private readonly IDbContext _dbContext; private readonly CommonSettings _commonSettings; private readonly LocalizationSettings _localizationSettings; private readonly IEventPublisher _eventPublisher; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="logger">Logger</param> /// <param name="workContext">Work context</param> /// <param name="lsrRepository">Locale string resource repository</param> /// <param name="languageService">Language service</param> /// <param name="dataProvider">Data provider</param> /// <param name="dbContext">Database Context</param> /// <param name="commonSettings">Common settings</param> /// <param name="localizationSettings">Localization settings</param> /// <param name="eventPublisher">Event published</param> public LocalizationService(ICacheManager cacheManager, ILogger logger, IWorkContext workContext, IRepository<LocaleStringResource> lsrRepository, ILanguageService languageService, IDataProvider dataProvider, IDbContext dbContext, CommonSettings commonSettings, LocalizationSettings localizationSettings, IEventPublisher eventPublisher) { this._cacheManager = cacheManager; this._logger = logger; this._workContext = workContext; this._lsrRepository = lsrRepository; this._languageService = languageService; this._dataProvider = dataProvider; this._dbContext = dbContext; this._commonSettings = commonSettings; this._localizationSettings = localizationSettings; this._eventPublisher = eventPublisher; } #endregion #region Methods /// <summary> /// Deletes a locale string resource /// </summary> /// <param name="localeStringResource">Locale string resource</param> public virtual void DeleteLocaleStringResource(LocaleStringResource localeStringResource) { if (localeStringResource == null) throw new ArgumentNullException("localeStringResource"); _lsrRepository.Delete(localeStringResource); //cache _cacheManager.RemoveByPattern(LOCALSTRINGRESOURCES_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(localeStringResource); } /// <summary> /// Gets a locale string resource /// </summary> /// <param name="localeStringResourceId">Locale string resource identifier</param> /// <returns>Locale string resource</returns> public virtual LocaleStringResource GetLocaleStringResourceById(int localeStringResourceId) { if (localeStringResourceId == 0) return null; return _lsrRepository.GetById(localeStringResourceId); } /// <summary> /// Gets a locale string resource /// </summary> /// <param name="resourceName">A string representing a resource name</param> /// <returns>Locale string resource</returns> public virtual LocaleStringResource GetLocaleStringResourceByName(string resourceName) { if (_workContext.WorkingLanguage != null) return GetLocaleStringResourceByName(resourceName, _workContext.WorkingLanguage.Id); return null; } /// <summary> /// Gets a locale string resource /// </summary> /// <param name="resourceName">A string representing a resource name</param> /// <param name="languageId">Language identifier</param> /// <param name="logIfNotFound">A value indicating whether to log error if locale string resource is not found</param> /// <returns>Locale string resource</returns> public virtual LocaleStringResource GetLocaleStringResourceByName(string resourceName, int languageId, bool logIfNotFound = true) { var query = from lsr in _lsrRepository.Table orderby lsr.ResourceName where lsr.LanguageId == languageId && lsr.ResourceName == resourceName select lsr; var localeStringResource = query.FirstOrDefault(); if (localeStringResource == null && logIfNotFound) _logger.Warning(string.Format("Resource string ({0}) not found. Language ID = {1}", resourceName, languageId)); return localeStringResource; } /// <summary> /// Gets all locale string resources by language identifier /// </summary> /// <param name="languageId">Language identifier</param> /// <returns>Locale string resources</returns> public virtual IList<LocaleStringResource> GetAllResources(int languageId) { var query = from l in _lsrRepository.Table orderby l.ResourceName where l.LanguageId == languageId select l; var locales = query.ToList(); return locales; } /// <summary> /// Inserts a locale string resource /// </summary> /// <param name="localeStringResource">Locale string resource</param> public virtual void InsertLocaleStringResource(LocaleStringResource localeStringResource) { if (localeStringResource == null) throw new ArgumentNullException("localeStringResource"); _lsrRepository.Insert(localeStringResource); //cache _cacheManager.RemoveByPattern(LOCALSTRINGRESOURCES_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(localeStringResource); } /// <summary> /// Updates the locale string resource /// </summary> /// <param name="localeStringResource">Locale string resource</param> public virtual void UpdateLocaleStringResource(LocaleStringResource localeStringResource) { if (localeStringResource == null) throw new ArgumentNullException("localeStringResource"); _lsrRepository.Update(localeStringResource); //cache _cacheManager.RemoveByPattern(LOCALSTRINGRESOURCES_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(localeStringResource); } /// <summary> /// Gets all locale string resources by language identifier /// </summary> /// <param name="languageId">Language identifier</param> /// <returns>Locale string resources</returns> public virtual Dictionary<string, KeyValuePair<int,string>> GetAllResourceValues(int languageId) { string key = string.Format(LOCALSTRINGRESOURCES_ALL_KEY, languageId); return _cacheManager.Get(key, () => { //we use no tracking here for performance optimization //anyway records are loaded only for read-only operations var query = from l in _lsrRepository.TableNoTracking orderby l.ResourceName where l.LanguageId == languageId select l; var locales = query.ToList(); //format: <name, <id, value>> var dictionary = new Dictionary<string, KeyValuePair<int, string>>(); foreach (var locale in locales) { var resourceName = locale.ResourceName.ToLowerInvariant(); if (!dictionary.ContainsKey(resourceName)) dictionary.Add(resourceName, new KeyValuePair<int, string>(locale.Id, locale.ResourceValue)); } return dictionary; }); } /// <summary> /// Gets a resource string based on the specified ResourceKey property. /// </summary> /// <param name="resourceKey">A string representing a ResourceKey.</param> /// <returns>A string representing the requested resource string.</returns> public virtual string GetResource(string resourceKey) { if (_workContext.WorkingLanguage != null) return GetResource(resourceKey, _workContext.WorkingLanguage.Id); return ""; } /// <summary> /// Gets a resource string based on the specified ResourceKey property. /// </summary> /// <param name="resourceKey">A string representing a ResourceKey.</param> /// <param name="languageId">Language identifier</param> /// <param name="logIfNotFound">A value indicating whether to log error if locale string resource is not found</param> /// <param name="defaultValue">Default value</param> /// <param name="returnEmptyIfNotFound">A value indicating whether an empty string will be returned if a resource is not found and default value is set to empty string</param> /// <returns>A string representing the requested resource string.</returns> public virtual string GetResource(string resourceKey, int languageId, bool logIfNotFound = true, string defaultValue = "", bool returnEmptyIfNotFound = false) { string result = string.Empty; if (resourceKey == null) resourceKey = string.Empty; resourceKey = resourceKey.Trim().ToLowerInvariant(); if (_localizationSettings.LoadAllLocaleRecordsOnStartup) { //load all records (we know they are cached) var resources = GetAllResourceValues(languageId); if (resources.ContainsKey(resourceKey)) { result = resources[resourceKey].Value; } } else { //gradual loading string key = string.Format(LOCALSTRINGRESOURCES_BY_RESOURCENAME_KEY, languageId, resourceKey); string lsr = _cacheManager.Get(key, () => { var query = from l in _lsrRepository.Table where l.ResourceName == resourceKey && l.LanguageId == languageId select l.ResourceValue; return query.FirstOrDefault(); }); if (lsr != null) result = lsr; } if (String.IsNullOrEmpty(result)) { if (logIfNotFound) _logger.Warning(string.Format("Resource string ({0}) is not found. Language ID = {1}", resourceKey, languageId)); if (!String.IsNullOrEmpty(defaultValue)) { result = defaultValue; } else { if (!returnEmptyIfNotFound) result = resourceKey; } } return result; } /// <summary> /// Export language resources to xml /// </summary> /// <param name="language">Language</param> /// <returns>Result in XML format</returns> public virtual string ExportResourcesToXml(Language language) { if (language == null) throw new ArgumentNullException("language"); var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); var xmlWriter = new XmlTextWriter(stringWriter); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("Language"); xmlWriter.WriteAttributeString("Name", language.Name); xmlWriter.WriteAttributeString("SupportedVersion", NopVersion.CurrentVersion); var resources = GetAllResources(language.Id); foreach (var resource in resources) { xmlWriter.WriteStartElement("LocaleResource"); xmlWriter.WriteAttributeString("Name", resource.ResourceName); xmlWriter.WriteElementString("Value", null, resource.ResourceValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); return stringWriter.ToString(); } /// <summary> /// Import language resources from XML file /// </summary> /// <param name="language">Language</param> /// <param name="xml">XML</param> /// <param name="updateExistingResources">A value indicating whether to update existing resources</param> public virtual void ImportResourcesFromXml(Language language, string xml, bool updateExistingResources = true) { if (language == null) throw new ArgumentNullException("language"); if (String.IsNullOrEmpty(xml)) return; if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported) { //SQL 2005 insists that your XML schema incoding be in UTF-16. //Otherwise, you'll get "XML parsing: line 1, character XXX, unable to switch the encoding" //so let's remove XML declaration var inDoc = new XmlDocument(); inDoc.LoadXml(xml); var sb = new StringBuilder(); using (var xWriter = XmlWriter.Create(sb, new XmlWriterSettings { OmitXmlDeclaration = true })) { inDoc.Save(xWriter); xWriter.Close(); } var outDoc = new XmlDocument(); outDoc.LoadXml(sb.ToString()); xml = outDoc.OuterXml; //stored procedures are enabled and supported by the database. var pLanguageId = _dataProvider.GetParameter(); pLanguageId.ParameterName = "LanguageId"; pLanguageId.Value = language.Id; pLanguageId.DbType = DbType.Int32; var pXmlPackage = _dataProvider.GetParameter(); pXmlPackage.ParameterName = "XmlPackage"; pXmlPackage.Value = xml; pXmlPackage.DbType = DbType.Xml; var pUpdateExistingResources = _dataProvider.GetParameter(); pUpdateExistingResources.ParameterName = "UpdateExistingResources"; pUpdateExistingResources.Value = updateExistingResources; pUpdateExistingResources.DbType = DbType.Boolean; //long-running query. specify timeout (600 seconds) _dbContext.ExecuteSqlCommand("EXEC [LanguagePackImport] @LanguageId, @XmlPackage, @UpdateExistingResources", false, 600, pLanguageId, pXmlPackage, pUpdateExistingResources); } else { //stored procedures aren't supported var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); var nodes = xmlDoc.SelectNodes(@"//Language/LocaleResource"); foreach (XmlNode node in nodes) { string name = node.Attributes["Name"].InnerText.Trim(); string value = ""; var valueNode = node.SelectSingleNode("Value"); if (valueNode != null) value = valueNode.InnerText; if (String.IsNullOrEmpty(name)) continue; //do not use "Insert"/"Update" methods because they clear cache //let's bulk insert var resource = language.LocaleStringResources.FirstOrDefault(x => x.ResourceName.Equals(name, StringComparison.InvariantCultureIgnoreCase)); if (resource != null) { if (updateExistingResources) { resource.ResourceValue = value; } } else { language.LocaleStringResources.Add( new LocaleStringResource { ResourceName = name, ResourceValue = value }); } } _languageService.UpdateLanguage(language); } //clear cache _cacheManager.RemoveByPattern(LOCALSTRINGRESOURCES_PATTERN_KEY); } #endregion } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// ExternalShipment /// </summary> [DataContract] public partial class ExternalShipment : IEquatable<ExternalShipment> { /// <summary> /// Initializes a new instance of the <see cref="ExternalShipment" /> class. /// </summary> [JsonConstructorAttribute] protected ExternalShipment() { } /// <summary> /// Initializes a new instance of the <see cref="ExternalShipment" /> class. /// </summary> /// <param name="OrderId">OrderId (required).</param> /// <param name="CarrierId">CarrierId (required).</param> /// <param name="ParcelAccountId">ParcelAccountId (required).</param> /// <param name="ThirdPartyParcelAccountId">ThirdPartyParcelAccountId.</param> /// <param name="Freight">Freight.</param> /// <param name="TrackingNo">TrackingNo (required).</param> /// <param name="Dim1In">Dim1In.</param> /// <param name="Dim2In">Dim2In.</param> /// <param name="Dim3In">Dim3In.</param> /// <param name="WeightLbs">WeightLbs.</param> /// <param name="DimWeight">DimWeight.</param> /// <param name="Residential">Residential (default to false).</param> /// <param name="Zone">Zone.</param> public ExternalShipment(double? OrderId = null, int? CarrierId = null, int? ParcelAccountId = null, int? ThirdPartyParcelAccountId = null, double? Freight = null, string TrackingNo = null, double? Dim1In = null, double? Dim2In = null, double? Dim3In = null, double? WeightLbs = null, double? DimWeight = null, bool? Residential = null, string Zone = null) { // to ensure "OrderId" is required (not null) if (OrderId == null) { throw new InvalidDataException("OrderId is a required property for ExternalShipment and cannot be null"); } else { this.OrderId = OrderId; } // to ensure "CarrierId" is required (not null) if (CarrierId == null) { throw new InvalidDataException("CarrierId is a required property for ExternalShipment and cannot be null"); } else { this.CarrierId = CarrierId; } // to ensure "ParcelAccountId" is required (not null) if (ParcelAccountId == null) { throw new InvalidDataException("ParcelAccountId is a required property for ExternalShipment and cannot be null"); } else { this.ParcelAccountId = ParcelAccountId; } // to ensure "TrackingNo" is required (not null) if (TrackingNo == null) { throw new InvalidDataException("TrackingNo is a required property for ExternalShipment and cannot be null"); } else { this.TrackingNo = TrackingNo; } this.ThirdPartyParcelAccountId = ThirdPartyParcelAccountId; this.Freight = Freight; this.Dim1In = Dim1In; this.Dim2In = Dim2In; this.Dim3In = Dim3In; this.WeightLbs = WeightLbs; this.DimWeight = DimWeight; // use default value if no "Residential" provided if (Residential == null) { this.Residential = false; } else { this.Residential = Residential; } this.Zone = Zone; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets OrderId /// </summary> [DataMember(Name="orderId", EmitDefaultValue=false)] public double? OrderId { get; set; } /// <summary> /// Gets or Sets CarrierId /// </summary> [DataMember(Name="carrierId", EmitDefaultValue=false)] public int? CarrierId { get; set; } /// <summary> /// Gets or Sets ParcelAccountId /// </summary> [DataMember(Name="parcelAccountId", EmitDefaultValue=false)] public int? ParcelAccountId { get; set; } /// <summary> /// Gets or Sets ThirdPartyParcelAccountId /// </summary> [DataMember(Name="thirdPartyParcelAccountId", EmitDefaultValue=false)] public int? ThirdPartyParcelAccountId { get; set; } /// <summary> /// Gets or Sets Freight /// </summary> [DataMember(Name="freight", EmitDefaultValue=false)] public double? Freight { get; set; } /// <summary> /// Gets or Sets TrackingNo /// </summary> [DataMember(Name="trackingNo", EmitDefaultValue=false)] public string TrackingNo { get; set; } /// <summary> /// Gets or Sets Dim1In /// </summary> [DataMember(Name="dim1In", EmitDefaultValue=false)] public double? Dim1In { get; set; } /// <summary> /// Gets or Sets Dim2In /// </summary> [DataMember(Name="dim2In", EmitDefaultValue=false)] public double? Dim2In { get; set; } /// <summary> /// Gets or Sets Dim3In /// </summary> [DataMember(Name="dim3In", EmitDefaultValue=false)] public double? Dim3In { get; set; } /// <summary> /// Gets or Sets WeightLbs /// </summary> [DataMember(Name="weightLbs", EmitDefaultValue=false)] public double? WeightLbs { get; set; } /// <summary> /// Gets or Sets DimWeight /// </summary> [DataMember(Name="dimWeight", EmitDefaultValue=false)] public double? DimWeight { get; set; } /// <summary> /// Gets or Sets Residential /// </summary> [DataMember(Name="residential", EmitDefaultValue=false)] public bool? Residential { get; set; } /// <summary> /// Gets or Sets Zone /// </summary> [DataMember(Name="zone", EmitDefaultValue=false)] public string Zone { get; set; } /// <summary> /// Gets or Sets Status /// </summary> [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; private 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 ExternalShipment {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" OrderId: ").Append(OrderId).Append("\n"); sb.Append(" CarrierId: ").Append(CarrierId).Append("\n"); sb.Append(" ParcelAccountId: ").Append(ParcelAccountId).Append("\n"); sb.Append(" ThirdPartyParcelAccountId: ").Append(ThirdPartyParcelAccountId).Append("\n"); sb.Append(" Freight: ").Append(Freight).Append("\n"); sb.Append(" TrackingNo: ").Append(TrackingNo).Append("\n"); sb.Append(" Dim1In: ").Append(Dim1In).Append("\n"); sb.Append(" Dim2In: ").Append(Dim2In).Append("\n"); sb.Append(" Dim3In: ").Append(Dim3In).Append("\n"); sb.Append(" WeightLbs: ").Append(WeightLbs).Append("\n"); sb.Append(" DimWeight: ").Append(DimWeight).Append("\n"); sb.Append(" Residential: ").Append(Residential).Append("\n"); sb.Append(" Zone: ").Append(Zone).Append("\n"); sb.Append(" Status: ").Append(Status).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 ExternalShipment); } /// <summary> /// Returns true if ExternalShipment instances are equal /// </summary> /// <param name="other">Instance of ExternalShipment to be compared</param> /// <returns>Boolean</returns> public bool Equals(ExternalShipment other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.OrderId == other.OrderId || this.OrderId != null && this.OrderId.Equals(other.OrderId) ) && ( this.CarrierId == other.CarrierId || this.CarrierId != null && this.CarrierId.Equals(other.CarrierId) ) && ( this.ParcelAccountId == other.ParcelAccountId || this.ParcelAccountId != null && this.ParcelAccountId.Equals(other.ParcelAccountId) ) && ( this.ThirdPartyParcelAccountId == other.ThirdPartyParcelAccountId || this.ThirdPartyParcelAccountId != null && this.ThirdPartyParcelAccountId.Equals(other.ThirdPartyParcelAccountId) ) && ( this.Freight == other.Freight || this.Freight != null && this.Freight.Equals(other.Freight) ) && ( this.TrackingNo == other.TrackingNo || this.TrackingNo != null && this.TrackingNo.Equals(other.TrackingNo) ) && ( this.Dim1In == other.Dim1In || this.Dim1In != null && this.Dim1In.Equals(other.Dim1In) ) && ( this.Dim2In == other.Dim2In || this.Dim2In != null && this.Dim2In.Equals(other.Dim2In) ) && ( this.Dim3In == other.Dim3In || this.Dim3In != null && this.Dim3In.Equals(other.Dim3In) ) && ( this.WeightLbs == other.WeightLbs || this.WeightLbs != null && this.WeightLbs.Equals(other.WeightLbs) ) && ( this.DimWeight == other.DimWeight || this.DimWeight != null && this.DimWeight.Equals(other.DimWeight) ) && ( this.Residential == other.Residential || this.Residential != null && this.Residential.Equals(other.Residential) ) && ( this.Zone == other.Zone || this.Zone != null && this.Zone.Equals(other.Zone) ) && ( this.Status == other.Status || this.Status != null && this.Status.Equals(other.Status) ); } /// <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.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.OrderId != null) hash = hash * 59 + this.OrderId.GetHashCode(); if (this.CarrierId != null) hash = hash * 59 + this.CarrierId.GetHashCode(); if (this.ParcelAccountId != null) hash = hash * 59 + this.ParcelAccountId.GetHashCode(); if (this.ThirdPartyParcelAccountId != null) hash = hash * 59 + this.ThirdPartyParcelAccountId.GetHashCode(); if (this.Freight != null) hash = hash * 59 + this.Freight.GetHashCode(); if (this.TrackingNo != null) hash = hash * 59 + this.TrackingNo.GetHashCode(); if (this.Dim1In != null) hash = hash * 59 + this.Dim1In.GetHashCode(); if (this.Dim2In != null) hash = hash * 59 + this.Dim2In.GetHashCode(); if (this.Dim3In != null) hash = hash * 59 + this.Dim3In.GetHashCode(); if (this.WeightLbs != null) hash = hash * 59 + this.WeightLbs.GetHashCode(); if (this.DimWeight != null) hash = hash * 59 + this.DimWeight.GetHashCode(); if (this.Residential != null) hash = hash * 59 + this.Residential.GetHashCode(); if (this.Zone != null) hash = hash * 59 + this.Zone.GetHashCode(); if (this.Status != null) hash = hash * 59 + this.Status.GetHashCode(); return hash; } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json.Linq; using OrchardCore.Environment.Shell; using OrchardCore.OpenId.Settings; using OrchardCore.Settings; using static OpenIddict.Abstractions.OpenIddictConstants; namespace OrchardCore.OpenId.Services { public class OpenIdServerService : IOpenIdServerService { private readonly IDataProtector _dataProtector; private readonly ILogger _logger; private readonly IMemoryCache _memoryCache; private readonly IOptionsMonitor<ShellOptions> _shellOptions; private readonly ShellSettings _shellSettings; private readonly ISiteService _siteService; private readonly IStringLocalizer S; public OpenIdServerService( IDataProtectionProvider dataProtectionProvider, ILogger<OpenIdServerService> logger, IMemoryCache memoryCache, IOptionsMonitor<ShellOptions> shellOptions, ShellSettings shellSettings, ISiteService siteService, IStringLocalizer<OpenIdServerService> stringLocalizer) { _dataProtector = dataProtectionProvider.CreateProtector(nameof(OpenIdServerService)); _logger = logger; _memoryCache = memoryCache; _shellOptions = shellOptions; _shellSettings = shellSettings; _siteService = siteService; S = stringLocalizer; } public async Task<OpenIdServerSettings> GetSettingsAsync() { var container = await _siteService.GetSiteSettingsAsync(); if (container.Properties.TryGetValue(nameof(OpenIdServerSettings), out var settings)) { return settings.ToObject<OpenIdServerSettings>(); } // If the OpenID server settings haven't been populated yet, the authorization, // logout, token and userinfo endpoints are assumed to be enabled by default. // In this case, only the authorization code and refresh token flows are used. return new OpenIdServerSettings { AuthorizationEndpointPath = "/connect/authorize", GrantTypes = { GrantTypes.AuthorizationCode, GrantTypes.RefreshToken }, LogoutEndpointPath = "/connect/logout", TokenEndpointPath = "/connect/token", UserinfoEndpointPath = "/connect/userinfo" }; } public async Task UpdateSettingsAsync(OpenIdServerSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var container = await _siteService.LoadSiteSettingsAsync(); container.Properties[nameof(OpenIdServerSettings)] = JObject.FromObject(settings); await _siteService.UpdateSiteSettingsAsync(container); } public Task<ImmutableArray<ValidationResult>> ValidateSettingsAsync(OpenIdServerSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var results = ImmutableArray.CreateBuilder<ValidationResult>(); if (settings.GrantTypes.Count == 0) { results.Add(new ValidationResult(S["At least one OpenID Connect flow must be enabled."])); } if (settings.Authority != null) { if (!settings.Authority.IsAbsoluteUri || !settings.Authority.IsWellFormedOriginalString()) { results.Add(new ValidationResult(S["The authority must be a valid absolute URL."], new[] { nameof(settings.Authority) })); } if (!string.IsNullOrEmpty(settings.Authority.Query) || !string.IsNullOrEmpty(settings.Authority.Fragment)) { results.Add(new ValidationResult(S["The authority cannot contain a query string or a fragment."], new[] { nameof(settings.Authority) })); } } if (settings.SigningCertificateStoreLocation != null && settings.SigningCertificateStoreName != null && !string.IsNullOrEmpty(settings.SigningCertificateThumbprint)) { var certificate = GetCertificate( settings.SigningCertificateStoreLocation.Value, settings.SigningCertificateStoreName.Value, settings.SigningCertificateThumbprint); if (certificate == null) { results.Add(new ValidationResult(S["The certificate cannot be found."], new[] { nameof(settings.SigningCertificateThumbprint) })); } else if (!certificate.HasPrivateKey) { results.Add(new ValidationResult(S["The certificate doesn't contain the required private key."], new[] { nameof(settings.SigningCertificateThumbprint) })); } else if (certificate.Archived) { results.Add(new ValidationResult(S["The certificate is not valid because it is marked as archived."], new[] { nameof(settings.SigningCertificateThumbprint) })); } else if (certificate.NotBefore > DateTime.Now || certificate.NotAfter < DateTime.Now) { results.Add(new ValidationResult(S["The certificate is not valid for current date."], new[] { nameof(settings.SigningCertificateThumbprint) })); } } if (settings.GrantTypes.Contains(GrantTypes.Password) && !settings.TokenEndpointPath.HasValue) { results.Add(new ValidationResult(S["The password flow cannot be enabled when the token endpoint is disabled."], new[] { nameof(settings.GrantTypes) })); } if (settings.GrantTypes.Contains(GrantTypes.ClientCredentials) && !settings.TokenEndpointPath.HasValue) { results.Add(new ValidationResult(S["The client credentials flow cannot be enabled when the token endpoint is disabled."], new[] { nameof(settings.GrantTypes) })); } if (settings.GrantTypes.Contains(GrantTypes.AuthorizationCode) && (!settings.AuthorizationEndpointPath.HasValue || !settings.TokenEndpointPath.HasValue)) { results.Add(new ValidationResult(S["The authorization code flow cannot be enabled when the authorization and token endpoints are disabled."], new[] { nameof(settings.GrantTypes) })); } if (settings.GrantTypes.Contains(GrantTypes.RefreshToken)) { if (!settings.TokenEndpointPath.HasValue) { results.Add(new ValidationResult(S["The refresh token flow cannot be enabled when the token endpoint is disabled."], new[] { nameof(settings.GrantTypes) })); } if (!settings.GrantTypes.Contains(GrantTypes.Password) && !settings.GrantTypes.Contains(GrantTypes.AuthorizationCode)) { results.Add(new ValidationResult(S["The refresh token flow can only be enabled if the password, authorization code or hybrid flows are enabled."], new[] { nameof(settings.GrantTypes) })); } } if (settings.GrantTypes.Contains(GrantTypes.Implicit) && !settings.AuthorizationEndpointPath.HasValue) { results.Add(new ValidationResult(S["The implicit flow cannot be enabled when the authorization endpoint is disabled."], new[] { nameof(settings.GrantTypes) })); } if (settings.DisableAccessTokenEncryption && settings.AccessTokenFormat != OpenIdServerSettings.TokenFormat.JsonWebToken) { results.Add(new ValidationResult(S["Access token encryption can only be disabled when using JWT tokens."], new[] { nameof(settings.GrantTypes) })); } return Task.FromResult(results.ToImmutable()); } public Task<ImmutableArray<(X509Certificate2 certificate, StoreLocation location, StoreName name)>> GetAvailableCertificatesAsync() { var certificates = ImmutableArray.CreateBuilder<(X509Certificate2, StoreLocation, StoreName)>(); foreach (StoreLocation location in Enum.GetValues(typeof(StoreLocation))) { foreach (StoreName name in Enum.GetValues(typeof(StoreName))) { // Note: on non-Windows platforms, an exception can // be thrown if the store location/name doesn't exist. try { using var store = new X509Store(name, location); store.Open(OpenFlags.ReadOnly); foreach (var certificate in store.Certificates) { if (!certificate.Archived && certificate.HasPrivateKey) { certificates.Add((certificate, location, name)); } } } catch (CryptographicException) { continue; } } } return Task.FromResult(certificates.ToImmutable()); } public async Task<ImmutableArray<SecurityKey>> GetEncryptionKeysAsync() { var settings = await GetSettingsAsync(); // If a certificate was explicitly provided, return it immediately // instead of using the fallback managed certificates logic. if (settings.EncryptionCertificateStoreLocation != null && settings.EncryptionCertificateStoreName != null && !string.IsNullOrEmpty(settings.EncryptionCertificateThumbprint)) { var certificate = GetCertificate( settings.EncryptionCertificateStoreLocation.Value, settings.EncryptionCertificateStoreName.Value, settings.EncryptionCertificateThumbprint); if (certificate != null) { return ImmutableArray.Create<SecurityKey>(new X509SecurityKey(certificate)); } _logger.LogWarning("The encryption certificate '{Thumbprint}' could not be found in the " + "{StoreLocation}/{StoreName} store.", settings.EncryptionCertificateThumbprint, settings.EncryptionCertificateStoreLocation.Value.ToString(), settings.EncryptionCertificateStoreName.Value.ToString()); } try { var directory = GetEncryptionCertificateDirectory(_shellOptions.CurrentValue, _shellSettings); var certificates = (await GetCertificatesAsync(directory)).Select(tuple => tuple.certificate).ToList(); if (certificates.Any(certificate => certificate.NotAfter.AddDays(-7) > DateTime.Now)) { return ImmutableArray.CreateRange<SecurityKey>( from certificate in certificates select new X509SecurityKey(certificate)); } try { // If the certificates list is empty or only contains certificates about to expire, // generate a new certificate and add it on top of the list to ensure it's preferred // by OpenIddict to the other certificates when issuing new IdentityModel tokens. var certificate = GenerateEncryptionCertificate(_shellSettings); await PersistCertificateAsync(directory, certificate); certificates.Insert(0, certificate); return certificates.Select(certificate => new X509SecurityKey(certificate)).ToImmutableArray<SecurityKey>(); } catch (Exception exception) { _logger.LogError(exception, "An error occurred while trying to generate a X.509 encryption certificate."); } } catch (Exception exception) { _logger.LogWarning(exception, "An error occurred while trying to retrieve the X.509 encryption certificates."); } // If none of the previous attempts succeeded, try to generate an ephemeral RSA key // and add it in the tenant memory cache so that future calls to this method return it. return ImmutableArray.Create<SecurityKey>(_memoryCache.GetOrCreate("05A24221-8C15-4E58-A0A7-56EC3E42E783", entry => { entry.SetPriority(CacheItemPriority.NeverRemove); return new RsaSecurityKey(GenerateRsaSecurityKey(size: 2048)); })); } public async Task<ImmutableArray<SecurityKey>> GetSigningKeysAsync() { var settings = await GetSettingsAsync(); // If a certificate was explicitly provided, return it immediately // instead of using the fallback managed certificates logic. if (settings.SigningCertificateStoreLocation != null && settings.SigningCertificateStoreName != null && !string.IsNullOrEmpty(settings.SigningCertificateThumbprint)) { var certificate = GetCertificate( settings.SigningCertificateStoreLocation.Value, settings.SigningCertificateStoreName.Value, settings.SigningCertificateThumbprint); if (certificate != null) { return ImmutableArray.Create<SecurityKey>(new X509SecurityKey(certificate)); } _logger.LogWarning("The signing certificate '{Thumbprint}' could not be found in the " + "{StoreLocation}/{StoreName} store.", settings.SigningCertificateThumbprint, settings.SigningCertificateStoreLocation.Value.ToString(), settings.SigningCertificateStoreName.Value.ToString()); } try { var directory = GetSigningCertificateDirectory(_shellOptions.CurrentValue, _shellSettings); var certificates = (await GetCertificatesAsync(directory)).Select(tuple => tuple.certificate).ToList(); if (certificates.Any(certificate => certificate.NotAfter.AddDays(-7) > DateTime.Now)) { return ImmutableArray.CreateRange<SecurityKey>( from certificate in certificates select new X509SecurityKey(certificate)); } try { // If the certificates list is empty or only contains certificates about to expire, // generate a new certificate and add it on top of the list to ensure it's preferred // by OpenIddict to the other certificates when issuing new IdentityModel tokens. var certificate = GenerateSigningCertificate(_shellSettings); await PersistCertificateAsync(directory, certificate); certificates.Insert(0, certificate); return certificates.Select(certificate => new X509SecurityKey(certificate)).ToImmutableArray<SecurityKey>(); } catch (Exception exception) { _logger.LogError(exception, "An error occurred while trying to generate a X.509 signing certificate."); } } catch (Exception exception) { _logger.LogWarning(exception, "An error occurred while trying to retrieve the X.509 signing certificates."); } // If none of the previous attempts succeeded, try to generate an ephemeral RSA key // and add it in the tenant memory cache so that future calls to this method return it. return ImmutableArray.Create<SecurityKey>(_memoryCache.GetOrCreate("44788774-20E3-4499-86F0-AB7CE2DF97F6", entry => { entry.SetPriority(CacheItemPriority.NeverRemove); return new RsaSecurityKey(GenerateRsaSecurityKey(size: 2048)); })); } public async Task PruneManagedCertificatesAsync() { List<Exception> exceptions = null; var certificates = new List<(string path, X509Certificate2 certificate)>(); certificates.AddRange(await GetCertificatesAsync(GetEncryptionCertificateDirectory(_shellOptions.CurrentValue, _shellSettings))); certificates.AddRange(await GetCertificatesAsync(GetSigningCertificateDirectory(_shellOptions.CurrentValue, _shellSettings))); foreach (var (path, certificate) in certificates) { // Only delete expired certificates that expired at least 7 days ago. if (certificate.NotAfter.AddDays(7) < DateTime.Now) { try { // Delete both the X.509 certificate and its password file. File.Delete(path); File.Delete(Path.ChangeExtension(path, ".pwd")); } catch (Exception exception) { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(exception); } } } if (exceptions != null) { throw new AggregateException(exceptions); } } private static X509Certificate2 GetCertificate(StoreLocation location, StoreName name, string thumbprint) { using var store = new X509Store(name, location); store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false); return certificates.Count switch { 0 => null, 1 => certificates[0], _ => throw new InvalidOperationException("Multiple certificates with the same thumbprint were found."), }; } private static DirectoryInfo GetEncryptionCertificateDirectory(ShellOptions options, ShellSettings settings) => Directory.CreateDirectory(Path.Combine( options.ShellsApplicationDataPath, options.ShellsContainerName, settings.Name, "IdentityModel-Encryption-Certificates")); private static DirectoryInfo GetSigningCertificateDirectory(ShellOptions options, ShellSettings settings) => Directory.CreateDirectory(Path.Combine( options.ShellsApplicationDataPath, options.ShellsContainerName, settings.Name, "IdentityModel-Signing-Certificates")); private async Task<ImmutableArray<(string path, X509Certificate2 certificate)>> GetCertificatesAsync(DirectoryInfo directory) { if (!directory.Exists) { return ImmutableArray.Create<(string, X509Certificate2)>(); } var certificates = ImmutableArray.CreateBuilder<(string, X509Certificate2)>(); foreach (var file in directory.EnumerateFiles("*.pfx", SearchOption.TopDirectoryOnly)) { try { // Only add the certificate if it's still valid. var certificate = await GetCertificateAsync(file.FullName); if (certificate.NotBefore <= DateTime.Now && certificate.NotAfter > DateTime.Now) { certificates.Add((file.FullName, certificate)); } } catch (Exception exception) { _logger.LogWarning(exception, "An error occurred while trying to extract a X.509 certificate."); continue; } } return certificates.ToImmutable(); async Task<string> GetPasswordAsync(string path) { using var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); using var reader = new StreamReader(stream); return _dataProtector.Unprotect(await reader.ReadToEndAsync()); } async Task<X509Certificate2> GetCertificateAsync(string path) { // Extract the certificate password from the separate .pwd file. var password = await GetPasswordAsync(Path.ChangeExtension(path, ".pwd")); try { // Note: ephemeral key sets are not supported on non-Windows platforms. var flags = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? X509KeyStorageFlags.EphemeralKeySet : X509KeyStorageFlags.MachineKeySet; return new X509Certificate2(path, password, flags); } // Some cloud platforms (e.g Azure App Service/Antares) are known to fail to import .pfx files if the // private key is not persisted or marked as exportable. To ensure X.509 certificates can be correctly // read on these platforms, a second pass is made by specifying the PersistKeySet and Exportable flags. // For more information, visit https://github.com/OrchardCMS/OrchardCore/issues/3222. catch (CryptographicException exception) { _logger.LogDebug(exception, "A first-chance exception occurred while trying to extract " + "a X.509 certificate with the default key storage options."); return new X509Certificate2(path, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); } // Don't swallow exceptions thrown from the catch handler to ensure unrecoverable exceptions // (e.g caused by malformed X.509 certificates or invalid password) are correctly logged. } } private X509Certificate2 GenerateEncryptionCertificate(ShellSettings settings) { var algorithm = GenerateRsaSecurityKey(size: 2048); var certificate = GenerateCertificate(X509KeyUsageFlags.KeyEncipherment, algorithm, settings); // Note: setting the friendly name is not supported on Unix machines (including Linux and macOS). // To ensure an exception is not thrown by the property setter, an OS runtime check is used here. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { certificate.FriendlyName = "OrchardCore OpenID Server Encryption Certificate"; } return certificate; } private static X509Certificate2 GenerateSigningCertificate(ShellSettings settings) { var algorithm = GenerateRsaSecurityKey(size: 2048); var certificate = GenerateCertificate(X509KeyUsageFlags.DigitalSignature, algorithm, settings); // Note: setting the friendly name is not supported on Unix machines (including Linux and macOS). // To ensure an exception is not thrown by the property setter, an OS runtime check is used here. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { certificate.FriendlyName = "OrchardCore OpenID Server Signing Certificate"; } return certificate; } private static X509Certificate2 GenerateCertificate(X509KeyUsageFlags type, RSA algorithm, ShellSettings settings) { var subject = GetSubjectName(); // Note: ensure the digitalSignature bit is added to the certificate, so that no validation error // is returned to clients that fully validate the certificates chain and their X.509 key usages. var request = new CertificateRequest(subject, algorithm, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509KeyUsageExtension(type, critical: true)); return request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddMonths(3)); X500DistinguishedName GetSubjectName() { try { return new X500DistinguishedName("CN=" + (settings.RequestUrlHost ?? "localhost")); } catch { return new X500DistinguishedName("CN=localhost"); } } } private static RSA GenerateRsaSecurityKey(int size) { // By default, the default RSA implementation used by .NET Core relies on the newest Windows CNG APIs. // Unfortunately, when a new key is generated using the default RSA.Create() method, it is not bound // to the machine account, which may cause security exceptions when running Orchard on IIS using a // virtual application pool identity or without the profile loading feature enabled (off by default). // To ensure a RSA key can be generated flawlessly, it is manually created using the managed CNG APIs. // For more information, visit https://github.com/openiddict/openiddict-core/issues/204. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Warning: ensure a null key name is specified to ensure the RSA key is not persisted by CNG. var key = CngKey.Create(CngAlgorithm.Rsa, keyName: null, new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport, KeyCreationOptions = CngKeyCreationOptions.MachineKey, Parameters = { new CngProperty("Length", BitConverter.GetBytes(size), CngPropertyOptions.None) } }); return new RSACng(key); } return RSA.Create(size); } private async Task PersistCertificateAsync(DirectoryInfo directory, X509Certificate2 certificate) { var password = GeneratePassword(); var path = Path.Combine(directory.FullName, Guid.NewGuid().ToString()); await File.WriteAllBytesAsync(Path.ChangeExtension(path, ".pfx"), certificate.Export(X509ContentType.Pfx, password)); await File.WriteAllTextAsync(Path.ChangeExtension(path, ".pwd"), _dataProtector.Protect(password)); static string GeneratePassword() { Span<byte> data = stackalloc byte[256 / 8]; RandomNumberGenerator.Fill(data); return Convert.ToBase64String(data, Base64FormattingOptions.None); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using mshtml; using OpenLiveWriter.Mshtml; namespace OpenLiveWriter.SpellChecker { public class SortedMarkupRangeList { private readonly SortedList<IMarkupPointerRaw, MarkupRange> words = new SortedList<IMarkupPointerRaw, MarkupRange>(new MarkupPointerComparer()); public void Add(MarkupRange range) { MarkupRange newRange = range.Clone(); newRange.Start.Cling = false; newRange.End.Cling = false; newRange.Start.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right; newRange.End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Left; // Select just the inner-most text so that it is easier to compare to other MarkupRanges. newRange.SelectInner(); try { words.Add(newRange.Start.PointerRaw, newRange); } catch (ArgumentException ex) { Trace.Fail(ex.ToString()); } } public bool Contains(MarkupRange testRange) { // Select just the inner-most text to normalize the MarkupRange before comparing it. testRange.SelectInner(); int pos = BinarySearch(words.Keys, testRange.Start.PointerRaw, new MarkupPointerComparer()); if (pos >= 0) { if (words.Values[pos].End.IsLeftOf(testRange.End)) { Debug.Fail("testRange partially overlaps with range"); try { Debug.WriteLine("testRange: [" + testRange.Text + "]"); Debug.WriteLine("thisRange: [" + words.Values[pos].Text + "]"); } catch (Exception e) { Debug.WriteLine(e.ToString()); } } return true; } pos = (~pos)-1; if (pos < 0) return false; if (words.Values[pos].End.IsRightOf(testRange.Start)) { if (words.Values[pos].End.IsLeftOf(testRange.End)) { #if DEBUG MarkupRange temp = testRange.Clone(); temp.Start.MoveToPointer(words.Values[pos].End); if ((temp.Text ?? "").Trim().Length > 0) { Debug.Fail("testRange partially overlaps with range"); try { Debug.WriteLine("testRange: [" + testRange.Text + "]"); Debug.WriteLine("thisRange: [" + words.Values[pos].Text + "]"); Debug.WriteLine("overlap: [" + temp.Text + "]"); } catch (Exception e) { Debug.WriteLine(e.ToString()); } } #endif } return true; } return false; } public void ClearRange(MarkupRange clear) { if (words.Count == 0) return; // Just being defensive here if (!clear.Positioned) return; // Debug.WriteLine(string.Format("ClearRange:\r\n{0}\r\n{1}", clear.Start.PositionTextDetail, clear.End.PositionTextDetail)); /* * Start from the first range in the list where the start is left of * the Clear range's end. Take a look at each range until you get to * one where the range's end is left of the Clear range's start. */ int idx = BinarySearch(words.Keys, clear.Start.PointerRaw, new MarkupPointerComparer()); if (idx < 0) { idx = ~idx; idx--; idx = Math.Max(0, idx); } for (; idx < words.Count; idx++) { MarkupRange range = words.Values[idx]; // Debug.WriteLine("Testing range: " + range.Text); if (!range.Positioned) { // Debug.WriteLine("ClearRange: Removing unpositioned word"); words.RemoveAt(idx--); } else if (clear.End.IsLeftOfOrEqualTo(range.Start)) { // Debug.WriteLine("We've gone far enough--all done"); return; } else if (clear.InRange(range)) { // Debug.WriteLine("ClearRange: Removing contained range"); words.RemoveAt(idx--); } else if (range.InRange(clear)) { // Debug.WriteLine("ClearRange: Splitting range"); MarkupRange trailingRange = range.Clone(); trailingRange.Start.MoveToPointer(clear.End); range.End.MoveToPointer(clear.Start); if (range.IsEmpty()) words.RemoveAt(idx--); if (!trailingRange.IsEmpty()) Add(trailingRange); } else if (range.InRange(clear.End, false)) { // Debug.WriteLine("ClearRange: Partial overlap, trimming from start of range"); words.RemoveAt(idx--); range.Start.MoveToPointer(clear.End); if (!range.IsEmpty()) Add(range); } else if (range.InRange(clear.Start, false)) { // Debug.WriteLine("ClearRange: Partial overlap, trimming from end of range"); range.End.MoveToPointer(clear.End); if (range.IsEmpty()) words.RemoveAt(idx--); } } // Debug.WriteLine("ClearRange: Remaining words in ignore list: " + words.Count); } /// <summary> /// Returns true if a word range is in this list that contains this markup pointer. /// </summary> public bool Contains(MarkupPointer p) { if (words.Count == 0) return false; // Just being defensive if (!p.Positioned) return false; int idx = BinarySearch(words.Keys, p.PointerRaw, new MarkupPointerComparer()); if (idx >= 0) return true; idx = ~idx; // really this could be "if (idx == words.Count)"--it's to handle the case // where p is larger than the values in the list while (idx >= words.Count) idx--; for (; idx >= 0; idx--) { MarkupRange wordRange = words.Values[idx]; if (wordRange.InRange(p)) return true; if (wordRange.End.IsLeftOf(p)) break; } return false; } /// <summary> /// Does a binary search. Very similar to System.Array.BinarySearch(). /// </summary> /// <returns> /// The index of the specified value in the specified array, if value is found. /// If value is not found and value is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If value is not found and value is /// greater than any of the elements in array, a negative number which is the /// bitwise complement of (the index of the last element plus 1). /// </returns> public static int BinarySearch<T>(IList<T> list, T value, IComparer<T> comparer) { int min = 0; int max = list.Count; while (min < max) { int mid = min + ((max - min)/2); int result = comparer.Compare(value, list[mid]); // found it if (result == 0) return mid; if (result < 0) max = mid; else min = mid + 1; } return ~min; } public void Clear() { words.Clear(); } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Windows.Controls; using Dynamo.Controls; using Dynamo.Models; using Dynamo.Wpf; using ProtoCore.AST.AssociativeAST; using Kodestruct.Common.CalculationLogger; using Kodestruct.Dynamo.Common; using Dynamo.Nodes; using System.Windows.Input; using System.Windows; using System.Xml; using Kodestruct.Dynamo.Common.Infra.TreeItems; using Kodestruct.Dynamo.UI.Views.Analysis.Beam.Flexure; using GalaSoft.MvvmLight.CommandWpf; using Kodestruct.Dynamo.UI.Common.TreeItems; using Dynamo.Graph; using Dynamo.Graph.Nodes; namespace Kodestruct.Analysis.Beam.Flexure { /// <summary> ///Selection of beam load and boundary condition case for deflection calculation /// </summary> [NodeName("Beam deflection case selection")] [NodeCategory("Kodestruct.Analysis.Beam.Flexure")] [NodeDescription("Selection of beam load and boundary condition case for deflection calculation")] [IsDesignScriptCompatible] public class BeamDeflectionCaseSelection : UiNodeBase { public BeamDeflectionCaseSelection() { ReportEntry = ""; BeamDeflectionCaseId = "C1B_1"; BeamForcesCaseDescription = "Simply supported. Uniform load on full span. Uniformly distributed load"; //OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)")); OutPortData.Add(new PortData("BeamDeflectionCaseId", "Case ID used in calculation of the beam deflection")); RegisterAllPorts(); //PropertyChanged += NodePropertyChanged; } /// <summary> /// Gets the type of this class, to be used in base class for reflection /// </summary> protected override Type GetModelType() { return GetType(); } #region Properties #region InputProperties #endregion #region OutputProperties #region BeamDeflectionCaseIdProperty /// <summary> /// BeamDeflectionCaseId property /// </summary> /// <value>Case ID used in calculation of the beam forces</value> public string _BeamDeflectionCaseId; public string BeamDeflectionCaseId { get { return _BeamDeflectionCaseId; } set { _BeamDeflectionCaseId = value; RaisePropertyChanged("BeamDeflectionCaseId"); OnNodeModified(true); } } #endregion #region BeamForcesCaseDescription Property private string _BeamForcesCaseDescription; public string BeamForcesCaseDescription { get { return _BeamForcesCaseDescription; } set { _BeamForcesCaseDescription = value; RaisePropertyChanged("BeamForcesCaseDescription"); } } #endregion #region ReportEntryProperty /// <summary> /// log property /// </summary> /// <value>Calculation entries that can be converted into a report.</value> public string reportEntry; public string ReportEntry { get { return reportEntry; } set { reportEntry = value; RaisePropertyChanged("ReportEntry"); OnNodeModified(true); } } #endregion #endregion #endregion #region Serialization /// <summary> ///Saves property values to be retained when opening the node /// </summary> protected override void SerializeCore(XmlElement nodeElement, SaveContext context) { base.SerializeCore(nodeElement, context); nodeElement.SetAttribute("BeamDeflectionCaseId", BeamDeflectionCaseId); } /// <summary> ///Retrieved property values when opening the node /// </summary> protected override void DeserializeCore(XmlElement nodeElement, SaveContext context) { base.DeserializeCore(nodeElement, context); var attrib = nodeElement.Attributes["BeamDeflectionCaseId"]; if (attrib == null) return; BeamDeflectionCaseId = attrib.Value; SetCaseDescription(); } private void SetCaseDescription() { Uri uri = new Uri("pack://application:,,,/KodestructDynamoUI;component/Views/Analysis/Beam/Flexure/BeamForceCaseTreeData.xml"); XmlTreeHelper treeHelper = new XmlTreeHelper(); treeHelper.ExamineXmlTreeFile(uri, new EvaluateXmlNodeDelegate(FindCaseDescription)); } private void FindCaseDescription(XmlNode node) { if (null != node.Attributes["Id"]) { if (node.Attributes["Id"].Value == BeamDeflectionCaseId) { BeamForcesCaseDescription = node.Attributes["Description"].Value; } } } public void UpdateSelectionEvents() { if (TreeViewControl != null) { TreeViewControl.SelectedItemChanged += OnTreeViewSelectionChanged; } } private void OnTreeViewSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { OnSelectedItemChanged(e.NewValue); } #endregion #region TreeView elements public TreeView TreeViewControl { get; set; } private ICommand selectedItemChanged; public ICommand SelectedItemChanged { get { selectedItemChanged = new RelayCommand<object>((i) => { OnSelectedItemChanged(i); }); return selectedItemChanged; } } public void DisplayComponentUI(XTreeItem selectedComponent) { } private XTreeItem selectedItem; public XTreeItem SelectedItem { get { return selectedItem; } set { selectedItem = value; } } private void OnSelectedItemChanged(object i) { XmlElement item = i as XmlElement; XTreeItem xtreeItem = new XTreeItem() { Header = item.GetAttribute("Header"), Description = item.GetAttribute("Description"), Id = item.GetAttribute("Id"), ResourcePath = item.GetAttribute("ResourcePath"), Tag = item.GetAttribute("Tag"), TemplateName = item.GetAttribute("TemplateName") }; if (item != null) { string id = xtreeItem.Id; if (id != "X") { BeamDeflectionCaseId = xtreeItem.Id; SelectedItem = xtreeItem; BeamForcesCaseDescription = xtreeItem.Description; } } } #endregion /// <summary> ///Customization of WPF view in Dynamo UI /// </summary> public class BeamDeflectionCaseSelectionViewCustomization : UiNodeBaseViewCustomization, INodeViewCustomization<BeamDeflectionCaseSelection> { public void CustomizeView(BeamDeflectionCaseSelection model, NodeView nodeView) { base.CustomizeView(model, nodeView); BeamDeflectionCaseView control = new BeamDeflectionCaseView(); control.DataContext = model; //remove this part if control does not contain tree TreeView tv = control.FindName("selectionTree") as TreeView; if (tv!=null) { model.TreeViewControl = tv; model.UpdateSelectionEvents(); } nodeView.inputGrid.Children.Add(control); base.CustomizeView(model, nodeView); } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace Elmah { #region Imports using System; using System.Collections; using System.Security; using System.Web; #endregion internal sealed class HttpModuleRegistry { private static Hashtable _moduleListByApp; private static readonly object _lock = new object(); public static bool RegisterInPartialTrust(HttpApplication application, IHttpModule module) { if (application == null) throw new ArgumentNullException("application"); if (module == null) throw new ArgumentNullException("module"); if (IsHighlyTrusted()) return false; lock (_lock) { // // On-demand allocate a map of modules per application. // if (_moduleListByApp == null) _moduleListByApp = new Hashtable(); // // Get the list of modules for the application. If this is // the first registration for the supplied application object // then setup a new and empty list. // IList moduleList = (IList) _moduleListByApp[application]; if (moduleList == null) { moduleList = new ArrayList(4); _moduleListByApp.Add(application, moduleList); } else if (moduleList.Contains(module)) throw new ApplicationException("Duplicate module registration."); // // Add the module to list of registered modules for the // given application object. // moduleList.Add(module); } // // Setup a closure to automatically unregister the module // when the application fires its Disposed event. // Housekeeper housekeeper = new Housekeeper(module); application.Disposed += new EventHandler(housekeeper.OnApplicationDisposed); return true; } private static bool UnregisterInPartialTrust(HttpApplication application, IHttpModule module) { Debug.Assert(application != null); Debug.Assert(module != null); if (module == null) throw new ArgumentNullException("module"); if (IsHighlyTrusted()) return false; lock (_lock) { // // Get the module list for the given application object. // if (_moduleListByApp == null) return false; IList moduleList = (IList) _moduleListByApp[application]; if (moduleList == null) return false; // // Remove the module from the list if it's in there. // int index = moduleList.IndexOf(module); if (index < 0) return false; moduleList.RemoveAt(index); // // If the list is empty then remove the application entry. // If this results in the entire map becoming empty then // release it. // if (moduleList.Count == 0) { _moduleListByApp.Remove(application); if (_moduleListByApp.Count == 0) _moduleListByApp = null; } } return true; } public static ICollection GetModules(HttpApplication application) { if (application == null) throw new ArgumentNullException("application"); try { IHttpModule[] modules = new IHttpModule[application.Modules.Count]; application.Modules.CopyTo(modules, 0); return modules; } catch (SecurityException) { // // Pass through because probably this is a partially trusted // environment that does not have access to the modules // collection over HttpApplication so we have to resort // to our own devices... // } lock (_lock) { if (_moduleListByApp == null) return new IHttpModule[0]; IList moduleList = (IList) _moduleListByApp[application]; if (moduleList == null) return new IHttpModule[0]; IHttpModule[] modules = new IHttpModule[moduleList.Count]; moduleList.CopyTo(modules, 0); return modules; } } private static bool IsHighlyTrusted() { #if NET_1_0 // // ASP.NET 1.0 applications always required and ran under full // trust so we just return true here. // return true; #else try { AspNetHostingPermission permission = new AspNetHostingPermission(AspNetHostingPermissionLevel.High); permission.Demand(); return true; } catch (SecurityException) { return false; } #endif } private HttpModuleRegistry() { throw new NotSupportedException(); } internal sealed class Housekeeper { private readonly IHttpModule _module; public Housekeeper(IHttpModule module) { _module = module; } public void OnApplicationDisposed(object sender, EventArgs e) { UnregisterInPartialTrust((HttpApplication) sender, _module); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma warning disable 618 namespace Apache.Ignite.Core.Tests { using System; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using NUnit.Framework; /// <summary> /// Tests grid exceptions propagation. /// </summary> public class ExceptionsTest { /// <summary> /// Before test. /// </summary> [SetUp] public void SetUp() { TestUtils.KillProcesses(); } /// <summary> /// After test. /// </summary> [TearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Tests exceptions. /// </summary> [Test] public void TestExceptions() { var grid = StartGrid(); Assert.Throws<ArgumentException>(() => grid.GetCache<object, object>("invalidCacheName")); var e = Assert.Throws<ClusterGroupEmptyException>(() => grid.GetCluster().ForRemotes().GetMetrics()); Assert.IsTrue(e.InnerException.Message.StartsWith( "class org.apache.ignite.cluster.ClusterGroupEmptyException: Cluster group is empty.")); grid.Dispose(); Assert.Throws<InvalidOperationException>(() => grid.GetCache<object, object>("cache1")); } /// <summary> /// Tests CachePartialUpdateException keys propagation. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestPartialUpdateException() { // Primitive type TestPartialUpdateException(false, (x, g) => x); // User type TestPartialUpdateException(false, (x, g) => new BinarizableEntry(x)); } /// <summary> /// Tests CachePartialUpdateException keys propagation in binary mode. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestPartialUpdateExceptionBinarizable() { // User type TestPartialUpdateException(false, (x, g) => g.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry(x))); } /// <summary> /// Tests CachePartialUpdateException serialization. /// </summary> [Test] public void TestPartialUpdateExceptionSerialization() { // Inner exception TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg", new IgniteException("Inner msg"))); // Primitive keys TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg", new object[] {1, 2, 3})); // User type keys TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg", new object[] { new SerializableEntry(1), new SerializableEntry(2), new SerializableEntry(3) })); } /// <summary> /// Tests CachePartialUpdateException serialization. /// </summary> private static void TestPartialUpdateExceptionSerialization(Exception ex) { var formatter = new BinaryFormatter(); var stream = new MemoryStream(); formatter.Serialize(stream, ex); stream.Seek(0, SeekOrigin.Begin); var ex0 = (Exception) formatter.Deserialize(stream); var updateEx = ((CachePartialUpdateException) ex); try { Assert.AreEqual(updateEx.GetFailedKeys<object>(), ((CachePartialUpdateException) ex0).GetFailedKeys<object>()); } catch (Exception e) { if (typeof(IgniteException) != e.GetType()) throw; } while (ex != null && ex0 != null) { Assert.AreEqual(ex0.GetType(), ex.GetType()); Assert.AreEqual(ex.Message, ex0.Message); ex = ex.InnerException; ex0 = ex0.InnerException; } Assert.AreEqual(ex, ex0); } /// <summary> /// Tests CachePartialUpdateException keys propagation. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestPartialUpdateExceptionAsync() { // Primitive type TestPartialUpdateException(true, (x, g) => x); // User type TestPartialUpdateException(true, (x, g) => new BinarizableEntry(x)); } /// <summary> /// Tests CachePartialUpdateException keys propagation in binary mode. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestPartialUpdateExceptionAsyncBinarizable() { TestPartialUpdateException(true, (x, g) => g.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry(x))); } /// <summary> /// Tests that invalid spring URL results in a meaningful exception. /// </summary> [Test] public void TestInvalidSpringUrl() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = "z:\\invalid.xml" }; var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.IsTrue(ex.ToString().Contains("Spring XML configuration path is invalid: z:\\invalid.xml")); } /// <summary> /// Tests that invalid configuration parameter results in a meaningful exception. /// </summary> [Test] public void TestInvalidConfig() { var disco = TestUtils.GetStaticDiscovery(); disco.SocketTimeout = TimeSpan.FromSeconds(-1); // set invalid timeout var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { DiscoverySpi = disco }; var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.IsTrue(ex.ToString().Contains("SPI parameter failed condition check: sockTimeout > 0")); } /// <summary> /// Tests CachePartialUpdateException keys propagation. /// </summary> private static void TestPartialUpdateException<TK>(bool async, Func<int, IIgnite, TK> keyFunc) { using (var grid = StartGrid()) { var cache = grid.GetCache<TK, int>("partitioned_atomic").WithNoRetries(); if (typeof (TK) == typeof (IBinaryObject)) cache = cache.WithKeepBinary<TK, int>(); // Do cache puts in parallel var putTask = Task.Factory.StartNew(() => { try { // Do a lot of puts so that one fails during Ignite stop for (var i = 0; i < 1000000; i++) { // ReSharper disable once AccessToDisposedClosure // ReSharper disable once AccessToModifiedClosure var dict = Enumerable.Range(1, 100).ToDictionary(k => keyFunc(k, grid), k => i); if (async) cache.PutAllAsync(dict).Wait(); else cache.PutAll(dict); } } catch (AggregateException ex) { CheckPartialUpdateException<TK>((CachePartialUpdateException) ex.InnerException); return; } catch (CachePartialUpdateException ex) { CheckPartialUpdateException<TK>(ex); return; } Assert.Fail("CachePartialUpdateException has not been thrown."); }); while (true) { Thread.Sleep(1000); Ignition.Stop("grid_2", true); StartGrid("grid_2"); Thread.Sleep(1000); if (putTask.Exception != null) throw putTask.Exception; if (putTask.IsCompleted) return; } } } /// <summary> /// Checks the partial update exception. /// </summary> private static void CheckPartialUpdateException<TK>(CachePartialUpdateException ex) { var failedKeys = ex.GetFailedKeys<TK>(); Assert.IsTrue(failedKeys.Any()); var failedKeysObj = ex.GetFailedKeys<object>(); Assert.IsTrue(failedKeysObj.Any()); } /// <summary> /// Starts the grid. /// </summary> private static IIgnite StartGrid(string gridName = null) { return Ignition.Start(new IgniteConfiguration { SpringConfigUrl = "config\\native-client-test-cache.xml", JvmOptions = TestUtils.TestJavaOptions(), JvmClasspath = TestUtils.CreateTestClasspath(), GridName = gridName, BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new[] { new BinaryTypeConfiguration(typeof (BinarizableEntry)) } } }); } /// <summary> /// Binarizable entry. /// </summary> private class BinarizableEntry { /** Value. */ private readonly int _val; /** <inheritDot /> */ public override int GetHashCode() { return _val; } /// <summary> /// Constructor. /// </summary> /// <param name="val">Value.</param> public BinarizableEntry(int val) { _val = val; } /** <inheritDoc /> */ public override bool Equals(object obj) { return obj is BinarizableEntry && ((BinarizableEntry)obj)._val == _val; } } /// <summary> /// Serializable entry. /// </summary> [Serializable] private class SerializableEntry { /** Value. */ private readonly int _val; /** <inheritDot /> */ public override int GetHashCode() { return _val; } /// <summary> /// Constructor. /// </summary> /// <param name="val">Value.</param> public SerializableEntry(int val) { _val = val; } /** <inheritDoc /> */ public override bool Equals(object obj) { return obj is SerializableEntry && ((SerializableEntry)obj)._val == _val; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using OpenMetaverse; using OpenSim.Region.PhysicsModules.SharedBase; using OpenSim.Region.PhysicsModule.Meshing; public class Vertex : IComparable<Vertex> { Vector3 vector; public float X { get { return vector.X; } set { vector.X = value; } } public float Y { get { return vector.Y; } set { vector.Y = value; } } public float Z { get { return vector.Z; } set { vector.Z = value; } } public Vertex(float x, float y, float z) { vector.X = x; vector.Y = y; vector.Z = z; } public Vertex normalize() { float tlength = vector.Length(); if (tlength != 0f) { float mul = 1.0f / tlength; return new Vertex(vector.X * mul, vector.Y * mul, vector.Z * mul); } else { return new Vertex(0f, 0f, 0f); } } public Vertex cross(Vertex v) { return new Vertex(vector.Y * v.Z - vector.Z * v.Y, vector.Z * v.X - vector.X * v.Z, vector.X * v.Y - vector.Y * v.X); } // disable warning: mono compiler moans about overloading // operators hiding base operator but should not according to C# // language spec #pragma warning disable 0108 public static Vertex operator *(Vertex v, Quaternion q) { // From http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/transforms/ Vertex v2 = new Vertex(0f, 0f, 0f); v2.X = q.W * q.W * v.X + 2f * q.Y * q.W * v.Z - 2f * q.Z * q.W * v.Y + q.X * q.X * v.X + 2f * q.Y * q.X * v.Y + 2f * q.Z * q.X * v.Z - q.Z * q.Z * v.X - q.Y * q.Y * v.X; v2.Y = 2f * q.X * q.Y * v.X + q.Y * q.Y * v.Y + 2f * q.Z * q.Y * v.Z + 2f * q.W * q.Z * v.X - q.Z * q.Z * v.Y + q.W * q.W * v.Y - 2f * q.X * q.W * v.Z - q.X * q.X * v.Y; v2.Z = 2f * q.X * q.Z * v.X + 2f * q.Y * q.Z * v.Y + q.Z * q.Z * v.Z - 2f * q.W * q.Y * v.X - q.Y * q.Y * v.Z + 2f * q.W * q.X * v.Y - q.X * q.X * v.Z + q.W * q.W * v.Z; return v2; } public static Vertex operator +(Vertex v1, Vertex v2) { return new Vertex(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z); } public static Vertex operator -(Vertex v1, Vertex v2) { return new Vertex(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z); } public static Vertex operator *(Vertex v1, Vertex v2) { return new Vertex(v1.X * v2.X, v1.Y * v2.Y, v1.Z * v2.Z); } public static Vertex operator +(Vertex v1, float am) { v1.X += am; v1.Y += am; v1.Z += am; return v1; } public static Vertex operator -(Vertex v1, float am) { v1.X -= am; v1.Y -= am; v1.Z -= am; return v1; } public static Vertex operator *(Vertex v1, float am) { v1.X *= am; v1.Y *= am; v1.Z *= am; return v1; } public static Vertex operator /(Vertex v1, float am) { if (am == 0f) { return new Vertex(0f,0f,0f); } float mul = 1.0f / am; v1.X *= mul; v1.Y *= mul; v1.Z *= mul; return v1; } #pragma warning restore 0108 public float dot(Vertex v) { return X * v.X + Y * v.Y + Z * v.Z; } public Vertex(Vector3 v) { vector = v; } public Vertex Clone() { return new Vertex(X, Y, Z); } public static Vertex FromAngle(double angle) { return new Vertex((float) Math.Cos(angle), (float) Math.Sin(angle), 0.0f); } public float Length() { return vector.Length(); } public virtual bool Equals(Vertex v, float tolerance) { Vertex diff = this - v; float d = diff.Length(); if (d < tolerance) return true; return false; } public int CompareTo(Vertex other) { if (X < other.X) return -1; if (X > other.X) return 1; if (Y < other.Y) return -1; if (Y > other.Y) return 1; if (Z < other.Z) return -1; if (Z > other.Z) return 1; return 0; } public static bool operator >(Vertex me, Vertex other) { return me.CompareTo(other) > 0; } public static bool operator <(Vertex me, Vertex other) { return me.CompareTo(other) < 0; } public String ToRaw() { // Why this stuff with the number formatter? // Well, the raw format uses the english/US notation of numbers // where the "," separates groups of 1000 while the "." marks the border between 1 and 10E-1. // The german notation uses these characters exactly vice versa! // The Float.ToString() routine is a localized one, giving different results depending on the country // settings your machine works with. Unusable for a machine readable file format :-( NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; nfi.NumberDecimalDigits = 3; String s1 = X.ToString("N2", nfi) + " " + Y.ToString("N2", nfi) + " " + Z.ToString("N2", nfi); return s1; } } public class Triangle { public Vertex v1; public Vertex v2; public Vertex v3; private float radius_square; private float cx; private float cy; public Triangle(Vertex _v1, Vertex _v2, Vertex _v3) { v1 = _v1; v2 = _v2; v3 = _v3; CalcCircle(); } public bool isInCircle(float x, float y) { float dx, dy; float dd; dx = x - cx; dy = y - cy; dd = dx*dx + dy*dy; if (dd < radius_square) return true; else return false; } public bool isDegraded() { // This means, the vertices of this triangle are somewhat strange. // They either line up or at least two of them are identical return (radius_square == 0.0); } private void CalcCircle() { // Calculate the center and the radius of a circle given by three points p1, p2, p3 // It is assumed, that the triangles vertices are already set correctly double p1x, p2x, p1y, p2y, p3x, p3y; // Deviation of this routine: // A circle has the general equation (M-p)^2=r^2, where M and p are vectors // this gives us three equations f(p)=r^2, each for one point p1, p2, p3 // putting respectively two equations together gives two equations // f(p1)=f(p2) and f(p1)=f(p3) // bringing all constant terms to one side brings them to the form // M*v1=c1 resp.M*v2=c2 where v1=(p1-p2) and v2=(p1-p3) (still vectors) // and c1, c2 are scalars (Naming conventions like the variables below) // Now using the equations that are formed by the components of the vectors // and isolate Mx lets you make one equation that only holds My // The rest is straight forward and eaasy :-) // /* helping variables for temporary results */ double c1, c2; double v1x, v1y, v2x, v2y; double z, n; double rx, ry; // Readout the three points, the triangle consists of p1x = v1.X; p1y = v1.Y; p2x = v2.X; p2y = v2.Y; p3x = v3.X; p3y = v3.Y; /* calc helping values first */ c1 = (p1x*p1x + p1y*p1y - p2x*p2x - p2y*p2y)/2; c2 = (p1x*p1x + p1y*p1y - p3x*p3x - p3y*p3y)/2; v1x = p1x - p2x; v1y = p1y - p2y; v2x = p1x - p3x; v2y = p1y - p3y; z = (c1*v2x - c2*v1x); n = (v1y*v2x - v2y*v1x); if (n == 0.0) // This is no triangle, i.e there are (at least) two points at the same location { radius_square = 0.0f; return; } cy = (float) (z/n); if (v2x != 0.0) { cx = (float) ((c2 - v2y*cy)/v2x); } else if (v1x != 0.0) { cx = (float) ((c1 - v1y*cy)/v1x); } else { Debug.Assert(false, "Malformed triangle"); /* Both terms zero means nothing good */ } rx = (p1x - cx); ry = (p1y - cy); radius_square = (float) (rx*rx + ry*ry); } public override String ToString() { NumberFormatInfo nfi = new NumberFormatInfo(); nfi.CurrencyDecimalDigits = 2; nfi.CurrencyDecimalSeparator = "."; String s1 = "<" + v1.X.ToString(nfi) + "," + v1.Y.ToString(nfi) + "," + v1.Z.ToString(nfi) + ">"; String s2 = "<" + v2.X.ToString(nfi) + "," + v2.Y.ToString(nfi) + "," + v2.Z.ToString(nfi) + ">"; String s3 = "<" + v3.X.ToString(nfi) + "," + v3.Y.ToString(nfi) + "," + v3.Z.ToString(nfi) + ">"; return s1 + ";" + s2 + ";" + s3; } public Vector3 getNormal() { // Vertices // Vectors for edges Vector3 e1; Vector3 e2; e1 = new Vector3(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z); e2 = new Vector3(v1.X - v3.X, v1.Y - v3.Y, v1.Z - v3.Z); // Cross product for normal Vector3 n = Vector3.Cross(e1, e2); // Length float l = n.Length(); // Normalized "normal" n = n/l; return n; } public void invertNormal() { Vertex vt; vt = v1; v1 = v2; v2 = vt; } // Dumps a triangle in the "raw faces" format, blender can import. This is for visualisation and // debugging purposes public String ToStringRaw() { String output = v1.ToRaw() + " " + v2.ToRaw() + " " + v3.ToRaw(); return output; } }
// 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.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Threading; namespace System.ServiceModel { public abstract class ClientBase<TChannel> : ICommunicationObject, IDisposable where TChannel : class { private TChannel _channel; private object _syncRoot = new object(); private static AsyncCallback s_onAsyncCallCompleted = Fx.ThunkCallback(new AsyncCallback(OnAsyncCallCompleted)); protected ClientBase() { throw new PlatformNotSupportedException(SR.ConfigurationFilesNotSupported); } protected ClientBase(string endpointConfigurationName) { throw new PlatformNotSupportedException(SR.ConfigurationFilesNotSupported); } protected ClientBase(string endpointConfigurationName, string remoteAddress) { throw new PlatformNotSupportedException(SR.ConfigurationFilesNotSupported); } protected ClientBase(string endpointConfigurationName, EndpointAddress remoteAddress) { throw new PlatformNotSupportedException(SR.ConfigurationFilesNotSupported); } protected ClientBase(Binding binding, EndpointAddress remoteAddress) { if (binding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(binding)); } if (remoteAddress == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(remoteAddress)); } ChannelFactory = new ChannelFactory<TChannel>(binding, remoteAddress); ChannelFactory.TraceOpenAndClose = false; } protected ClientBase(ServiceEndpoint endpoint) { if (endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(endpoint)); } ChannelFactory = new ChannelFactory<TChannel>(endpoint); ChannelFactory.TraceOpenAndClose = false; } protected ClientBase(InstanceContext callbackInstance, Binding binding, EndpointAddress remoteAddress) { if (callbackInstance == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(callbackInstance)); } if (binding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(binding)); } if (remoteAddress == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(remoteAddress)); } ChannelFactory = new DuplexChannelFactory<TChannel>(callbackInstance, binding, remoteAddress); ChannelFactory.TraceOpenAndClose = false; } protected T GetDefaultValueForInitialization<T>() { return default(T); } private object ThisLock { get { return _syncRoot; } } protected TChannel Channel { get { // created on demand, so that Mort can modify .Endpoint before calling methods on the client if (_channel == null) { lock (ThisLock) { if (_channel == null) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityOpenClientBase, typeof(TChannel).FullName), ActivityType.OpenClient); } CreateChannelInternal(); } } } } return _channel; } } public ChannelFactory<TChannel> ChannelFactory { get; } public ClientCredentials ClientCredentials { get { return ChannelFactory.Credentials; } } public CommunicationState State { get { IChannel channel = (IChannel)_channel; if (channel != null) { return channel.State; } else { // we may have failed to create the channel under open, in which case we our factory wouldn't be open return ChannelFactory.State; } } } public IClientChannel InnerChannel { get { return (IClientChannel)Channel; } } public ServiceEndpoint Endpoint { get { return ChannelFactory.Endpoint; } } public void Open() { ((ICommunicationObject)this).Open(ChannelFactory.InternalOpenTimeout); } public void Abort() { IChannel channel = (IChannel)_channel; if (channel != null) { channel.Abort(); } ChannelFactory.Abort(); } public void Close() { ((ICommunicationObject)this).Close(ChannelFactory.InternalCloseTimeout); } private void CreateChannelInternal() { _channel = CreateChannel(); } protected virtual TChannel CreateChannel() { return ChannelFactory.CreateChannel(); } void IDisposable.Dispose() { Close(); } void ICommunicationObject.Open(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); ChannelFactory.Open(timeoutHelper.RemainingTime()); InnerChannel.Open(timeoutHelper.RemainingTime()); } void ICommunicationObject.Close(TimeSpan timeout) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityCloseClientBase, typeof(TChannel).FullName), ActivityType.Close); } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (_channel != null) { InnerChannel.Close(timeoutHelper.RemainingTime()); } ChannelFactory.Close(timeoutHelper.RemainingTime()); } } event EventHandler ICommunicationObject.Closed { add { InnerChannel.Closed += value; } remove { InnerChannel.Closed -= value; } } event EventHandler ICommunicationObject.Closing { add { InnerChannel.Closing += value; } remove { InnerChannel.Closing -= value; } } event EventHandler ICommunicationObject.Faulted { add { InnerChannel.Faulted += value; } remove { InnerChannel.Faulted -= value; } } event EventHandler ICommunicationObject.Opened { add { InnerChannel.Opened += value; } remove { InnerChannel.Opened -= value; } } event EventHandler ICommunicationObject.Opening { add { InnerChannel.Opening += value; } remove { InnerChannel.Opening -= value; } } IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state) { return ((ICommunicationObject)this).BeginClose(ChannelFactory.InternalCloseTimeout, callback, state); } IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedAsyncResult(timeout, callback, state, BeginChannelClose, EndChannelClose, BeginFactoryClose, EndFactoryClose); } void ICommunicationObject.EndClose(IAsyncResult result) { ChainedAsyncResult.End(result); } IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state) { return ((ICommunicationObject)this).BeginOpen(ChannelFactory.InternalOpenTimeout, callback, state); } IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedAsyncResult(timeout, callback, state, BeginFactoryOpen, EndFactoryOpen, BeginChannelOpen, EndChannelOpen); } void ICommunicationObject.EndOpen(IAsyncResult result) { ChainedAsyncResult.End(result); } //ChainedAsyncResult methods for opening and closing ChannelFactory<T> internal IAsyncResult BeginFactoryOpen(TimeSpan timeout, AsyncCallback callback, object state) { return ChannelFactory.BeginOpen(timeout, callback, state); } internal void EndFactoryOpen(IAsyncResult result) { ChannelFactory.EndOpen(result); } internal IAsyncResult BeginChannelOpen(TimeSpan timeout, AsyncCallback callback, object state) { return InnerChannel.BeginOpen(timeout, callback, state); } internal void EndChannelOpen(IAsyncResult result) { InnerChannel.EndOpen(result); } internal IAsyncResult BeginFactoryClose(TimeSpan timeout, AsyncCallback callback, object state) { return ChannelFactory.BeginClose(timeout, callback, state); } internal void EndFactoryClose(IAsyncResult result) { if (typeof(CompletedAsyncResult).IsAssignableFrom(result.GetType())) { CompletedAsyncResult.End(result); } else { ChannelFactory.EndClose(result); } } internal IAsyncResult BeginChannelClose(TimeSpan timeout, AsyncCallback callback, object state) { if (_channel != null) { return InnerChannel.BeginClose(timeout, callback, state); } else { return new CompletedAsyncResult(callback, state); } } internal void EndChannelClose(IAsyncResult result) { if (typeof(CompletedAsyncResult).IsAssignableFrom(result.GetType())) { CompletedAsyncResult.End(result); } else { InnerChannel.EndClose(result); } } // WARNING: changes in the signature/name of the following delegates must be applied to the // ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code. protected delegate IAsyncResult BeginOperationDelegate(object[] inValues, AsyncCallback asyncCallback, object state); protected delegate object[] EndOperationDelegate(IAsyncResult result); // WARNING: Any changes in the signature/name of the following type and its ctor must be applied to the // ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code. protected class InvokeAsyncCompletedEventArgs : AsyncCompletedEventArgs { internal InvokeAsyncCompletedEventArgs(object[] results, Exception error, bool cancelled, object userState) : base(error, cancelled, userState) { Results = results; } public object[] Results { get; } } // WARNING: Any changes in the signature/name of the following method ctor must be applied to the // ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code. protected void InvokeAsync(BeginOperationDelegate beginOperationDelegate, object[] inValues, EndOperationDelegate endOperationDelegate, SendOrPostCallback operationCompletedCallback, object userState) { if (beginOperationDelegate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(beginOperationDelegate)); } if (endOperationDelegate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(endOperationDelegate)); } AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(userState); AsyncOperationContext context = new AsyncOperationContext(asyncOperation, endOperationDelegate, operationCompletedCallback); Exception error = null; object[] results = null; IAsyncResult result = null; try { result = beginOperationDelegate(inValues, s_onAsyncCallCompleted, context); if (result.CompletedSynchronously) { results = endOperationDelegate(result); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } error = e; } if (error != null || result.CompletedSynchronously) /* result cannot be null if error == null */ { CompleteAsyncCall(context, results, error); } } private static void OnAsyncCallCompleted(IAsyncResult result) { if (result.CompletedSynchronously) { return; } AsyncOperationContext context = (AsyncOperationContext)result.AsyncState; Exception error = null; object[] results = null; try { results = context.EndDelegate(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } error = e; } CompleteAsyncCall(context, results, error); } private static void CompleteAsyncCall(AsyncOperationContext context, object[] results, Exception error) { if (context.CompletionCallback != null) { InvokeAsyncCompletedEventArgs e = new InvokeAsyncCompletedEventArgs(results, error, false, context.AsyncOperation.UserSuppliedState); context.AsyncOperation.PostOperationCompleted(context.CompletionCallback, e); } else { context.AsyncOperation.OperationCompleted(); } } protected class AsyncOperationContext { private SendOrPostCallback _completionCallback; internal AsyncOperationContext(AsyncOperation asyncOperation, EndOperationDelegate endDelegate, SendOrPostCallback completionCallback) { AsyncOperation = asyncOperation; EndDelegate = endDelegate; _completionCallback = completionCallback; } internal AsyncOperation AsyncOperation { get; } internal EndOperationDelegate EndDelegate { get; } internal SendOrPostCallback CompletionCallback { get { return _completionCallback; } } } protected class ChannelBase<T> : IClientChannel, IOutputChannel, IRequestChannel, IChannelBaseProxy where T : class { private ServiceChannel _channel; private ImmutableClientRuntime _runtime; protected ChannelBase(ClientBase<T> client) { if (client.Endpoint.Address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryEndpointAddressUri)); } ChannelFactory<T> cf = client.ChannelFactory; cf.EnsureOpened(); // to prevent the NullReferenceException that is thrown if the ChannelFactory is not open when cf.ServiceChannelFactory is accessed. _channel = cf.ServiceChannelFactory.CreateServiceChannel(client.Endpoint.Address, client.Endpoint.Address.Uri); _channel.InstanceContext = cf.CallbackInstance; _runtime = _channel.ClientRuntime.GetRuntime(); } protected IAsyncResult BeginInvoke(string methodName, object[] args, AsyncCallback callback, object state) { object[] inArgs = new object[args.Length + 2]; Array.Copy(args, inArgs, args.Length); inArgs[inArgs.Length - 2] = callback; inArgs[inArgs.Length - 1] = state; MethodCall methodCall = new MethodCall(inArgs); ProxyOperationRuntime op = GetOperationByName(methodName); object[] ins = op.MapAsyncBeginInputs(methodCall, out callback, out state); return _channel.BeginCall(op.Action, op.IsOneWay, op, ins, callback, state); } protected object EndInvoke(string methodName, object[] args, IAsyncResult result) { object[] inArgs = new object[args.Length + 1]; Array.Copy(args, inArgs, args.Length); inArgs[inArgs.Length - 1] = result; MethodCall methodCall = new MethodCall(inArgs); ProxyOperationRuntime op = GetOperationByName(methodName); object[] outs; op.MapAsyncEndInputs(methodCall, out result, out outs); object ret = _channel.EndCall(op.Action, outs, result); object[] retArgs = op.MapAsyncOutputs(methodCall, outs, ref ret); if (retArgs != null) { Fx.Assert(retArgs.Length == inArgs.Length, "retArgs.Length should be equal to inArgs.Length"); Array.Copy(retArgs, args, args.Length); } return ret; } private ProxyOperationRuntime GetOperationByName(string methodName) { ProxyOperationRuntime op = _runtime.GetOperationByName(methodName); if (op == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SFxMethodNotSupported1, methodName))); } return op; } bool IClientChannel.AllowInitializationUI { get { return ((IClientChannel)_channel).AllowInitializationUI; } set { ((IClientChannel)_channel).AllowInitializationUI = value; } } bool IClientChannel.DidInteractiveInitialization { get { return ((IClientChannel)_channel).DidInteractiveInitialization; } } Uri IClientChannel.Via { get { return ((IClientChannel)_channel).Via; } } event EventHandler<UnknownMessageReceivedEventArgs> IClientChannel.UnknownMessageReceived { add { ((IClientChannel)_channel).UnknownMessageReceived += value; } remove { ((IClientChannel)_channel).UnknownMessageReceived -= value; } } void IClientChannel.DisplayInitializationUI() { ((IClientChannel)_channel).DisplayInitializationUI(); } IAsyncResult IClientChannel.BeginDisplayInitializationUI(AsyncCallback callback, object state) { return ((IClientChannel)_channel).BeginDisplayInitializationUI(callback, state); } void IClientChannel.EndDisplayInitializationUI(IAsyncResult result) { ((IClientChannel)_channel).EndDisplayInitializationUI(result); } bool IContextChannel.AllowOutputBatching { get { return ((IContextChannel)_channel).AllowOutputBatching; } set { ((IContextChannel)_channel).AllowOutputBatching = value; } } IInputSession IContextChannel.InputSession { get { return ((IContextChannel)_channel).InputSession; } } EndpointAddress IContextChannel.LocalAddress { get { return ((IContextChannel)_channel).LocalAddress; } } TimeSpan IContextChannel.OperationTimeout { get { return ((IContextChannel)_channel).OperationTimeout; } set { ((IContextChannel)_channel).OperationTimeout = value; } } IOutputSession IContextChannel.OutputSession { get { return ((IContextChannel)_channel).OutputSession; } } EndpointAddress IContextChannel.RemoteAddress { get { return ((IContextChannel)_channel).RemoteAddress; } } string IContextChannel.SessionId { get { return ((IContextChannel)_channel).SessionId; } } TProperty IChannel.GetProperty<TProperty>() { return ((IChannel)_channel).GetProperty<TProperty>(); } CommunicationState ICommunicationObject.State { get { return ((ICommunicationObject)_channel).State; } } event EventHandler ICommunicationObject.Closed { add { ((ICommunicationObject)_channel).Closed += value; } remove { ((ICommunicationObject)_channel).Closed -= value; } } event EventHandler ICommunicationObject.Closing { add { ((ICommunicationObject)_channel).Closing += value; } remove { ((ICommunicationObject)_channel).Closing -= value; } } event EventHandler ICommunicationObject.Faulted { add { ((ICommunicationObject)_channel).Faulted += value; } remove { ((ICommunicationObject)_channel).Faulted -= value; } } event EventHandler ICommunicationObject.Opened { add { ((ICommunicationObject)_channel).Opened += value; } remove { ((ICommunicationObject)_channel).Opened -= value; } } event EventHandler ICommunicationObject.Opening { add { ((ICommunicationObject)_channel).Opening += value; } remove { ((ICommunicationObject)_channel).Opening -= value; } } void ICommunicationObject.Abort() { ((ICommunicationObject)_channel).Abort(); } void ICommunicationObject.Close() { ((ICommunicationObject)_channel).Close(); } void ICommunicationObject.Close(TimeSpan timeout) { ((ICommunicationObject)_channel).Close(timeout); } IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state) { return ((ICommunicationObject)_channel).BeginClose(callback, state); } IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return ((ICommunicationObject)_channel).BeginClose(timeout, callback, state); } void ICommunicationObject.EndClose(IAsyncResult result) { ((ICommunicationObject)_channel).EndClose(result); } void ICommunicationObject.Open() { ((ICommunicationObject)_channel).Open(); } void ICommunicationObject.Open(TimeSpan timeout) { ((ICommunicationObject)_channel).Open(timeout); } IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state) { return ((ICommunicationObject)_channel).BeginOpen(callback, state); } IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return ((ICommunicationObject)_channel).BeginOpen(timeout, callback, state); } void ICommunicationObject.EndOpen(IAsyncResult result) { ((ICommunicationObject)_channel).EndOpen(result); } IExtensionCollection<IContextChannel> IExtensibleObject<IContextChannel>.Extensions { get { return ((IExtensibleObject<IContextChannel>)_channel).Extensions; } } void IDisposable.Dispose() { ((IDisposable)_channel).Dispose(); } Uri IOutputChannel.Via { get { return ((IOutputChannel)_channel).Via; } } EndpointAddress IOutputChannel.RemoteAddress { get { return ((IOutputChannel)_channel).RemoteAddress; } } void IOutputChannel.Send(Message message) { ((IOutputChannel)_channel).Send(message); } void IOutputChannel.Send(Message message, TimeSpan timeout) { ((IOutputChannel)_channel).Send(message, timeout); } IAsyncResult IOutputChannel.BeginSend(Message message, AsyncCallback callback, object state) { return ((IOutputChannel)_channel).BeginSend(message, callback, state); } IAsyncResult IOutputChannel.BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return ((IOutputChannel)_channel).BeginSend(message, timeout, callback, state); } void IOutputChannel.EndSend(IAsyncResult result) { ((IOutputChannel)_channel).EndSend(result); } Uri IRequestChannel.Via { get { return ((IRequestChannel)_channel).Via; } } EndpointAddress IRequestChannel.RemoteAddress { get { return ((IRequestChannel)_channel).RemoteAddress; } } Message IRequestChannel.Request(Message message) { return ((IRequestChannel)_channel).Request(message); } Message IRequestChannel.Request(Message message, TimeSpan timeout) { return ((IRequestChannel)_channel).Request(message, timeout); } IAsyncResult IRequestChannel.BeginRequest(Message message, AsyncCallback callback, object state) { return ((IRequestChannel)_channel).BeginRequest(message, callback, state); } IAsyncResult IRequestChannel.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return ((IRequestChannel)_channel).BeginRequest(message, timeout, callback, state); } Message IRequestChannel.EndRequest(IAsyncResult result) { return ((IRequestChannel)_channel).EndRequest(result); } ServiceChannel IChannelBaseProxy.GetServiceChannel() { return _channel; } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Compilation.Preprocessor; using Microsoft.DotNet.ProjectModel.Files; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.DotNet.ProjectModel.Resolution; using Microsoft.DotNet.ProjectModel.Utilities; using Microsoft.DotNet.Tools.Compiler; using NuGet.Frameworks; namespace Microsoft.DotNet.ProjectModel.Compilation { public class LibraryExporter { private readonly string _configuration; private readonly string _runtime; private readonly string[] _runtimeFallbacks; private readonly ProjectDescription _rootProject; private readonly string _buildBasePath; private readonly string _solutionRootPath; public LibraryExporter(ProjectDescription rootProject, LibraryManager manager, string configuration, string runtime, string[] runtimeFallbacks, string buildBasePath, string solutionRootPath) { if (string.IsNullOrEmpty(configuration)) { throw new ArgumentNullException(nameof(configuration)); } LibraryManager = manager; _configuration = configuration; _runtime = runtime; _runtimeFallbacks = runtimeFallbacks; _buildBasePath = buildBasePath; _solutionRootPath = solutionRootPath; _rootProject = rootProject; } public LibraryManager LibraryManager { get; } /// <summary> /// Gets all the exports specified by this project, including the root project itself /// </summary> public IEnumerable<LibraryExport> GetAllExports() { return ExportLibraries(_ => true); } /// <summary> /// Gets all exports required by the project, NOT including the project itself /// </summary> /// <returns></returns> public IEnumerable<LibraryExport> GetDependencies() { return GetDependencies(LibraryType.Unspecified); } /// <summary> /// Gets all exports required by the project, of the specified <see cref="LibraryType"/>, NOT including the project itself /// </summary> /// <returns></returns> public IEnumerable<LibraryExport> GetDependencies(LibraryType type) { // Export all but the main project return ExportLibraries(library => library != _rootProject && LibraryIsOfType(type, library)); } /// <summary> /// Retrieves a list of <see cref="LibraryExport"/> objects representing the assets /// required from other libraries to compile this project. /// </summary> private IEnumerable<LibraryExport> ExportLibraries(Func<LibraryDescription, bool> condition) { var seenMetadataReferences = new HashSet<string>(); // Iterate over libraries in the library manager foreach (var library in LibraryManager.GetLibraries()) { if (!condition(library)) { continue; } var compilationAssemblies = new List<LibraryAsset>(); var sourceReferences = new List<LibraryAsset>(); var analyzerReferences = new List<AnalyzerReference>(); var libraryExport = GetExport(library); // We need to filter out source references from non-root libraries, // so we rebuild the library export foreach (var reference in libraryExport.CompilationAssemblies) { if (seenMetadataReferences.Add(reference.Name)) { compilationAssemblies.Add(reference); } } // Source and analyzer references are not transitive if (library.Parents.Contains(_rootProject)) { sourceReferences.AddRange(libraryExport.SourceReferences); analyzerReferences.AddRange(libraryExport.AnalyzerReferences); } var builder = LibraryExportBuilder.Create(library); if (_runtime != null && _runtimeFallbacks != null) { // For portable apps that are built with runtime trimming we replace RuntimeAssemblyGroups and NativeLibraryGroups // with single default group that contains asset specific to runtime we are trimming for // based on runtime fallback list builder.WithRuntimeAssemblyGroups(TrimAssetGroups(libraryExport.RuntimeAssemblyGroups, _runtimeFallbacks)); builder.WithNativeLibraryGroups(TrimAssetGroups(libraryExport.NativeLibraryGroups, _runtimeFallbacks)); } else { builder.WithRuntimeAssemblyGroups(libraryExport.RuntimeAssemblyGroups); builder.WithNativeLibraryGroups(libraryExport.NativeLibraryGroups); } yield return builder .WithCompilationAssemblies(compilationAssemblies) .WithSourceReferences(sourceReferences) .WithRuntimeAssets(libraryExport.RuntimeAssets) .WithEmbedddedResources(libraryExport.EmbeddedResources) .WithAnalyzerReference(analyzerReferences) .WithResourceAssemblies(libraryExport.ResourceAssemblies) .Build(); } } private IEnumerable<LibraryAssetGroup> TrimAssetGroups(IEnumerable<LibraryAssetGroup> runtimeAssemblyGroups, string[] runtimeFallbacks) { LibraryAssetGroup runtimeAssets; foreach (var rid in runtimeFallbacks) { runtimeAssets = runtimeAssemblyGroups.GetRuntimeGroup(rid); if (runtimeAssets != null) { yield return new LibraryAssetGroup(runtimeAssets.Assets); yield break; } } runtimeAssets = runtimeAssemblyGroups.GetDefaultGroup(); if (runtimeAssets != null) { yield return runtimeAssets; } } /// <summary> /// Create a LibraryExport from LibraryDescription. /// /// When the library is not resolved the LibraryExport is created nevertheless. /// </summary> private LibraryExport GetExport(LibraryDescription library) { if (!library.Resolved) { // For a unresolved project reference returns a export with empty asset. return LibraryExportBuilder.Create(library).Build(); } var libraryType = library.Identity.Type; if (Equals(LibraryType.Package, libraryType) || Equals(LibraryType.MSBuildProject, libraryType)) { return ExportPackage((TargetLibraryWithAssets)library); } else if (Equals(LibraryType.Project, libraryType)) { return ExportProject((ProjectDescription)library); } else { return ExportFrameworkLibrary(library); } } private LibraryExport ExportPackage(TargetLibraryWithAssets library) { var builder = LibraryExportBuilder.Create(library); builder.AddNativeLibraryGroup(new LibraryAssetGroup(PopulateAssets(library, library.NativeLibraries))); builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(PopulateAssets(library, library.RuntimeAssemblies))); builder.WithResourceAssemblies(PopulateResources(library, library.ResourceAssemblies)); builder.WithCompilationAssemblies(PopulateAssets(library, library.CompileTimeAssemblies)); if (library.Identity.Type.Equals(LibraryType.Package)) { builder.WithSourceReferences(GetSharedSources((PackageDescription) library)); builder.WithAnalyzerReference(GetAnalyzerReferences((PackageDescription) library)); } if (library.ContentFiles.Any()) { var parameters = PPFileParameters.CreateForProject(_rootProject.Project); Action<Stream, Stream> transform = (input, output) => PPFilePreprocessor.Preprocess(input, output, parameters); var sourceCodeLanguage = _rootProject.Project.GetSourceCodeLanguage(); var languageGroups = library.ContentFiles.GroupBy(file => file.CodeLanguage); var selectedGroup = languageGroups.FirstOrDefault(g => g.Key == sourceCodeLanguage) ?? languageGroups.FirstOrDefault(g => g.Key == null); if (selectedGroup != null) { foreach (var contentFile in selectedGroup) { if (contentFile.CodeLanguage != null && string.Compare(contentFile.CodeLanguage, sourceCodeLanguage, StringComparison.OrdinalIgnoreCase) != 0) { continue; } var fileTransform = contentFile.PPOutputPath != null ? transform : null; var fullPath = Path.Combine(library.Path, contentFile.Path); if (contentFile.BuildAction == BuildAction.Compile) { builder.AddSourceReference(LibraryAsset.CreateFromRelativePath(library.Path, contentFile.Path, fileTransform)); } else if (contentFile.BuildAction == BuildAction.EmbeddedResource) { builder.AddEmbedddedResource(LibraryAsset.CreateFromRelativePath(library.Path, contentFile.Path, fileTransform)); } if (contentFile.CopyToOutput) { builder.AddRuntimeAsset(new LibraryAsset(contentFile.Path, contentFile.OutputPath, fullPath, fileTransform)); } } } } if (library.RuntimeTargets.Any()) { foreach (var targetGroup in library.RuntimeTargets.GroupBy(t => t.Runtime)) { var runtime = new List<LibraryAsset>(); var native = new List<LibraryAsset>(); foreach (var lockFileRuntimeTarget in targetGroup) { if (string.Equals(lockFileRuntimeTarget.AssetType, "native", StringComparison.OrdinalIgnoreCase)) { native.Add(LibraryAsset.CreateFromRelativePath(library.Path, lockFileRuntimeTarget.Path)); } else if (string.Equals(lockFileRuntimeTarget.AssetType, "runtime", StringComparison.OrdinalIgnoreCase)) { runtime.Add(LibraryAsset.CreateFromRelativePath(library.Path, lockFileRuntimeTarget.Path)); } } if (runtime.Any()) { builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(targetGroup.Key, runtime.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.RelativePath)))); } if (native.Any()) { builder.AddNativeLibraryGroup(new LibraryAssetGroup(targetGroup.Key, native.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.RelativePath)))); } } } return builder.Build(); } private LibraryExport ExportProject(ProjectDescription project) { var builder = LibraryExportBuilder.Create(project); var compilerOptions = project.Project.GetCompilerOptions(project.TargetFrameworkInfo.FrameworkName, _configuration); if (!string.IsNullOrEmpty(project.TargetFrameworkInfo?.AssemblyPath)) { // Project specifies a pre-compiled binary. We're done! var assemblyPath = ResolvePath(project.Project, _configuration, project.TargetFrameworkInfo.AssemblyPath); var pdbPath = Path.ChangeExtension(assemblyPath, "pdb"); if (!File.Exists(pdbPath)) { pdbPath = assemblyPath + ".mdb"; } var compileAsset = new LibraryAsset( project.Project.Name, Path.GetFileName(assemblyPath), assemblyPath); builder.AddCompilationAssembly(compileAsset); builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(new[] { compileAsset })); if (File.Exists(pdbPath)) { builder.AddRuntimeAsset(new LibraryAsset(Path.GetFileName(pdbPath), Path.GetFileName(pdbPath), pdbPath)); } } else if (HasSourceFiles(project, compilerOptions)) { var outputPaths = project.GetOutputPaths(_buildBasePath, _solutionRootPath, _configuration, _runtime); var compilationAssembly = outputPaths.CompilationFiles.Assembly; var compilationAssemblyAsset = LibraryAsset.CreateFromAbsolutePath( outputPaths.CompilationFiles.BasePath, compilationAssembly); builder.AddCompilationAssembly(compilationAssemblyAsset); if (ExportsRuntime(project)) { var runtimeAssemblyAsset = LibraryAsset.CreateFromAbsolutePath( outputPaths.RuntimeFiles.BasePath, outputPaths.RuntimeFiles.Assembly); builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(new[] { runtimeAssemblyAsset })); builder.WithRuntimeAssets(CollectAssets(outputPaths.RuntimeFiles)); } else { builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(new[] { compilationAssemblyAsset })); builder.WithRuntimeAssets(CollectAssets(outputPaths.CompilationFiles)); } builder.WithResourceAssemblies(outputPaths.CompilationFiles.Resources().Select(r => new LibraryResourceAssembly( LibraryAsset.CreateFromAbsolutePath(outputPaths.CompilationFiles.BasePath, r.Path), r.Locale))); } builder.WithSourceReferences(project.Project.Files.SharedFiles.Select(f => LibraryAsset.CreateFromAbsolutePath(project.Path, f) )); return builder.Build(); } private bool HasSourceFiles(ProjectDescription project, CommonCompilerOptions compilerOptions) { if (compilerOptions.CompileInclude == null) { return project.Project.Files.SourceFiles.Any(); } var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null); return includeFiles.Any(); } private IEnumerable<LibraryAsset> CollectAssets(CompilationOutputFiles files) { var assemblyPath = files.Assembly; foreach (var path in files.All().Except(files.Resources().Select(r => r.Path))) { if (string.Equals(assemblyPath, path)) { continue; } yield return LibraryAsset.CreateFromAbsolutePath(files.BasePath, path); } } private bool ExportsRuntime(ProjectDescription project) { return project == _rootProject && !string.IsNullOrWhiteSpace(_runtime) && project.Project.HasRuntimeOutput(_configuration); } private static string ResolvePath(Project project, string configuration, string path) { if (string.IsNullOrEmpty(path)) { return null; } path = PathUtility.GetPathWithDirectorySeparator(path); path = path.Replace("{configuration}", configuration); return Path.Combine(project.ProjectDirectory, path); } private LibraryExport ExportFrameworkLibrary(LibraryDescription library) { // We assume the path is to an assembly. Framework libraries only export compile-time stuff // since they assume the runtime library is present already var builder = LibraryExportBuilder.Create(library); if (!string.IsNullOrEmpty(library.Path)) { builder.WithCompilationAssemblies(new[] { new LibraryAsset(library.Identity.Name, null, library.Path) }); } return builder.Build(); } private IEnumerable<LibraryAsset> GetSharedSources(PackageDescription package) { return package .PackageLibrary .Files .Where(path => path.StartsWith("shared" + Path.DirectorySeparatorChar)) .Select(path => LibraryAsset.CreateFromRelativePath(package.Path, path)); } private IEnumerable<AnalyzerReference> GetAnalyzerReferences(PackageDescription package) { var analyzers = package .PackageLibrary .Files .Where(path => path.StartsWith("analyzers" + Path.DirectorySeparatorChar) && path.EndsWith(".dll")); var analyzerRefs = new List<AnalyzerReference>(); // See https://docs.nuget.org/create/analyzers-conventions for the analyzer // NuGet specification foreach (var analyzer in analyzers) { var specifiers = analyzer.Split(Path.DirectorySeparatorChar); var assemblyPath = Path.Combine(package.Path, analyzer); // $/analyzers/{Framework Name}{Version}/{Supported Architecture}/{Supported Programming Language}/{Analyzer}.dll switch (specifiers.Length) { // $/analyzers/{analyzer}.dll case 2: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: null, language: null, runtimeIdentifier: null )); break; // $/analyzers/{framework}/{analyzer}.dll case 3: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: NuGetFramework.Parse(specifiers[1]), language: null, runtimeIdentifier: null )); break; // $/analyzers/{framework}/{language}/{analyzer}.dll case 4: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: NuGetFramework.Parse(specifiers[1]), language: specifiers[2], runtimeIdentifier: null )); break; // $/analyzers/{framework}/{runtime}/{language}/{analyzer}.dll case 5: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: NuGetFramework.Parse(specifiers[1]), language: specifiers[3], runtimeIdentifier: specifiers[2] )); break; // Anything less than 2 specifiers or more than 4 is // illegal according to the specification and will be // ignored } } return analyzerRefs; } private IEnumerable<LibraryResourceAssembly> PopulateResources(TargetLibraryWithAssets library, IEnumerable<LockFileItem> section) { foreach (var assemblyPath in section.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.Path))) { string locale; if(!assemblyPath.Properties.TryGetValue(Constants.LocaleLockFilePropertyName, out locale)) { locale = null; } yield return new LibraryResourceAssembly( LibraryAsset.CreateFromRelativePath(library.Path, assemblyPath.Path), locale); } } private IEnumerable<LibraryAsset> PopulateAssets(TargetLibraryWithAssets library, IEnumerable<LockFileItem> section) { foreach (var assemblyPath in section.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.Path))) { yield return LibraryAsset.CreateFromRelativePath(library.Path, assemblyPath.Path); } } private static bool LibraryIsOfType(LibraryType type, LibraryDescription library) { return type.Equals(LibraryType.Unspecified) || // No type filter was requested library.Identity.Type.Equals(type); // OR, library type matches requested type } } }
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 Governance.ExternalSharingTimer.Web { 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> /// Configures .Net to trust all certificates when making network calls. This is used so that calls /// to an https SharePoint server without a valid certificate are not rejected. This should only be used during /// testing, and should never be used in a production app. /// </summary> public static void TrustAllCertificates() { //Trust all certificates ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); } /// <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 } }
// // StreamHeader.cs: Provides support for reading Apple's AIFF stream // properties. // // Author: // Helmut Wahrmann // // Copyright (C) 2009 Helmut Wahrmann // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // using System; using System.Globalization; namespace TagLib.Aiff { /// <summary> /// This struct implements <see cref="IAudioCodec" /> to provide /// support for reading Apple's AIFF stream properties. /// </summary> public struct StreamHeader : IAudioCodec, ILosslessAudioCodec { #region Private Fields /// <summary> /// Contains the number of channels. /// </summary> /// <remarks> /// This value is stored in bytes (9,10). /// 1 is monophonic, 2 is stereo, 4 means 4 channels, etc.. /// any number of audio channels may be represented /// </remarks> private ushort channels; /// <summary> /// Contains the number of sample frames in the Sound Data chunk. /// </summary> /// <remarks> /// This value is stored in bytes (11-14). /// </remarks> private ulong total_frames; /// <summary> /// Contains the number of bits per sample. /// </summary> /// <remarks> /// This value is stored in bytes (15,16). /// It can be any number from 1 to 32. /// </remarks> private ushort bits_per_sample; /// <summary> /// Contains the sample rate. /// </summary> /// <remarks> /// This value is stored in bytes (17-26). /// the sample rate at which the sound is to be played back, /// in sample frames per second /// </remarks> private ulong sample_rate; /// <summary> /// Contains the length of the audio stream. /// </summary> /// <remarks> /// This value is provided by the constructor. /// </remarks> private long stream_length; #endregion #region Public Static Fields /// <summary> /// The size of an AIFF Common chunk /// </summary> public const uint Size = 26; /// <summary> /// The identifier used to recognize a AIFF file. /// Altough an AIFF file start with "FORM2, we're interested /// in the Common chunk only, which contains the properties we need. /// </summary> /// <value> /// "COMM" /// </value> public static readonly ReadOnlyByteVector FileIdentifier = "COMM"; #endregion #region Constructors /// <summary> /// Constructs and initializes a new instance of <see /// cref="StreamHeader" /> for a specified header block and /// stream length. /// </summary> /// <param name="data"> /// A <see cref="ByteVector" /> object containing the stream /// header data. /// </param> /// <param name="streamLength"> /// A <see cref="long" /> value containing the length of the /// AIFF Audio stream in bytes. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="data" /> is <see langword="null" />. /// </exception> /// <exception cref="CorruptFileException"> /// <paramref name="data" /> does not begin with <see /// cref="FileIdentifier" /> /// </exception> public StreamHeader(ByteVector data, long streamLength) { if (data == null) throw new ArgumentNullException("data"); if (!data.StartsWith(FileIdentifier)) throw new CorruptFileException( "Data does not begin with identifier."); stream_length = streamLength; // The first 8 bytes contain the Common chunk identifier "COMM" // And the size of the common chunk, which is always 18 channels = data.Mid(8, 2).ToUShort(true); total_frames = data.Mid(10, 4).ToULong(true); bits_per_sample = data.Mid(14, 2).ToUShort(true); ByteVector sample_rate_indicator = data.Mid(17, 1); ulong sample_rate_tmp = data.Mid(18, 2).ToULong(true); sample_rate = 44100; // Set 44100 as default sample rate // The following are combinations that iTunes 8 encodes to. // There may be other combinations in the field, but i couldn't test them. switch (sample_rate_tmp) { case 44100: if (sample_rate_indicator == 0x0E) { sample_rate = 44100; } else if (sample_rate_indicator == 0x0D) { sample_rate = 22050; } else if (sample_rate_indicator == 0x0C) { sample_rate = 11025; } break; case 48000: if (sample_rate_indicator == 0x0E) { sample_rate = 48000; } else if (sample_rate_indicator == 0x0D) { sample_rate = 24000; } break; case 64000: if (sample_rate_indicator == 0x0D) { sample_rate = 32000; } else if (sample_rate_indicator == 0x0C) { sample_rate = 16000; } else if (sample_rate_indicator == 0x0B) { sample_rate = 8000; } break; case 44510: if (sample_rate_indicator == 0x0D) { sample_rate = 22255; } break; case 44508: if (sample_rate_indicator == 0x0C) { sample_rate = 11127; } break; } } #endregion #region Public Properties /// <summary> /// Gets the duration of the media represented by the current /// instance. /// </summary> /// <value> /// A <see cref="TimeSpan" /> containing the duration of the /// media represented by the current instance. /// </value> public TimeSpan Duration { get { if (sample_rate <= 0 || total_frames <= 0) return TimeSpan.Zero; return TimeSpan.FromSeconds( (double) total_frames/ (double) sample_rate); } } /// <summary> /// Gets the types of media represented by the current /// instance. /// </summary> /// <value> /// Always <see cref="MediaTypes.Audio" />. /// </value> public MediaTypes MediaTypes { get { return MediaTypes.Audio; } } /// <summary> /// Gets a text description of the media represented by the /// current instance. /// </summary> /// <value> /// A <see cref="string" /> object containing a description /// of the media represented by the current instance. /// </value> public string Description { get { return "AIFF Audio"; } } /// <summary> /// Gets the bitrate of the audio represented by the current /// instance. /// </summary> /// <value> /// A <see cref="int" /> value containing a bitrate of the /// audio represented by the current instance. /// </value> public int AudioBitrate { get { TimeSpan d = Duration; if (d <= TimeSpan.Zero) return 0; return (int) ((stream_length*8L)/ d.TotalSeconds)/1000; } } /// <summary> /// Gets the sample rate of the audio represented by the /// current instance. /// </summary> /// <value> /// A <see cref="int" /> value containing the sample rate of /// the audio represented by the current instance. /// </value> public int AudioSampleRate { get { return (int) sample_rate; } } /// <summary> /// Gets the number of channels in the audio represented by /// the current instance. /// </summary> /// <value> /// A <see cref="int" /> value containing the number of /// channels in the audio represented by the current /// instance. /// </value> public int AudioChannels { get { return channels; } } /// <summary> /// Gets the number of bits per sample in the audio /// represented by the current instance. /// </summary> /// <value> /// A <see cref="int" /> value containing the number of bits /// per sample in the audio represented by the current /// instance. /// </value> public int BitsPerSample { get { return bits_per_sample; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class Event_Generic : PortsTest { // Maximum time to wait for all of the expected events to be firered private static readonly int MAX_TIME_WAIT = 5000; // Time to wait in-between triggering events private static readonly int TRIGERING_EVENTS_WAIT_TIME = 500; #region Test Cases [ConditionalFact(nameof(HasNullModem))] public void EventHandlers_CalledSerially() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true); ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true); ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true); int numPinChangedEvents = 0, numErrorEvents = 0, numReceivedEvents = 0; int iterationWaitTime = 100; /*************************************************************** Scenario Description: All of the event handlers should be called sequentially never at the same time on multiple thread. Basically we will block each event handler caller thread and verify that no other thread is in another event handler ***************************************************************/ Debug.WriteLine("Verifying that event handlers are called serially"); com1.WriteTimeout = 5000; com2.WriteTimeout = 5000; com1.Open(); com2.Open(); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); com1.PinChanged += pinChangedEventHandler.HandleEvent; com1.DataReceived += receivedEventHandler.HandleEvent; com1.ErrorReceived += errorEventHandler.HandleEvent; //This should cause ErrorEvent to be fired with a parity error since the //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), //and com2 is writing 0 for this bit com1.DataBits = 7; com1.Parity = Parity.Mark; com2.BaseStream.Write(new byte[1], 0, 1); Debug.Print("ERROREvent Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged //since we are setting DtrEnable to true com2.DtrEnable = true; Debug.WriteLine("PinChange Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause ReceivedEvent to be fired with ReceivedChars //since we are writing some bytes com1.DataBits = 8; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 40 }, 0, 1); Debug.WriteLine("RxEvent Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause a frame error since the 8th bit is not set, //and com1 is set to 7 data bits so the 8th bit will +12v where //com1 expects the stop bit at the 8th bit to be -12v com1.DataBits = 7; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 0x01 }, 0, 1); Debug.WriteLine("FrameError Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause PinChangedEvent to be fired with SerialPinChanges.CtsChanged //since we are setting RtsEnable to true com2.RtsEnable = true; Debug.WriteLine("PinChange Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause ReceivedEvent to be fired with EofReceived //since we are writing the EOF char com1.DataBits = 8; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 26 }, 0, 1); Debug.WriteLine("RxEOF Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause PinChangedEvent to be fired with SerialPinChanges.Break //since we are setting BreakState to true com2.BreakState = true; Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); bool threadFound = true; Stopwatch sw = Stopwatch.StartNew(); while (threadFound && sw.ElapsedMilliseconds < MAX_TIME_WAIT) { threadFound = false; for (int i = 0; i < MAX_TIME_WAIT / iterationWaitTime; ++i) { Debug.WriteLine("Event counts: PinChange {0}, Rx {1}, error {2}", numPinChangedEvents, numReceivedEvents, numErrorEvents); Debug.WriteLine("Waiting for pinchange event {0}ms", iterationWaitTime); if (pinChangedEventHandler.WaitForEvent(iterationWaitTime, numPinChangedEvents + 1)) { // A thread is in PinChangedEvent: verify that it is not in any other handler at the same time if (receivedEventHandler.NumEventsHandled != numReceivedEvents) { Fail("Err_191818ahied A thread is in PinChangedEvent and ReceivedEvent"); } if (errorEventHandler.NumEventsHandled != numErrorEvents) { Fail("Err_198119hjaheid A thread is in PinChangedEvent and ErrorEvent"); } ++numPinChangedEvents; pinChangedEventHandler.ResumeHandleEvent(); threadFound = true; break; } Debug.WriteLine("Waiting for rx event {0}ms", iterationWaitTime); if (receivedEventHandler.WaitForEvent(iterationWaitTime, numReceivedEvents + 1)) { // A thread is in ReceivedEvent: verify that it is not in any other handler at the same time if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents) { Fail("Err_2288ajed A thread is in ReceivedEvent and PinChangedEvent"); } if (errorEventHandler.NumEventsHandled != numErrorEvents) { Fail("Err_25158ajeiod A thread is in ReceivedEvent and ErrorEvent"); } ++numReceivedEvents; receivedEventHandler.ResumeHandleEvent(); threadFound = true; break; } Debug.WriteLine("Waiting for error event {0}ms", iterationWaitTime); if (errorEventHandler.WaitForEvent(iterationWaitTime, numErrorEvents + 1)) { // A thread is in ErrorEvent: verify that it is not in any other handler at the same time if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents) { Fail("Err_01208akiehd A thread is in ErrorEvent and PinChangedEvent"); } if (receivedEventHandler.NumEventsHandled != numReceivedEvents) { Fail("Err_1254847ajied A thread is in ErrorEvent and ReceivedEvent"); } ++numErrorEvents; errorEventHandler.ResumeHandleEvent(); threadFound = true; break; } } } if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 3)) { Fail("Err_2288ajied Expected 3 PinChangedEvents to be fired and only {0} occurred", pinChangedEventHandler.NumEventsHandled); } if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) { Fail("Err_122808aoeid Expected 2 ReceivedEvents to be fired and only {0} occurred", receivedEventHandler.NumEventsHandled); } if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) { Fail("Err_215887ajeid Expected 3 ErrorEvents to be fired and only {0} occurred", errorEventHandler.NumEventsHandled); } //[] Verify all PinChangedEvents should have occurred pinChangedEventHandler.Validate(SerialPinChange.DsrChanged, 0); pinChangedEventHandler.Validate(SerialPinChange.CtsChanged, 0); pinChangedEventHandler.Validate(SerialPinChange.Break, 0); //[] Verify all ReceivedEvent should have occurred receivedEventHandler.Validate(SerialData.Chars, 0); receivedEventHandler.Validate(SerialData.Eof, 0); //[] Verify all ErrorEvents should have occurred errorEventHandler.Validate(SerialError.RXParity, 0); errorEventHandler.Validate(SerialError.Frame, 0); // It's important that we close com1 BEFORE com2 (the using() block would do this the other way around normally) // This is because we have our special blocking event handlers hooked onto com1, and closing com2 is likely to // cause a pin-change event which then hangs and prevents com1 from closing. // An alternative approach would be to unhook all the event-handlers before leaving the using() block. com1.Close(); } } [ConditionalFact(nameof(HasNullModem))] public void Thread_In_PinChangedEvent() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true); Debug.WriteLine( "Verifying that if a thread is blocked in a PinChangedEvent handler the port can still be closed"); com1.Open(); com2.Open(); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); com1.PinChanged += pinChangedEventHandler.HandleEvent; //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged //since we are setting DtrEnable to true com2.DtrEnable = true; if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) { Fail("Err_32688ajoid Expected 1 PinChangedEvents to be fired and only {0} occurred", pinChangedEventHandler.NumEventsHandled); } Task task = Task.Run(() => com1.Close()); Thread.Sleep(5000); pinChangedEventHandler.ResumeHandleEvent(); TCSupport.WaitForTaskCompletion(task); } } [ConditionalFact(nameof(HasNullModem))] public void Thread_In_ReceivedEvent() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true); Debug.WriteLine( "Verifying that if a thread is blocked in a RecevedEvent handler the port can still be closed"); com1.Open(); com2.Open(); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); com1.DataReceived += receivedEventHandler.HandleEvent; //This should cause ReceivedEvent to be fired with ReceivedChars //since we are writing some bytes com1.DataBits = 8; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 40 }, 0, 1); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) { Fail("Err_122808aoeid Expected 1 ReceivedEvents to be fired and only {0} occurred", receivedEventHandler.NumEventsHandled); } Task task = Task.Run(() => com1.Close()); Thread.Sleep(5000); receivedEventHandler.ResumeHandleEvent(); TCSupport.WaitForTaskCompletion(task); } } [ConditionalFact(nameof(HasNullModem))] public void Thread_In_ErrorEvent() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true); Debug.WriteLine("Verifying that if a thread is blocked in a ErrorEvent handler the port can still be closed"); com1.Open(); com2.Open(); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); com1.ErrorReceived += errorEventHandler.HandleEvent; //This should cause ErrorEvent to be fired with a parity error since the //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), //and com2 is writing 0 for this bit com1.DataBits = 7; com1.Parity = Parity.Mark; com2.BaseStream.Write(new byte[1], 0, 1); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) { Fail("Err_215887ajeid Expected 1 ErrorEvents to be fired and only {0} occurred", errorEventHandler.NumEventsHandled); } Task task = Task.Run(() => com1.Close()); Thread.Sleep(5000); errorEventHandler.ResumeHandleEvent(); TCSupport.WaitForTaskCompletion(task); } } #endregion #region Verification for Test Cases private class PinChangedEventHandler : TestEventHandler<SerialPinChange> { public PinChangedEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait) { } public void HandleEvent(object source, SerialPinChangedEventArgs e) { HandleEvent(source, e.EventType); } } private class ErrorEventHandler : TestEventHandler<SerialError> { public ErrorEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait) { } public void HandleEvent(object source, SerialErrorReceivedEventArgs e) { HandleEvent(source, e.EventType); } } private class ReceivedEventHandler : TestEventHandler<SerialData> { public ReceivedEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait) { } public void HandleEvent(object source, SerialDataReceivedEventArgs e) { HandleEvent(source, e.EventType); } } #endregion } }
// // DiscSource.cs // // Author: // Alex Launi <[email protected]> // // Copyright 2010 Alex Launi // // 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.Threading; using Hyena; using Mono.Unix; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.ServiceStack; using Banshee.Sources; using Selection = Hyena.Collections.Selection; namespace Banshee.OpticalDisc { public abstract class DiscSource : Source, ITrackModelSource, IUnmapableSource, IDisposable { public DiscSource (DiscService service, DiscModel model, string genericName, string name, int order) : base (genericName, name, order) { Service = service; Model = model; } protected DiscService Service { get; set; } protected DiscModel Model { get; set; } public DiscModel DiscModel { get { return Model; } protected set { Model = value; } } public bool DiscIsPlaying { get { DiscTrackInfo playing_track = ServiceManager.PlayerEngine.CurrentTrack as DiscTrackInfo; return playing_track != null && playing_track.Model == Model; } } public virtual void StopPlayingDisc () { if (DiscIsPlaying) { ServiceManager.PlayerEngine.Close (true); } } public virtual void Dispose () { } #region ITrackModelSource Implementation public TrackListModel TrackModel { get { return Model; } } public AlbumListModel AlbumModel { get { return null; } } public ArtistListModel ArtistModel { get { return null; } } public void Reload () { Model.Reload (); } public void RemoveTracks (Selection selection) { } public void DeleteTracks (Selection selection) { } public abstract bool CanRepeat { get; } public abstract bool CanShuffle { get; } public bool CanAddTracks { get { return false; } } public bool CanRemoveTracks { get { return false; } } public bool CanDeleteTracks { get { return false; } } public bool ConfirmRemoveTracks { get { return false; } } public bool ShowBrowser { get { return false; } } public bool HasDependencies { get { return false; } } public bool Indexable { get { return false; } } #endregion #region IUnmapableSource Implementation public bool Unmap () { StopPlayingDisc (); foreach (TrackInfo track in DiscModel) { track.CanPlay = false; } OnUpdated (); SourceMessage eject_message = new SourceMessage (this); eject_message.FreezeNotify (); eject_message.IsSpinning = true; eject_message.CanClose = false; // Translators: {0} is the type of disc, "Audio CD" or "DVD" eject_message.Text = String.Format (Catalog.GetString ("Ejecting {0}..."), GenericName.ToLower ()); eject_message.ThawNotify (); PushMessage (eject_message); ThreadPool.QueueUserWorkItem (delegate { try { DiscModel.Volume.Unmount (); DiscModel.Volume.Eject (); ThreadAssist.ProxyToMain (delegate { Service.UnmapDiscVolume (DiscModel.Volume.Uuid); Dispose (); }); } catch (Exception e) { ThreadAssist.ProxyToMain (delegate { ClearMessages (); eject_message.IsSpinning = false; eject_message.SetIconName ("dialog-error"); // Translators: {0} is the type of disc, "Audio CD" or "DVD". {1} is the error message. eject_message.Text = String.Format (Catalog.GetString ("Could not eject {0}: {1}"), GenericName.ToLower (), e.Message); PushMessage (eject_message); foreach (TrackInfo track in Model) { track.CanPlay = true; } OnUpdated (); }); Log.Error (e); } }); return true; } public bool CanUnmap { get { return DiscModel != null ? !DiscModel.IsDoorLocked : true; } } public bool ConfirmBeforeUnmap { get { return false; } } #endregion } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.Build.Construction; using Microsoft.DotNet.Tools; using Microsoft.DotNet.Tools.Test.Utilities; using Msbuild.Tests.Utilities; using System; using System.IO; using Xunit; namespace Microsoft.DotNet.Cli.List.Reference.Tests { public class GivenDotnetListReference : TestBase { private const string HelpText = @"Usage: dotnet list <PROJECT | SOLUTION> reference [options] Arguments: <PROJECT | SOLUTION> The project or solution file to operate on. If a file is not specified, the command will search the current directory for one. Options: -h, --help Show command line help."; private const string ListCommandHelpText = @"Usage: dotnet list [options] <PROJECT | SOLUTION> [command] Arguments: <PROJECT | SOLUTION> The project or solution file to operate on. If a file is not specified, the command will search the current directory for one. Options: -h, --help Show command line help. Commands: package List all package references of the project or solution. reference List all project-to-project references of the project."; const string FrameworkNet451Arg = "-f net451"; const string ConditionFrameworkNet451 = "== 'net451'"; const string FrameworkNetCoreApp10Arg = "-f netcoreapp1.0"; const string ConditionFrameworkNetCoreApp10 = "== 'netcoreapp1.0'"; [Theory] [InlineData("--help")] [InlineData("-h")] public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg) { var cmd = new ListReferenceCommand().Execute(helpArg); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Theory] [InlineData("")] [InlineData("unknownCommandName")] public void WhenNoCommandIsPassedItPrintsError(string commandName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"list {commandName}"); cmd.Should().Fail(); cmd.StdErr.Should().Be(CommonLocalizableStrings.RequiredCommandNotPassed); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(ListCommandHelpText); } [Fact] public void WhenTooManyArgumentsArePassedItPrintsError() { var cmd = new ListReferenceCommand() .WithProject("one two three") .Execute("proj.csproj"); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().BeVisuallyEquivalentTo($@"{string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "two")} {string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "three")}"); } [Theory] [InlineData("idontexist.csproj")] [InlineData("ihave?inv@lid/char\\acters")] public void WhenNonExistingProjectIsPassedItPrintsErrorAndUsage(string projName) { var setup = Setup(); var cmd = new ListReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(projName) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindProjectOrDirectory, projName)); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Fact] public void WhenBrokenProjectIsPassedItPrintsErrorAndUsage() { string projName = "Broken/Broken.csproj"; var setup = Setup(); var cmd = new ListReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(projName) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.ProjectIsInvalid, "Broken/Broken.csproj")); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Fact] public void WhenMoreThanOneProjectExistsInTheDirectoryItPrintsErrorAndUsage() { var setup = Setup(); var workingDir = Path.Combine(setup.TestRoot, "MoreThanOne"); var cmd = new ListReferenceCommand() .WithWorkingDirectory(workingDir) .Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.MoreThanOneProjectInDirectory, workingDir + Path.DirectorySeparatorChar)); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Fact] public void WhenNoProjectsExistsInTheDirectoryItPrintsErrorAndUsage() { var setup = Setup(); var cmd = new ListReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindAnyProjectInDirectory, setup.TestRoot + Path.DirectorySeparatorChar)); cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText); } [Fact] public void WhenNoProjectReferencesArePresentInTheProjectItPrintsError() { var lib = NewLib(); var cmd = new ListReferenceCommand() .WithProject(lib.CsProjPath) .Execute(); cmd.Should().Pass(); cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.NoReferencesFound, CommonLocalizableStrings.P2P, lib.CsProjPath)); } [Fact] public void ItPrintsSingleReference() { string OutputText = CommonLocalizableStrings.ProjectReferenceOneOrMore; OutputText += $@" {new string('-', OutputText.Length)} ..\ref\ref.csproj"; var lib = NewLib("lib"); string ref1 = NewLib("ref").CsProjPath; AddValidRef(ref1, lib); var cmd = new ListReferenceCommand() .WithProject(lib.CsProjPath) .Execute(); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText); } [Fact] public void ItPrintsMultipleReferences() { string OutputText = CommonLocalizableStrings.ProjectReferenceOneOrMore; OutputText += $@" {new string('-', OutputText.Length)} ..\ref1\ref1.csproj ..\ref2\ref2.csproj ..\ref3\ref3.csproj"; var lib = NewLib("lib"); string ref1 = NewLib("ref1").CsProjPath; string ref2 = NewLib("ref2").CsProjPath; string ref3 = NewLib("ref3").CsProjPath; AddValidRef(ref1, lib); AddValidRef(ref2, lib); AddValidRef(ref3, lib); var cmd = new ListReferenceCommand() .WithProject(lib.CsProjPath) .Execute(); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText); } private TestSetup Setup([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(Setup), string identifier = "") { return new TestSetup( TestAssets.Get(TestSetup.TestGroup, TestSetup.ProjectName) .CreateInstance(callingMethod: callingMethod, identifier: identifier) .WithSourceFiles() .Root .FullName); } private ProjDir NewDir(string testProjectName = "temp", [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "") { return new ProjDir(TestAssets.CreateTestDirectory(testProjectName: testProjectName, callingMethod: callingMethod, identifier: identifier).FullName); } private ProjDir NewLib(string testProjectName = "temp", [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "") { var dir = NewDir(testProjectName: testProjectName, callingMethod: callingMethod, identifier: identifier); try { string newArgs = $"classlib -o \"{dir.Path}\" --debug:ephemeral-hive --no-restore"; new NewCommandShim() .WithWorkingDirectory(dir.Path) .ExecuteWithCapturedOutput(newArgs) .Should().Pass(); } catch (System.ComponentModel.Win32Exception e) { throw new Exception($"Intermittent error in `dotnet new` occurred when running it in dir `{dir.Path}`\nException:\n{e}"); } return dir; } private void AddValidRef(string path, ProjDir proj) { new AddReferenceCommand() .WithProject(proj.CsProjPath) .Execute($"\"{path}\"") .Should().Pass(); } } }
// 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.Xml.Xsl.XPath; using System.Xml.Xsl.Qil; namespace System.Xml.Xsl.Xslt { using T = XmlQueryTypeFactory; // <spec>http://www.w3.org/TR/xslt20/#dt-singleton-focus</spec> internal enum SingletonFocusType { // No context set // Used to prevent bugs None, // Document node of the document containing the initial context node // Used while compiling global variables and params InitialDocumentNode, // Initial context node for the transformation // Used while compiling initial apply-templates InitialContextNode, // Context node is specified by iterator // Used while compiling keys Iterator, } internal struct SingletonFocus : IFocus { private readonly XPathQilFactory _f; private SingletonFocusType _focusType; private QilIterator _current; public SingletonFocus(XPathQilFactory f) { _f = f; _focusType = SingletonFocusType.None; _current = null; } public void SetFocus(SingletonFocusType focusType) { Debug.Assert(focusType != SingletonFocusType.Iterator); _focusType = focusType; } public void SetFocus(QilIterator current) { if (current != null) { _focusType = SingletonFocusType.Iterator; _current = current; } else { _focusType = SingletonFocusType.None; _current = null; } } [Conditional("DEBUG")] private void CheckFocus() { Debug.Assert(_focusType != SingletonFocusType.None, "Focus is not set, call SetFocus first"); } public QilNode GetCurrent() { CheckFocus(); switch (_focusType) { case SingletonFocusType.InitialDocumentNode: return _f.Root(_f.XmlContext()); case SingletonFocusType.InitialContextNode: return _f.XmlContext(); default: Debug.Assert(_focusType == SingletonFocusType.Iterator && _current != null, "Unexpected singleton focus type"); return _current; } } public QilNode GetPosition() { CheckFocus(); return _f.Double(1); } public QilNode GetLast() { CheckFocus(); return _f.Double(1); } } internal struct FunctionFocus : IFocus { private bool _isSet; private QilParameter _current, _position, _last; public void StartFocus(IList<QilNode> args, XslFlags flags) { Debug.Assert(!IsFocusSet, "Focus was already set"); int argNum = 0; if ((flags & XslFlags.Current) != 0) { _current = (QilParameter)args[argNum++]; Debug.Assert(_current.Name.NamespaceUri == XmlReservedNs.NsXslDebug && _current.Name.LocalName == "current"); } if ((flags & XslFlags.Position) != 0) { _position = (QilParameter)args[argNum++]; Debug.Assert(_position.Name.NamespaceUri == XmlReservedNs.NsXslDebug && _position.Name.LocalName == "position"); } if ((flags & XslFlags.Last) != 0) { _last = (QilParameter)args[argNum++]; Debug.Assert(_last.Name.NamespaceUri == XmlReservedNs.NsXslDebug && _last.Name.LocalName == "last"); } _isSet = true; } public void StopFocus() { Debug.Assert(IsFocusSet, "Focus was not set"); _isSet = false; _current = _position = _last = null; } public bool IsFocusSet { get { return _isSet; } } public QilNode GetCurrent() { Debug.Assert(_current != null, "Naked current() is not expected in this function"); return _current; } public QilNode GetPosition() { Debug.Assert(_position != null, "Naked position() is not expected in this function"); return _position; } public QilNode GetLast() { Debug.Assert(_last != null, "Naked last() is not expected in this function"); return _last; } } internal struct LoopFocus : IFocus { private readonly XPathQilFactory _f; private QilIterator _current, _cached, _last; public LoopFocus(XPathQilFactory f) { _f = f; _current = _cached = _last = null; } public void SetFocus(QilIterator current) { _current = current; _cached = _last = null; } public bool IsFocusSet { get { return _current != null; } } public QilNode GetCurrent() { return _current; } public QilNode GetPosition() { return _f.XsltConvert(_f.PositionOf(_current), T.DoubleX); } public QilNode GetLast() { if (_last == null) { // Create a let that will be fixed up later in ConstructLoop or by LastFixupVisitor _last = _f.Let(_f.Double(0)); } return _last; } public void EnsureCache() { if (_cached == null) { _cached = _f.Let(_current.Binding); _current.Binding = _cached; } } public void Sort(QilNode sortKeys) { if (sortKeys != null) { // If sorting is required, cache the input node-set to support last() within sort key expressions EnsureCache(); // The rest of the loop content must be compiled in the context of already sorted node-set _current = _f.For(_f.Sort(_current, sortKeys)); } } public QilLoop ConstructLoop(QilNode body) { QilLoop result; if (_last != null) { // last() encountered either in the sort keys or in the body of the current loop EnsureCache(); _last.Binding = _f.XsltConvert(_f.Length(_cached), T.DoubleX); } result = _f.BaseFactory.Loop(_current, body); if (_last != null) { result = _f.BaseFactory.Loop(_last, result); } if (_cached != null) { result = _f.BaseFactory.Loop(_cached, result); } return result; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion #if !PORTABLE40 using System; using System.Collections.Generic; using System.Globalization; using System.Xml; #if !(NET20 || PORTABLE40) using System.Xml.Linq; #endif using Newtonsoft.Json.Utilities; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Converters { #region XmlNodeWrappers #if !NETFX_CORE && !PORTABLE && !PORTABLE40 internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument { private readonly XmlDocument _document; public XmlDocumentWrapper(XmlDocument document) : base(document) { _document = document; } public IXmlNode CreateComment(string data) { return new XmlNodeWrapper(_document.CreateComment(data)); } public IXmlNode CreateTextNode(string text) { return new XmlNodeWrapper(_document.CreateTextNode(text)); } public IXmlNode CreateCDataSection(string data) { return new XmlNodeWrapper(_document.CreateCDataSection(data)); } public IXmlNode CreateWhitespace(string text) { return new XmlNodeWrapper(_document.CreateWhitespace(text)); } public IXmlNode CreateSignificantWhitespace(string text) { return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text)); } public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) { return new XmlDeclarationWrapper(_document.CreateXmlDeclaration(version, encoding, standalone)); } public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset) { return new XmlDocumentTypeWrapper(_document.CreateDocumentType(name, publicId, systemId, null)); } public IXmlNode CreateProcessingInstruction(string target, string data) { return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data)); } public IXmlElement CreateElement(string elementName) { return new XmlElementWrapper(_document.CreateElement(elementName)); } public IXmlElement CreateElement(string qualifiedName, string namespaceUri) { return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceUri)); } public IXmlNode CreateAttribute(string name, string value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name)); attribute.Value = value; return attribute; } public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri)); attribute.Value = value; return attribute; } public IXmlElement DocumentElement { get { if (_document.DocumentElement == null) return null; return new XmlElementWrapper(_document.DocumentElement); } } } internal class XmlElementWrapper : XmlNodeWrapper, IXmlElement { private readonly XmlElement _element; public XmlElementWrapper(XmlElement element) : base(element) { _element = element; } public void SetAttributeNode(IXmlNode attribute) { XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute; _element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode); } public string GetPrefixOfNamespace(string namespaceUri) { return _element.GetPrefixOfNamespace(namespaceUri); } public bool IsEmpty { get { return _element.IsEmpty; } } } internal class XmlDeclarationWrapper : XmlNodeWrapper, IXmlDeclaration { private readonly XmlDeclaration _declaration; public XmlDeclarationWrapper(XmlDeclaration declaration) : base(declaration) { _declaration = declaration; } public string Version { get { return _declaration.Version; } } public string Encoding { get { return _declaration.Encoding; } set { _declaration.Encoding = value; } } public string Standalone { get { return _declaration.Standalone; } set { _declaration.Standalone = value; } } } internal class XmlDocumentTypeWrapper : XmlNodeWrapper, IXmlDocumentType { private readonly XmlDocumentType _documentType; public XmlDocumentTypeWrapper(XmlDocumentType documentType) : base(documentType) { _documentType = documentType; } public string Name { get { return _documentType.Name; } } public string System { get { return _documentType.SystemId; } } public string Public { get { return _documentType.PublicId; } } public string InternalSubset { get { return _documentType.InternalSubset; } } public new string LocalName { get { return "DOCTYPE"; } } } internal class XmlNodeWrapper : IXmlNode { private readonly XmlNode _node; public XmlNodeWrapper(XmlNode node) { _node = node; } public object WrappedNode { get { return _node; } } public XmlNodeType NodeType { get { return _node.NodeType; } } public string LocalName { get { return _node.LocalName; } } public IList<IXmlNode> ChildNodes { get { return _node.ChildNodes.Cast<XmlNode>().Select(n => WrapNode(n)).ToList(); } } private IXmlNode WrapNode(XmlNode node) { switch (node.NodeType) { case XmlNodeType.Element: return new XmlElementWrapper((XmlElement)node); case XmlNodeType.XmlDeclaration: return new XmlDeclarationWrapper((XmlDeclaration)node); case XmlNodeType.DocumentType: return new XmlDocumentTypeWrapper((XmlDocumentType)node); default: return new XmlNodeWrapper(node); } } public IList<IXmlNode> Attributes { get { if (_node.Attributes == null) return null; return _node.Attributes.Cast<XmlAttribute>().Select(a => WrapNode(a)).ToList(); } } public IXmlNode ParentNode { get { XmlNode node = (_node is XmlAttribute) ? ((XmlAttribute)_node).OwnerElement : _node.ParentNode; if (node == null) return null; return WrapNode(node); } } public string Value { get { return _node.Value; } set { _node.Value = value; } } public IXmlNode AppendChild(IXmlNode newChild) { XmlNodeWrapper xmlNodeWrapper = (XmlNodeWrapper)newChild; _node.AppendChild(xmlNodeWrapper._node); return newChild; } public string NamespaceUri { get { return _node.NamespaceURI; } } } #endif #endregion #region Interfaces internal interface IXmlDocument : IXmlNode { IXmlNode CreateComment(string text); IXmlNode CreateTextNode(string text); IXmlNode CreateCDataSection(string data); IXmlNode CreateWhitespace(string text); IXmlNode CreateSignificantWhitespace(string text); IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone); IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset); IXmlNode CreateProcessingInstruction(string target, string data); IXmlElement CreateElement(string elementName); IXmlElement CreateElement(string qualifiedName, string namespaceUri); IXmlNode CreateAttribute(string name, string value); IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value); IXmlElement DocumentElement { get; } } internal interface IXmlDeclaration : IXmlNode { string Version { get; } string Encoding { get; set; } string Standalone { get; set; } } internal interface IXmlDocumentType : IXmlNode { string Name { get; } string System { get; } string Public { get; } string InternalSubset { get; } } internal interface IXmlElement : IXmlNode { void SetAttributeNode(IXmlNode attribute); string GetPrefixOfNamespace(string namespaceUri); bool IsEmpty { get; } } internal interface IXmlNode { XmlNodeType NodeType { get; } string LocalName { get; } IList<IXmlNode> ChildNodes { get; } IList<IXmlNode> Attributes { get; } IXmlNode ParentNode { get; } string Value { get; set; } IXmlNode AppendChild(IXmlNode newChild); string NamespaceUri { get; } object WrappedNode { get; } } #endregion #region XNodeWrappers #if !NET20 internal class XDeclarationWrapper : XObjectWrapper, IXmlDeclaration { internal XDeclaration Declaration { get; private set; } public XDeclarationWrapper(XDeclaration declaration) : base(null) { Declaration = declaration; } public override XmlNodeType NodeType { get { return XmlNodeType.XmlDeclaration; } } public string Version { get { return Declaration.Version; } } public string Encoding { get { return Declaration.Encoding; } set { Declaration.Encoding = value; } } public string Standalone { get { return Declaration.Standalone; } set { Declaration.Standalone = value; } } } internal class XDocumentTypeWrapper : XObjectWrapper, IXmlDocumentType { private readonly XDocumentType _documentType; public XDocumentTypeWrapper(XDocumentType documentType) : base(documentType) { _documentType = documentType; } public string Name { get { return _documentType.Name; } } public string System { get { return _documentType.SystemId; } } public string Public { get { return _documentType.PublicId; } } public string InternalSubset { get { return _documentType.InternalSubset; } } public new string LocalName { get { return "DOCTYPE"; } } } internal class XDocumentWrapper : XContainerWrapper, IXmlDocument { private XDocument Document { get { return (XDocument)WrappedNode; } } public XDocumentWrapper(XDocument document) : base(document) { } public override IList<IXmlNode> ChildNodes { get { IList<IXmlNode> childNodes = base.ChildNodes; if (Document.Declaration != null) childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration)); return childNodes; } } public IXmlNode CreateComment(string text) { return new XObjectWrapper(new XComment(text)); } public IXmlNode CreateTextNode(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateCDataSection(string data) { return new XObjectWrapper(new XCData(data)); } public IXmlNode CreateWhitespace(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateSignificantWhitespace(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) { return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone)); } public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset) { return new XDocumentTypeWrapper(new XDocumentType(name, publicId, systemId, internalSubset)); } public IXmlNode CreateProcessingInstruction(string target, string data) { return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data)); } public IXmlElement CreateElement(string elementName) { return new XElementWrapper(new XElement(elementName)); } public IXmlElement CreateElement(string qualifiedName, string namespaceUri) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri))); } public IXmlNode CreateAttribute(string name, string value) { return new XAttributeWrapper(new XAttribute(name, value)); } public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value)); } public IXmlElement DocumentElement { get { if (Document.Root == null) return null; return new XElementWrapper(Document.Root); } } public override IXmlNode AppendChild(IXmlNode newChild) { XDeclarationWrapper declarationWrapper = newChild as XDeclarationWrapper; if (declarationWrapper != null) { Document.Declaration = declarationWrapper.Declaration; return declarationWrapper; } else { return base.AppendChild(newChild); } } } internal class XTextWrapper : XObjectWrapper { private XText Text { get { return (XText)WrappedNode; } } public XTextWrapper(XText text) : base(text) { } public override string Value { get { return Text.Value; } set { Text.Value = value; } } public override IXmlNode ParentNode { get { if (Text.Parent == null) return null; return XContainerWrapper.WrapNode(Text.Parent); } } } internal class XCommentWrapper : XObjectWrapper { private XComment Text { get { return (XComment)WrappedNode; } } public XCommentWrapper(XComment text) : base(text) { } public override string Value { get { return Text.Value; } set { Text.Value = value; } } public override IXmlNode ParentNode { get { if (Text.Parent == null) return null; return XContainerWrapper.WrapNode(Text.Parent); } } } internal class XProcessingInstructionWrapper : XObjectWrapper { private XProcessingInstruction ProcessingInstruction { get { return (XProcessingInstruction)WrappedNode; } } public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction) : base(processingInstruction) { } public override string LocalName { get { return ProcessingInstruction.Target; } } public override string Value { get { return ProcessingInstruction.Data; } set { ProcessingInstruction.Data = value; } } } internal class XContainerWrapper : XObjectWrapper { private XContainer Container { get { return (XContainer)WrappedNode; } } public XContainerWrapper(XContainer container) : base(container) { } public override IList<IXmlNode> ChildNodes { get { return Container.Nodes().Select(n => WrapNode(n)).ToList(); } } public override IXmlNode ParentNode { get { if (Container.Parent == null) return null; return WrapNode(Container.Parent); } } internal static IXmlNode WrapNode(XObject node) { if (node is XDocument) return new XDocumentWrapper((XDocument)node); else if (node is XElement) return new XElementWrapper((XElement)node); else if (node is XContainer) return new XContainerWrapper((XContainer)node); else if (node is XProcessingInstruction) return new XProcessingInstructionWrapper((XProcessingInstruction)node); else if (node is XText) return new XTextWrapper((XText)node); else if (node is XComment) return new XCommentWrapper((XComment)node); else if (node is XAttribute) return new XAttributeWrapper((XAttribute)node); else if (node is XDocumentType) return new XDocumentTypeWrapper((XDocumentType)node); else return new XObjectWrapper(node); } public override IXmlNode AppendChild(IXmlNode newChild) { Container.Add(newChild.WrappedNode); return newChild; } } internal class XObjectWrapper : IXmlNode { private readonly XObject _xmlObject; public XObjectWrapper(XObject xmlObject) { _xmlObject = xmlObject; } public object WrappedNode { get { return _xmlObject; } } public virtual XmlNodeType NodeType { get { return _xmlObject.NodeType; } } public virtual string LocalName { get { return null; } } public virtual IList<IXmlNode> ChildNodes { get { return new List<IXmlNode>(); } } public virtual IList<IXmlNode> Attributes { get { return null; } } public virtual IXmlNode ParentNode { get { return null; } } public virtual string Value { get { return null; } set { throw new InvalidOperationException(); } } public virtual IXmlNode AppendChild(IXmlNode newChild) { throw new InvalidOperationException(); } public virtual string NamespaceUri { get { return null; } } } internal class XAttributeWrapper : XObjectWrapper { private XAttribute Attribute { get { return (XAttribute)WrappedNode; } } public XAttributeWrapper(XAttribute attribute) : base(attribute) { } public override string Value { get { return Attribute.Value; } set { Attribute.Value = value; } } public override string LocalName { get { return Attribute.Name.LocalName; } } public override string NamespaceUri { get { return Attribute.Name.NamespaceName; } } public override IXmlNode ParentNode { get { if (Attribute.Parent == null) return null; return XContainerWrapper.WrapNode(Attribute.Parent); } } } internal class XElementWrapper : XContainerWrapper, IXmlElement { private XElement Element { get { return (XElement)WrappedNode; } } public XElementWrapper(XElement element) : base(element) { } public void SetAttributeNode(IXmlNode attribute) { XObjectWrapper wrapper = (XObjectWrapper)attribute; Element.Add(wrapper.WrappedNode); } public override IList<IXmlNode> Attributes { get { return Element.Attributes().Select(a => new XAttributeWrapper(a)).Cast<IXmlNode>().ToList(); } } public override string Value { get { return Element.Value; } set { Element.Value = value; } } public override string LocalName { get { return Element.Name.LocalName; } } public override string NamespaceUri { get { return Element.Name.NamespaceName; } } public string GetPrefixOfNamespace(string namespaceUri) { return Element.GetPrefixOfNamespace(namespaceUri); } public bool IsEmpty { get { return Element.IsEmpty; } } } #endif #endregion /// <summary> /// Converts XML to and from JSON. /// </summary> public class XmlNodeConverter : JsonConverter { private const string TextName = "#text"; private const string CommentName = "#comment"; private const string CDataName = "#cdata-section"; private const string WhitespaceName = "#whitespace"; private const string SignificantWhitespaceName = "#significant-whitespace"; private const string DeclarationName = "?xml"; private const string JsonNamespaceUri = "http://james.newtonking.com/projects/json"; /// <summary> /// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produces multiple root elements. /// </summary> /// <value>The name of the deserialize root element.</value> public string DeserializeRootElementName { get; set; } /// <summary> /// Gets or sets a flag to indicate whether to write the Json.NET array attribute. /// This attribute helps preserve arrays when converting the written XML back to JSON. /// </summary> /// <value><c>true</c> if the array attibute is written to the XML; otherwise, <c>false</c>.</value> public bool WriteArrayAttribute { get; set; } /// <summary> /// Gets or sets a value indicating whether to write the root JSON object. /// </summary> /// <value><c>true</c> if the JSON root object is omitted; otherwise, <c>false</c>.</value> public bool OmitRootObject { get; set; } #region Writing /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="serializer">The calling serializer.</param> /// <param name="value">The value.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { IXmlNode node = WrapXml(value); XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); PushParentNamespaces(node, manager); if (!OmitRootObject) writer.WriteStartObject(); SerializeNode(writer, node, manager, !OmitRootObject); if (!OmitRootObject) writer.WriteEndObject(); } private IXmlNode WrapXml(object value) { #if !NET20 if (value is XObject) return XContainerWrapper.WrapNode((XObject)value); #endif #if !(NETFX_CORE || PORTABLE) if (value is XmlNode) return new XmlNodeWrapper((XmlNode)value); #endif throw new ArgumentException("Value must be an XML object.", "value"); } private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) { List<IXmlNode> parentElements = null; IXmlNode parent = node; while ((parent = parent.ParentNode) != null) { if (parent.NodeType == XmlNodeType.Element) { if (parentElements == null) parentElements = new List<IXmlNode>(); parentElements.Add(parent); } } if (parentElements != null) { parentElements.Reverse(); foreach (IXmlNode parentElement in parentElements) { manager.PushScope(); foreach (IXmlNode attribute in parentElement.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns") manager.AddNamespace(attribute.LocalName, attribute.Value); } } } } private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager) { string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/")) ? null : manager.LookupPrefix(node.NamespaceUri); if (!string.IsNullOrEmpty(prefix)) return prefix + ":" + node.LocalName; else return node.LocalName; } private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager) { switch (node.NodeType) { case XmlNodeType.Attribute: if (node.NamespaceUri == JsonNamespaceUri) return "$" + node.LocalName; else return "@" + ResolveFullName(node, manager); case XmlNodeType.CDATA: return CDataName; case XmlNodeType.Comment: return CommentName; case XmlNodeType.Element: return ResolveFullName(node, manager); case XmlNodeType.ProcessingInstruction: return "?" + ResolveFullName(node, manager); case XmlNodeType.DocumentType: return "!" + ResolveFullName(node, manager); case XmlNodeType.XmlDeclaration: return DeclarationName; case XmlNodeType.SignificantWhitespace: return SignificantWhitespaceName; case XmlNodeType.Text: return TextName; case XmlNodeType.Whitespace: return WhitespaceName; default: throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType); } } private bool IsArray(IXmlNode node) { IXmlNode jsonArrayAttribute = (node.Attributes != null) ? node.Attributes.SingleOrDefault(a => a.LocalName == "Array" && a.NamespaceUri == JsonNamespaceUri) : null; return (jsonArrayAttribute != null && XmlConvert.ToBoolean(jsonArrayAttribute.Value)); } private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { // group nodes together by name Dictionary<string, List<IXmlNode>> nodesGroupedByName = new Dictionary<string, List<IXmlNode>>(); for (int i = 0; i < node.ChildNodes.Count; i++) { IXmlNode childNode = node.ChildNodes[i]; string nodeName = GetPropertyName(childNode, manager); List<IXmlNode> nodes; if (!nodesGroupedByName.TryGetValue(nodeName, out nodes)) { nodes = new List<IXmlNode>(); nodesGroupedByName.Add(nodeName, nodes); } nodes.Add(childNode); } // loop through grouped nodes. write single name instances as normal, // write multiple names together in an array foreach (KeyValuePair<string, List<IXmlNode>> nodeNameGroup in nodesGroupedByName) { List<IXmlNode> groupedNodes = nodeNameGroup.Value; bool writeArray; if (groupedNodes.Count == 1) { writeArray = IsArray(groupedNodes[0]); } else { writeArray = true; } if (!writeArray) { SerializeNode(writer, groupedNodes[0], manager, writePropertyName); } else { string elementNames = nodeNameGroup.Key; if (writePropertyName) writer.WritePropertyName(elementNames); writer.WriteStartArray(); for (int i = 0; i < groupedNodes.Count; i++) { SerializeNode(writer, groupedNodes[i], manager, false); } writer.WriteEndArray(); } } } private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { switch (node.NodeType) { case XmlNodeType.Document: case XmlNodeType.DocumentFragment: SerializeGroupedNodes(writer, node, manager, writePropertyName); break; case XmlNodeType.Element: if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0) { SerializeGroupedNodes(writer, node, manager, false); } else { manager.PushScope(); foreach (IXmlNode attribute in node.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/") { string namespacePrefix = (attribute.LocalName != "xmlns") ? attribute.LocalName : string.Empty; string namespaceUri = attribute.Value; manager.AddNamespace(namespacePrefix, namespaceUri); } } if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text) { // write elements with a single text child as a name value pair writer.WriteValue(node.ChildNodes[0].Value); } else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes)) { IXmlElement element = (IXmlElement)node; // empty element if (element.IsEmpty) writer.WriteNull(); else writer.WriteValue(string.Empty); } else { writer.WriteStartObject(); for (int i = 0; i < node.Attributes.Count; i++) { SerializeNode(writer, node.Attributes[i], manager, true); } SerializeGroupedNodes(writer, node, manager, true); writer.WriteEndObject(); } manager.PopScope(); } break; case XmlNodeType.Comment: if (writePropertyName) writer.WriteComment(node.Value); break; case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri) return; if (node.NamespaceUri == JsonNamespaceUri) { if (node.LocalName == "Array") return; } if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteValue(node.Value); break; case XmlNodeType.XmlDeclaration: IXmlDeclaration declaration = (IXmlDeclaration)node; writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(declaration.Version)) { writer.WritePropertyName("@version"); writer.WriteValue(declaration.Version); } if (!string.IsNullOrEmpty(declaration.Encoding)) { writer.WritePropertyName("@encoding"); writer.WriteValue(declaration.Encoding); } if (!string.IsNullOrEmpty(declaration.Standalone)) { writer.WritePropertyName("@standalone"); writer.WriteValue(declaration.Standalone); } writer.WriteEndObject(); break; case XmlNodeType.DocumentType: IXmlDocumentType documentType = (IXmlDocumentType)node; writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(documentType.Name)) { writer.WritePropertyName("@name"); writer.WriteValue(documentType.Name); } if (!string.IsNullOrEmpty(documentType.Public)) { writer.WritePropertyName("@public"); writer.WriteValue(documentType.Public); } if (!string.IsNullOrEmpty(documentType.System)) { writer.WritePropertyName("@system"); writer.WriteValue(documentType.System); } if (!string.IsNullOrEmpty(documentType.InternalSubset)) { writer.WritePropertyName("@internalSubset"); writer.WriteValue(documentType.InternalSubset); } writer.WriteEndObject(); break; default: throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType); } } #endregion #region Reading /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); IXmlDocument document = null; IXmlNode rootNode = null; #if !NET20 if (typeof(XObject).IsAssignableFrom(objectType)) { if (objectType != typeof(XDocument) && objectType != typeof(XElement)) throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement."); XDocument d = new XDocument(); document = new XDocumentWrapper(d); rootNode = document; } #endif #if !(NETFX_CORE || PORTABLE) if (typeof(XmlNode).IsAssignableFrom(objectType)) { if (objectType != typeof(XmlDocument)) throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments"); XmlDocument d = new XmlDocument(); document = new XmlDocumentWrapper(d); rootNode = document; } #endif if (document == null || rootNode == null) throw new JsonSerializationException("Unexpected type when converting XML: " + objectType); if (reader.TokenType != JsonToken.StartObject) throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object."); if (!string.IsNullOrEmpty(DeserializeRootElementName)) { //rootNode = document.CreateElement(DeserializeRootElementName); //document.AppendChild(rootNode); ReadElement(reader, document, rootNode, DeserializeRootElementName, manager); } else { reader.Read(); DeserializeNode(reader, document, manager, rootNode); } #if !NET20 if (objectType == typeof(XElement)) { XElement element = (XElement)document.DocumentElement.WrappedNode; element.Remove(); return element; } #endif return document.WrappedNode; } private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, string propertyName, IXmlNode currentNode) { switch (propertyName) { case TextName: currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString())); break; case CDataName: currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString())); break; case WhitespaceName: currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString())); break; case SignificantWhitespaceName: currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString())); break; default: // processing instructions and the xml declaration start with ? if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?') { CreateInstruction(reader, document, currentNode, propertyName); } else if (string.Equals(propertyName, "!DOCTYPE", StringComparison.OrdinalIgnoreCase)) { CreateDocumentType(reader, document, currentNode); } else { if (reader.TokenType == JsonToken.StartArray) { // handle nested arrays ReadArrayElements(reader, document, propertyName, currentNode, manager); return; } // have to wait until attributes have been parsed before creating element // attributes may contain namespace info used by the element ReadElement(reader, document, currentNode, propertyName, manager); } break; } } private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { if (string.IsNullOrEmpty(propertyName)) throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML."); Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager); string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); if (propertyName.StartsWith("@")) { string attributeName = propertyName.Substring(1); string attributeValue = reader.Value.ToString(); string attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue) : document.CreateAttribute(attributeName, attributeValue); ((IXmlElement)currentNode).SetAttributeNode(attribute); } else { IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair<string, string> nameValue in attributeNameValues) { string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value) : document.CreateAttribute(nameValue.Key, nameValue.Value); element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.Integer || reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Boolean || reader.TokenType == JsonToken.Date) { element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (reader.TokenType != JsonToken.EndObject) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } manager.RemoveNamespace(string.Empty, manager.DefaultNamespace); } } } private string ConvertTokenToXmlValue(JsonReader reader) { if (reader.TokenType == JsonToken.String) { return reader.Value.ToString(); } else if (reader.TokenType == JsonToken.Integer) { return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Float) { if (reader.Value is decimal) return XmlConvert.ToString((decimal)reader.Value); if (reader.Value is float) return XmlConvert.ToString((float)reader.Value); return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Boolean) { return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Date) { #if !NET20 if (reader.Value is DateTimeOffset) return XmlConvert.ToString((DateTimeOffset)reader.Value); #endif DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture); #if !(NETFX_CORE || PORTABLE) return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind)); #else return XmlConvert.ToString(d); #endif } else if (reader.TokenType == JsonToken.Null) { return null; } else { throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager) { string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(nestedArrayElement); int count = 0; while (reader.Read() && reader.TokenType != JsonToken.EndArray) { DeserializeValue(reader, document, manager, propertyName, nestedArrayElement); count++; } if (WriteArrayAttribute) { AddJsonArrayAttribute(nestedArrayElement, document); } if (count == 1 && WriteArrayAttribute) { IXmlElement arrayElement = nestedArrayElement.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName); AddJsonArrayAttribute(arrayElement, document); } } private void AddJsonArrayAttribute(IXmlElement element, IXmlDocument document) { element.SetAttributeNode(document.CreateAttribute("json:Array", JsonNamespaceUri, "true")); #if !NET20 // linq to xml doesn't automatically include prefixes via the namespace manager if (element is XElementWrapper) { if (element.GetPrefixOfNamespace(JsonNamespaceUri) == null) { element.SetAttributeNode(document.CreateAttribute("xmlns:json", "http://www.w3.org/2000/xmlns/", JsonNamespaceUri)); } } #endif } private Dictionary<string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager) { Dictionary<string, string> attributeNameValues = new Dictionary<string, string>(); bool finishedAttributes = false; bool finishedElement = false; // a string token means the element only has a single text child if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null && reader.TokenType != JsonToken.Boolean && reader.TokenType != JsonToken.Integer && reader.TokenType != JsonToken.Float && reader.TokenType != JsonToken.Date && reader.TokenType != JsonToken.StartConstructor) { // read properties until first non-attribute is encountered while (!finishedAttributes && !finishedElement && reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string attributeName = reader.Value.ToString(); if (!string.IsNullOrEmpty(attributeName)) { char firstChar = attributeName[0]; string attributeValue; switch (firstChar) { case '@': attributeName = attributeName.Substring(1); reader.Read(); attributeValue = ConvertTokenToXmlValue(reader); attributeNameValues.Add(attributeName, attributeValue); string namespacePrefix; if (IsNamespaceAttribute(attributeName, out namespacePrefix)) { manager.AddNamespace(namespacePrefix, attributeValue); } break; case '$': attributeName = attributeName.Substring(1); reader.Read(); attributeValue = reader.Value.ToString(); // check that JsonNamespaceUri is in scope // if it isn't then add it to document and namespace manager string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); if (jsonPrefix == null) { // ensure that the prefix used is free int? i = null; while (manager.LookupNamespace("json" + i) != null) { i = i.GetValueOrDefault() + 1; } jsonPrefix = "json" + i; attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri); manager.AddNamespace(jsonPrefix, JsonNamespaceUri); } attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue); break; default: finishedAttributes = true; break; } } else { finishedAttributes = true; } break; case JsonToken.EndObject: finishedElement = true; break; default: throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType); } } } return attributeNameValues; } private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName) { if (propertyName == DeclarationName) { string version = null; string encoding = null; string standalone = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { switch (reader.Value.ToString()) { case "@version": reader.Read(); version = reader.Value.ToString(); break; case "@encoding": reader.Read(); encoding = reader.Value.ToString(); break; case "@standalone": reader.Read(); standalone = reader.Value.ToString(); break; default: throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); } } IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone); currentNode.AppendChild(declaration); } else { IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString()); currentNode.AppendChild(instruction); } } private void CreateDocumentType(JsonReader reader, IXmlDocument document, IXmlNode currentNode) { string name = null; string publicId = null; string systemId = null; string internalSubset = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { switch (reader.Value.ToString()) { case "@name": reader.Read(); name = reader.Value.ToString(); break; case "@public": reader.Read(); publicId = reader.Value.ToString(); break; case "@system": reader.Read(); systemId = reader.Value.ToString(); break; case "@internalSubset": reader.Read(); internalSubset = reader.Value.ToString(); break; default: throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); } } IXmlNode documentType = document.CreateXmlDocumentType(name, publicId, systemId, internalSubset); currentNode.AppendChild(documentType); } private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager) { string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(elementName, ns) : document.CreateElement(elementName); return element; } private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode) { do { switch (reader.TokenType) { case JsonToken.PropertyName: if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null) throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); string propertyName = reader.Value.ToString(); reader.Read(); if (reader.TokenType == JsonToken.StartArray) { int count = 0; while (reader.Read() && reader.TokenType != JsonToken.EndArray) { DeserializeValue(reader, document, manager, propertyName, currentNode); count++; } if (count == 1 && WriteArrayAttribute) { IXmlElement arrayElement = currentNode.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName); AddJsonArrayAttribute(arrayElement, document); } } else { DeserializeValue(reader, document, manager, propertyName, currentNode); } break; case JsonToken.StartConstructor: string constructorName = reader.Value.ToString(); while (reader.Read() && reader.TokenType != JsonToken.EndConstructor) { DeserializeValue(reader, document, manager, constructorName, currentNode); } break; case JsonToken.Comment: currentNode.AppendChild(document.CreateComment((string)reader.Value)); break; case JsonToken.EndObject: case JsonToken.EndArray: return; default: throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType); } } while (reader.TokenType == JsonToken.PropertyName || reader.Read()); // don't read if current token is a property. token was already read when parsing element attributes } /// <summary> /// Checks if the attributeName is a namespace attribute. /// </summary> /// <param name="attributeName">Attribute name to test.</param> /// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param> /// <returns>True if attribute name is for a namespace attribute, otherwise false.</returns> private bool IsNamespaceAttribute(string attributeName, out string prefix) { if (attributeName.StartsWith("xmlns", StringComparison.Ordinal)) { if (attributeName.Length == 5) { prefix = string.Empty; return true; } else if (attributeName[5] == ':') { prefix = attributeName.Substring(6, attributeName.Length - 6); return true; } } prefix = null; return false; } private IEnumerable<IXmlNode> ValueAttributes(IEnumerable<IXmlNode> c) { return c.Where(a => a.NamespaceUri != JsonNamespaceUri); } #endregion /// <summary> /// Determines whether this instance can convert the specified value type. /// </summary> /// <param name="valueType">Type of the value.</param> /// <returns> /// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type valueType) { #if !NET20 if (typeof(XObject).IsAssignableFrom(valueType)) return true; #endif #if !(NETFX_CORE || PORTABLE) if (typeof(XmlNode).IsAssignableFrom(valueType)) return true; #endif return false; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Xunit; namespace System.Threading.Tasks.Dataflow.Tests { public class DebugAttributeTests { [Fact] public void TestDebuggerDisplaysAndTypeProxies() { // Test both canceled and non-canceled foreach (var ct in new[] { new CancellationToken(false), new CancellationToken(true) }) { // Some blocks have different code paths for whether they're greedy or not. // This helps with code-coverage. var dboBuffering = new DataflowBlockOptions(); var dboNoBuffering = new DataflowBlockOptions() { BoundedCapacity = 1 }; var dboExBuffering = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2, CancellationToken = ct }; var dboExSpsc = new ExecutionDataflowBlockOptions { SingleProducerConstrained = true }; var dboExNoBuffering = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2, BoundedCapacity = 1, CancellationToken = ct }; var dboGroupGreedy = new GroupingDataflowBlockOptions(); var dboGroupNonGreedy = new GroupingDataflowBlockOptions { Greedy = false }; // Item1 == test DebuggerDisplay, Item2 == test DebuggerTypeProxy, Item3 == object var objectsToTest = new Tuple<bool, bool, object>[] { // Primary Blocks // (Don't test DebuggerTypeProxy on instances that may internally have async operations in progress) Tuple.Create<bool,bool,object>(true, true, new ActionBlock<int>(i => {})), Tuple.Create<bool,bool,object>(true, true, new ActionBlock<int>(i => {}, dboExBuffering)), Tuple.Create<bool,bool,object>(true, true, new ActionBlock<int>(i => {}, dboExSpsc)), Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new ActionBlock<int>(i => {}, dboExNoBuffering), 2)), Tuple.Create<bool,bool,object>(true, true, new TransformBlock<int,int>(i => i)), Tuple.Create<bool,bool,object>(true, true, new TransformBlock<int,int>(i => i, dboExBuffering)), Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new TransformBlock<int,int>(i => i, dboExNoBuffering),2)), Tuple.Create<bool,bool,object>(true, true, new TransformManyBlock<int,int>(i => new [] { i })), Tuple.Create<bool,bool,object>(true, true, new TransformManyBlock<int,int>(i => new [] { i }, dboExBuffering)), Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new TransformManyBlock<int,int>(i => new [] { i }, dboExNoBuffering),2)), Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>()), Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>(new DataflowBlockOptions() { NameFormat = "none" })), Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>(new DataflowBlockOptions() { NameFormat = "foo={0}, bar={1}" })), Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>(new DataflowBlockOptions() { NameFormat = "foo={0}, bar={1}, kaboom={2}" })), Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>(dboBuffering)), Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 10 }), 20)), Tuple.Create<bool,bool,object>(true, true, new BroadcastBlock<int>(i => i)), Tuple.Create<bool,bool,object>(true, true, new BroadcastBlock<int>(i => i, dboBuffering)), Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new BroadcastBlock<int>(i => i, dboNoBuffering), 20)), Tuple.Create<bool,bool,object>(true, true, new WriteOnceBlock<int>(i => i)), Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new WriteOnceBlock<int>(i => i), 1)), Tuple.Create<bool,bool,object>(true, true, new WriteOnceBlock<int>(i => i, dboBuffering)), Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>()), Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>(dboGroupGreedy)), Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>(dboGroupNonGreedy)), Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int,int>()), Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int,int>(dboGroupGreedy)), Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int,int>(dboGroupNonGreedy)), Tuple.Create<bool,bool,object>(true, true, new BatchedJoinBlock<int,int>(42)), Tuple.Create<bool,bool,object>(true, true, new BatchedJoinBlock<int,int>(42, dboGroupGreedy)), Tuple.Create<bool,bool,object>(true, true, new BatchedJoinBlock<int,int,int>(42, dboGroupGreedy)), Tuple.Create<bool,bool,object>(true, true, new BatchBlock<int>(42)), Tuple.Create<bool,bool,object>(true, true, new BatchBlock<int>(42, dboGroupGreedy)), Tuple.Create<bool,bool,object>(true, true, new BatchBlock<int>(42, dboGroupNonGreedy)), Tuple.Create<bool,bool,object>(true, true, DataflowBlock.Encapsulate<int,int>(new BufferBlock<int>(),new BufferBlock<int>())), Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>().AsObservable()), // Supporting and Internal Types Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new ActionBlock<int>(i => {}, dboExBuffering), "_defaultTarget")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new ActionBlock<int>(i => {}, dboExNoBuffering), "_defaultTarget")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(DebuggerAttributes.GetFieldValue(new ActionBlock<int>(i => {}), "_defaultTarget"), "_messages")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new ActionBlock<int>(i => {}, dboExSpsc), "_spscTarget")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(DebuggerAttributes.GetFieldValue(new ActionBlock<int>(i => {}, dboExSpsc), "_spscTarget"), "_messages")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BufferBlock<int>(), "_source")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 10 }), "_source")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new TransformBlock<int,int>(i => i, dboExBuffering), "_source")), Tuple.Create<bool,bool,object>(true, true, DebuggerAttributes.GetFieldValue(new TransformBlock<int,int>(i => i, dboExNoBuffering), "_reorderingBuffer")), Tuple.Create<bool,bool,object>(true, true, DebuggerAttributes.GetFieldValue(DebuggerAttributes.GetFieldValue(new TransformBlock<int,int>(i => i, dboExBuffering), "_source"), "_targetRegistry")), Tuple.Create<bool,bool,object>(true, true, DebuggerAttributes.GetFieldValue(DebuggerAttributes.GetFieldValue(WithLinkedTarget<TransformBlock<int,int>,int>(new TransformBlock<int,int>(i => i, dboExNoBuffering)), "_source"), "_targetRegistry")), Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>().Target1), Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>(dboGroupGreedy).Target1), Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>(dboGroupNonGreedy).Target1), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new JoinBlock<int,int>().Target1, "_sharedResources")), Tuple.Create<bool,bool,object>(true, true, new BatchedJoinBlock<int,int>(42).Target1), Tuple.Create<bool,bool,object>(true, true, new BatchedJoinBlock<int,int>(42, dboGroupGreedy).Target1), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BatchBlock<int>(42), "_target")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BatchBlock<int>(42, dboGroupGreedy), "_target")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BatchBlock<int>(42, dboGroupNonGreedy), "_target")), Tuple.Create<bool,bool,object>(true, false, new BufferBlock<int>().LinkTo(new ActionBlock<int>(i => {}))), // ActionOnDispose Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BroadcastBlock<int>(i => i), "_source")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BroadcastBlock<int>(i => i, dboGroupGreedy), "_source")), Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BroadcastBlock<int>(i => i, dboGroupNonGreedy), "_source")), Tuple.Create<bool,bool,object>(true, true, CreateNopLinkSource<int>()), Tuple.Create<bool,bool,object>(true, true, CreateFilteringSource<int>()), Tuple.Create<bool,bool,object>(true, true, CreateSendSource<int>()), Tuple.Create<bool,bool,object>(true, false, CreateReceiveTarget<int>()), Tuple.Create<bool,bool,object>(true, false, CreateOutputAvailableTarget()), Tuple.Create<bool,bool,object>(true, false, CreateChooseTarget<int>()), Tuple.Create<bool,bool,object>(true, false, new BufferBlock<int>().AsObservable().Subscribe(DataflowBlock.NullTarget<int>().AsObserver())), // Other Tuple.Create<bool,bool,object>(true, false, new DataflowMessageHeader(1)), }; // Test all DDAs and DTPAs foreach (var obj in objectsToTest) { if (obj.Item1) DebuggerAttributes.ValidateDebuggerDisplayReferences(obj.Item3); if (obj.Item2) DebuggerAttributes.ValidateDebuggerTypeProxyProperties(obj.Item3); } } } private static object SendAsyncMessages<T>(ITargetBlock<T> target, int numMessages) { for (int i = 0; i < numMessages; i++) target.SendAsync(default(T)); return target; } private static TBlock WithLinkedTarget<TBlock, T>(TBlock block) where TBlock : ISourceBlock<T> { block.LinkTo(DataflowBlock.NullTarget<T>()); return block; } private static ISourceBlock<T> CreateNopLinkSource<T>() { var bb = new BufferBlock<T>(); var sos = new StoreOfferingSource<T>(); using (bb.LinkTo(sos)) bb.LinkTo(sos); bb.Post(default(T)); return sos.GetOfferingSource(); } private static ISourceBlock<T> CreateFilteringSource<T>() { var bb = new BufferBlock<T>(); var sos = new StoreOfferingSource<T>(); bb.LinkTo(sos, i => true); bb.Post(default(T)); return sos.GetOfferingSource(); } private static ITargetBlock<T> CreateReceiveTarget<T>() { var slt = new StoreLinkedTarget<T>(); slt.ReceiveAsync(); return slt.GetLinkedTarget(); } private static ITargetBlock<bool> CreateOutputAvailableTarget() { var slt = new StoreLinkedTarget<bool>(); slt.OutputAvailableAsync(); return slt.GetLinkedTarget(); } private static ISourceBlock<T> CreateSendSource<T>() { var sos = new StoreOfferingSource<T>(); sos.SendAsync(default(T)); return sos.GetOfferingSource(); } private static ITargetBlock<T> CreateChooseTarget<T>() { var slt = new StoreLinkedTarget<T>(); DataflowBlock.Choose(slt, i => { }, new BufferBlock<T>(), i => { }); return slt.GetLinkedTarget(); } private class StoreOfferingSource<T> : ITargetBlock<T> { private TaskCompletionSource<ISourceBlock<T>> _m_offeringSource = new TaskCompletionSource<ISourceBlock<T>>(); public ISourceBlock<T> GetOfferingSource() { return _m_offeringSource.Task.Result; } public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, bool consumeToAccept) { if (source != null) { _m_offeringSource.TrySetResult(source); return DataflowMessageStatus.Postponed; } return DataflowMessageStatus.Declined; } public bool Post(T item) { return false; } public Task Completion { get { return null; } } public void Complete() { } void IDataflowBlock.Fault(Exception exception) { throw new NotSupportedException(); } } private class StoreLinkedTarget<T> : IReceivableSourceBlock<T> { private TaskCompletionSource<ITargetBlock<T>> _m_linkedTarget = new TaskCompletionSource<ITargetBlock<T>>(); public ITargetBlock<T> GetLinkedTarget() { return _m_linkedTarget.Task.Result; } public IDisposable LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { _m_linkedTarget.TrySetResult(target); return new NopDisposable(); } private class NopDisposable : IDisposable { public void Dispose() { } } public bool TryReceive(Predicate<T> filter, out T item) { item = default(T); return false; } public bool TryReceiveAll(out System.Collections.Generic.IList<T> items) { items = default(System.Collections.Generic.IList<T>); return false; } public T ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out Boolean messageConsumed) { messageConsumed = true; return default(T); } public bool ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { return false; } public void ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { } public Task Completion { get { return null; } } public void Complete() { } void IDataflowBlock.Fault(Exception exception) { throw new NotSupportedException(); } } } }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; namespace Zenject.ReflectionBaking.Mono.Cecil.PE { class ByteBuffer { internal byte [] buffer; internal int length; internal int position; public ByteBuffer () { this.buffer = Empty<byte>.Array; } public ByteBuffer (int length) { this.buffer = new byte [length]; } public ByteBuffer (byte [] buffer) { this.buffer = buffer ?? Empty<byte>.Array; this.length = this.buffer.Length; } public void Reset (byte [] buffer) { this.buffer = buffer ?? Empty<byte>.Array; this.length = this.buffer.Length; } public void Advance (int length) { position += length; } public byte ReadByte () { return buffer [position++]; } public sbyte ReadSByte () { return (sbyte) ReadByte (); } public byte [] ReadBytes (int length) { var bytes = new byte [length]; Buffer.BlockCopy (buffer, position, bytes, 0, length); position += length; return bytes; } public ushort ReadUInt16 () { ushort value = (ushort) (buffer [position] | (buffer [position + 1] << 8)); position += 2; return value; } public short ReadInt16 () { return (short) ReadUInt16 (); } public uint ReadUInt32 () { uint value = (uint) (buffer [position] | (buffer [position + 1] << 8) | (buffer [position + 2] << 16) | (buffer [position + 3] << 24)); position += 4; return value; } public int ReadInt32 () { return (int) ReadUInt32 (); } public ulong ReadUInt64 () { uint low = ReadUInt32 (); uint high = ReadUInt32 (); return (((ulong) high) << 32) | low; } public long ReadInt64 () { return (long) ReadUInt64 (); } public uint ReadCompressedUInt32 () { byte first = ReadByte (); if ((first & 0x80) == 0) return first; if ((first & 0x40) == 0) return ((uint) (first & ~0x80) << 8) | ReadByte (); return ((uint) (first & ~0xc0) << 24) | (uint) ReadByte () << 16 | (uint) ReadByte () << 8 | ReadByte (); } public int ReadCompressedInt32 () { var value = (int) (ReadCompressedUInt32 () >> 1); if ((value & 1) == 0) return value; if (value < 0x40) return value - 0x40; if (value < 0x2000) return value - 0x2000; if (value < 0x10000000) return value - 0x10000000; return value - 0x20000000; } public float ReadSingle () { if (!BitConverter.IsLittleEndian) { var bytes = ReadBytes (4); Array.Reverse (bytes); return BitConverter.ToSingle (bytes, 0); } float value = BitConverter.ToSingle (buffer, position); position += 4; return value; } public double ReadDouble () { if (!BitConverter.IsLittleEndian) { var bytes = ReadBytes (8); Array.Reverse (bytes); return BitConverter.ToDouble (bytes, 0); } double value = BitConverter.ToDouble (buffer, position); position += 8; return value; } #if !READ_ONLY public void WriteByte (byte value) { if (position == buffer.Length) Grow (1); buffer [position++] = value; if (position > length) length = position; } public void WriteSByte (sbyte value) { WriteByte ((byte) value); } public void WriteUInt16 (ushort value) { if (position + 2 > buffer.Length) Grow (2); buffer [position++] = (byte) value; buffer [position++] = (byte) (value >> 8); if (position > length) length = position; } public void WriteInt16 (short value) { WriteUInt16 ((ushort) value); } public void WriteUInt32 (uint value) { if (position + 4 > buffer.Length) Grow (4); buffer [position++] = (byte) value; buffer [position++] = (byte) (value >> 8); buffer [position++] = (byte) (value >> 16); buffer [position++] = (byte) (value >> 24); if (position > length) length = position; } public void WriteInt32 (int value) { WriteUInt32 ((uint) value); } public void WriteUInt64 (ulong value) { if (position + 8 > buffer.Length) Grow (8); buffer [position++] = (byte) value; buffer [position++] = (byte) (value >> 8); buffer [position++] = (byte) (value >> 16); buffer [position++] = (byte) (value >> 24); buffer [position++] = (byte) (value >> 32); buffer [position++] = (byte) (value >> 40); buffer [position++] = (byte) (value >> 48); buffer [position++] = (byte) (value >> 56); if (position > length) length = position; } public void WriteInt64 (long value) { WriteUInt64 ((ulong) value); } public void WriteCompressedUInt32 (uint value) { if (value < 0x80) WriteByte ((byte) value); else if (value < 0x4000) { WriteByte ((byte) (0x80 | (value >> 8))); WriteByte ((byte) (value & 0xff)); } else { WriteByte ((byte) ((value >> 24) | 0xc0)); WriteByte ((byte) ((value >> 16) & 0xff)); WriteByte ((byte) ((value >> 8) & 0xff)); WriteByte ((byte) (value & 0xff)); } } public void WriteCompressedInt32 (int value) { if (value >= 0) { WriteCompressedUInt32 ((uint) (value << 1)); return; } if (value > -0x40) value = 0x40 + value; else if (value >= -0x2000) value = 0x2000 + value; else if (value >= -0x20000000) value = 0x20000000 + value; WriteCompressedUInt32 ((uint) ((value << 1) | 1)); } public void WriteBytes (byte [] bytes) { var length = bytes.Length; if (position + length > buffer.Length) Grow (length); Buffer.BlockCopy (bytes, 0, buffer, position, length); position += length; if (position > this.length) this.length = position; } public void WriteBytes (int length) { if (position + length > buffer.Length) Grow (length); position += length; if (position > this.length) this.length = position; } public void WriteBytes (ByteBuffer buffer) { if (position + buffer.length > this.buffer.Length) Grow (buffer.length); Buffer.BlockCopy (buffer.buffer, 0, this.buffer, position, buffer.length); position += buffer.length; if (position > this.length) this.length = position; } public void WriteSingle (float value) { var bytes = BitConverter.GetBytes (value); if (!BitConverter.IsLittleEndian) Array.Reverse (bytes); WriteBytes (bytes); } public void WriteDouble (double value) { var bytes = BitConverter.GetBytes (value); if (!BitConverter.IsLittleEndian) Array.Reverse (bytes); WriteBytes (bytes); } void Grow (int desired) { var current = this.buffer; var current_length = current.Length; var buffer = new byte [System.Math.Max (current_length + desired, current_length * 2)]; Buffer.BlockCopy (current, 0, buffer, 0, current_length); this.buffer = buffer; } #endif } }
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using SmugMug.v2.Authentication; namespace SmugMug.v2.Types { public partial class ImageEntity : SmugMugEntity { private long _altitude; private string _archivedMD5; private long _archivedSize; private string _archivedUri; private bool _canEdit; private string _caption; private bool _collectable; private DateTime _date; private bool _eZProject; private string _fileName; private string _format; private CaptionEntity _formattedValues; private bool _hidden; private string _imageKey; private bool _isArchive; private bool _isVideo; private string[] _keywordArray; private string _keywords; private DateTime _lastUpdated; private decimal _latitude; private decimal _longitude; private long _originalHeight; private long _originalSize; private long _originalWidth; private bool _processing; private bool _protected; private string _thumbnailUrl; private string _title; private string _uploadKey; private WatermarkEnum _watermark; private bool _watermarked; private string _webUri; public long Altitude { get { return _altitude; } set { if (_altitude != value) { NotifyPropertyValueChanged("Altitude", oldValue:_altitude, newValue: value); _altitude = value; } } } public string ArchivedMD5 { get { return _archivedMD5; } set { if (_archivedMD5 != value) { NotifyPropertyValueChanged("ArchivedMD5", oldValue:_archivedMD5, newValue: value); _archivedMD5 = value; } } } public long ArchivedSize { get { return _archivedSize; } set { if (_archivedSize != value) { NotifyPropertyValueChanged("ArchivedSize", oldValue:_archivedSize, newValue: value); _archivedSize = value; } } } public string ArchivedUri { get { return _archivedUri; } set { if (_archivedUri != value) { NotifyPropertyValueChanged("ArchivedUri", oldValue:_archivedUri, newValue: value); _archivedUri = value; } } } public bool CanEdit { get { return _canEdit; } set { if (_canEdit != value) { NotifyPropertyValueChanged("CanEdit", oldValue:_canEdit, newValue: value); _canEdit = value; } } } public string Caption { get { return _caption; } set { if (_caption != value) { NotifyPropertyValueChanged("Caption", oldValue:_caption, newValue: value); _caption = value; } } } public bool Collectable { get { return _collectable; } set { if (_collectable != value) { NotifyPropertyValueChanged("Collectable", oldValue:_collectable, newValue: value); _collectable = value; } } } public DateTime Date { get { return _date; } set { if (_date != value) { NotifyPropertyValueChanged("Date", oldValue:_date, newValue: value); _date = value; } } } public bool EZProject { get { return _eZProject; } set { if (_eZProject != value) { NotifyPropertyValueChanged("EZProject", oldValue:_eZProject, newValue: value); _eZProject = value; } } } public string FileName { get { return _fileName; } set { if (_fileName != value) { NotifyPropertyValueChanged("FileName", oldValue:_fileName, newValue: value); _fileName = value; } } } public string Format { get { return _format; } set { if (_format != value) { NotifyPropertyValueChanged("Format", oldValue:_format, newValue: value); _format = value; } } } public CaptionEntity FormattedValues { get { return _formattedValues; } set { if (_formattedValues != value) { NotifyPropertyValueChanged("FormattedValues", oldValue:_formattedValues, newValue: value); _formattedValues = value; } } } public bool Hidden { get { return _hidden; } set { if (_hidden != value) { NotifyPropertyValueChanged("Hidden", oldValue:_hidden, newValue: value); _hidden = value; } } } public string ImageKey { get { return _imageKey; } set { if (_imageKey != value) { NotifyPropertyValueChanged("ImageKey", oldValue:_imageKey, newValue: value); _imageKey = value; } } } public bool IsArchive { get { return _isArchive; } set { if (_isArchive != value) { NotifyPropertyValueChanged("IsArchive", oldValue:_isArchive, newValue: value); _isArchive = value; } } } public bool IsVideo { get { return _isVideo; } set { if (_isVideo != value) { NotifyPropertyValueChanged("IsVideo", oldValue:_isVideo, newValue: value); _isVideo = value; } } } public string[] KeywordArray { get { return _keywordArray; } set { if (_keywordArray != value) { NotifyPropertyValueChanged("KeywordArray", oldValue:_keywordArray, newValue: value); _keywordArray = value; } } } public string Keywords { get { return _keywords; } set { if (_keywords != value) { NotifyPropertyValueChanged("Keywords", oldValue:_keywords, newValue: value); _keywords = value; } } } public DateTime LastUpdated { get { return _lastUpdated; } set { if (_lastUpdated != value) { NotifyPropertyValueChanged("LastUpdated", oldValue:_lastUpdated, newValue: value); _lastUpdated = value; } } } public decimal Latitude { get { return _latitude; } set { if (_latitude != value) { NotifyPropertyValueChanged("Latitude", oldValue:_latitude, newValue: value); _latitude = value; } } } public decimal Longitude { get { return _longitude; } set { if (_longitude != value) { NotifyPropertyValueChanged("Longitude", oldValue:_longitude, newValue: value); _longitude = value; } } } public long OriginalHeight { get { return _originalHeight; } set { if (_originalHeight != value) { NotifyPropertyValueChanged("OriginalHeight", oldValue:_originalHeight, newValue: value); _originalHeight = value; } } } public long OriginalSize { get { return _originalSize; } set { if (_originalSize != value) { NotifyPropertyValueChanged("OriginalSize", oldValue:_originalSize, newValue: value); _originalSize = value; } } } public long OriginalWidth { get { return _originalWidth; } set { if (_originalWidth != value) { NotifyPropertyValueChanged("OriginalWidth", oldValue:_originalWidth, newValue: value); _originalWidth = value; } } } public bool Processing { get { return _processing; } set { if (_processing != value) { NotifyPropertyValueChanged("Processing", oldValue:_processing, newValue: value); _processing = value; } } } public bool Protected { get { return _protected; } set { if (_protected != value) { NotifyPropertyValueChanged("Protected", oldValue:_protected, newValue: value); _protected = value; } } } public string ThumbnailUrl { get { return _thumbnailUrl; } set { if (_thumbnailUrl != value) { NotifyPropertyValueChanged("ThumbnailUrl", oldValue:_thumbnailUrl, newValue: value); _thumbnailUrl = value; } } } public string Title { get { return _title; } set { if (_title != value) { NotifyPropertyValueChanged("Title", oldValue:_title, newValue: value); _title = value; } } } public string UploadKey { get { return _uploadKey; } set { if (_uploadKey != value) { NotifyPropertyValueChanged("UploadKey", oldValue:_uploadKey, newValue: value); _uploadKey = value; } } } public WatermarkEnum Watermark { get { return _watermark; } set { if (_watermark != value) { NotifyPropertyValueChanged("Watermark", oldValue:_watermark, newValue: value); _watermark = value; } } } public bool Watermarked { get { return _watermarked; } set { if (_watermarked != value) { NotifyPropertyValueChanged("Watermarked", oldValue:_watermarked, newValue: value); _watermarked = value; } } } public string WebUri { get { return _webUri; } set { if (_webUri != value) { NotifyPropertyValueChanged("WebUri", oldValue:_webUri, newValue: value); _webUri = value; } } } } }
// // 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.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Resources { /// <summary> /// Operations for managing resource groups. /// </summary> internal partial class ResourceGroupOperations : IServiceOperations<ResourceManagementClient>, IResourceGroupOperations { /// <summary> /// Initializes a new instance of the ResourceGroupOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ResourceGroupOperations(ResourceManagementClient client) { this._client = client; } private ResourceManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Resources.ResourceManagementClient. /// </summary> public ResourceManagementClient Client { get { return this._client; } } /// <summary> /// Begin deleting resource group.To determine whether the operation /// has finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group to be deleted. The name is /// case insensitive. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> BeginDeletingAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); Tracing.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "?"; url = url + "api-version=2014-04-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } 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.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Checks whether resource group exists. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group to check. The name is case /// insensitive. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Resource group information. /// </returns> public async Task<ResourceGroupExistsResult> CheckExistenceAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); Tracing.Enter(invocationId, this, "CheckExistenceAsync", tracingParameters); } // Construct URL string url = "subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "?"; url = url + "api-version=2014-04-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Head; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.NotFound) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ResourceGroupExistsResult result = null; result = new ResourceGroupExistsResult(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.NoContent) { result.Exists = true; } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create a resource group. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group to be created or updated. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create or update resource /// group service operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Resource group information. /// </returns> public async Task<ResourceGroupCreateOrUpdateResult> CreateOrUpdateAsync(string resourceGroupName, BasicResourceGroup parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "?"; url = url + "api-version=2014-04-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject basicResourceGroupValue = new JObject(); requestDoc = basicResourceGroupValue; basicResourceGroupValue["location"] = parameters.Location; if (parameters.Properties != null) { basicResourceGroupValue["properties"] = JObject.Parse(parameters.Properties); } if (parameters.Tags != null) { if (parameters.Tags is ILazyCollection == false || ((ILazyCollection)parameters.Tags).IsInitialized) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } basicResourceGroupValue["tags"] = tagsDictionary; } } if (parameters.ProvisioningState != null) { basicResourceGroupValue["provisioningState"] = parameters.ProvisioningState; } requestContent = requestDoc.ToString(Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ResourceGroupCreateOrUpdateResult result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceGroupCreateOrUpdateResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceGroup resourceGroupInstance = new ResourceGroup(); result.ResourceGroup = resourceGroupInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceGroupInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceGroupInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); resourceGroupInstance.ProvisioningState = provisioningStateInstance; } } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceGroupInstance.Location = locationInstance; } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { string propertiesInstance = propertiesValue2.ToString(Formatting.Indented); resourceGroupInstance.Properties = propertiesInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); resourceGroupInstance.Tags.Add(tagsKey2, tagsValue2); } } JToken provisioningStateValue2 = responseDoc["provisioningState"]; if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null) { string provisioningStateInstance2 = ((string)provisioningStateValue2); resourceGroupInstance.ProvisioningState = provisioningStateInstance2; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Delete resource group and all of its resources. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group to be deleted. The name is /// case insensitive. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<OperationResponse> DeleteAsync(string resourceGroupName, CancellationToken cancellationToken) { ResourceManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResponse response = await client.ResourceGroups.BeginDeletingAsync(resourceGroupName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != Microsoft.WindowsAzure.OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } /// <summary> /// Get a resource group. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group to get. The name is case /// insensitive. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Resource group information. /// </returns> public async Task<ResourceGroupGetResult> GetAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "?"; url = url + "api-version=2014-04-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ResourceGroupGetResult result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceGroupGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceGroup resourceGroupInstance = new ResourceGroup(); result.ResourceGroup = resourceGroupInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceGroupInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceGroupInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); resourceGroupInstance.ProvisioningState = provisioningStateInstance; } } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceGroupInstance.Location = locationInstance; } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { string propertiesInstance = propertiesValue2.ToString(Formatting.Indented); resourceGroupInstance.Properties = propertiesInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); resourceGroupInstance.Tags.Add(tagsKey, tagsValue); } } JToken provisioningStateValue2 = responseDoc["provisioningState"]; if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null) { string provisioningStateInstance2 = ((string)provisioningStateValue2); resourceGroupInstance.ProvisioningState = provisioningStateInstance2; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a collection of resource groups. /// </summary> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all resource /// groups. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of resource groups. /// </returns> public async Task<ResourceGroupListResult> ListAsync(ResourceGroupListParameters parameters, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups?"; bool appendFilter = true; if (parameters != null && parameters.TagName != null) { appendFilter = false; url = url + "$filter=tagname eq '" + Uri.EscapeDataString(parameters.TagName != null ? parameters.TagName.Trim() : "") + "'"; } if (parameters != null && parameters.TagValue != null) { if (appendFilter == true) { appendFilter = false; url = url + "$filter="; } else { url = url + " and "; } url = url + "tagvalue eq '" + Uri.EscapeDataString(parameters.TagValue != null ? parameters.TagValue.Trim() : "") + "'"; } if (parameters != null && parameters.Top != null) { url = url + "&$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString()); } url = url + "&api-version=2014-04-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ResourceGroupListResult result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceGroupListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ResourceGroup resourceGroupJsonFormatInstance = new ResourceGroup(); result.ResourceGroups.Add(resourceGroupJsonFormatInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceGroupJsonFormatInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceGroupJsonFormatInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance; } } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceGroupJsonFormatInstance.Location = locationInstance; } JToken propertiesValue2 = valueValue["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { string propertiesInstance = propertiesValue2.ToString(Formatting.Indented); resourceGroupJsonFormatInstance.Properties = propertiesInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); resourceGroupJsonFormatInstance.Tags.Add(tagsKey, tagsValue); } } JToken provisioningStateValue2 = valueValue["provisioningState"]; if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null) { string provisioningStateInstance2 = ((string)provisioningStateValue2); resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance2; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of resource groups. /// </returns> public async Task<ResourceGroupListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); Tracing.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = nextLink.Trim(); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ResourceGroupListResult result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceGroupListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ResourceGroup resourceGroupJsonFormatInstance = new ResourceGroup(); result.ResourceGroups.Add(resourceGroupJsonFormatInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceGroupJsonFormatInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceGroupJsonFormatInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance; } } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceGroupJsonFormatInstance.Location = locationInstance; } JToken propertiesValue2 = valueValue["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { string propertiesInstance = propertiesValue2.ToString(Formatting.Indented); resourceGroupJsonFormatInstance.Properties = propertiesInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); resourceGroupJsonFormatInstance.Tags.Add(tagsKey, tagsValue); } } JToken provisioningStateValue2 = valueValue["provisioningState"]; if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null) { string provisioningStateInstance2 = ((string)provisioningStateValue2); resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance2; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Resource groups can be updated through a simple PATCH operation to /// a group address. The format of the request is the same as that for /// creating a resource groups, though if a field is unspecified /// current value will be carried over. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group to be created or updated. /// The name is case insensitive. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the update state resource group /// service operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Resource group information. /// </returns> public async Task<ResourceGroupPatchResult> PatchAsync(string resourceGroupName, BasicResourceGroup parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "PatchAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "?"; url = url + "api-version=2014-04-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject basicResourceGroupValue = new JObject(); requestDoc = basicResourceGroupValue; basicResourceGroupValue["location"] = parameters.Location; if (parameters.Properties != null) { basicResourceGroupValue["properties"] = JObject.Parse(parameters.Properties); } if (parameters.Tags != null) { if (parameters.Tags is ILazyCollection == false || ((ILazyCollection)parameters.Tags).IsInitialized) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } basicResourceGroupValue["tags"] = tagsDictionary; } } if (parameters.ProvisioningState != null) { basicResourceGroupValue["provisioningState"] = parameters.ProvisioningState; } requestContent = requestDoc.ToString(Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ResourceGroupPatchResult result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceGroupPatchResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceGroup resourceGroupInstance = new ResourceGroup(); result.ResourceGroup = resourceGroupInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceGroupInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceGroupInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); resourceGroupInstance.ProvisioningState = provisioningStateInstance; } } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceGroupInstance.Location = locationInstance; } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { string propertiesInstance = propertiesValue2.ToString(Formatting.Indented); resourceGroupInstance.Properties = propertiesInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); resourceGroupInstance.Tags.Add(tagsKey2, tagsValue2); } } JToken provisioningStateValue2 = responseDoc["provisioningState"]; if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null) { string provisioningStateInstance2 = ((string)provisioningStateValue2); resourceGroupInstance.ProvisioningState = provisioningStateInstance2; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// 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. namespace IdentityBase.EntityFramework.IntegrationTests.Stores { using System; using System.Collections.Generic; using System.Linq; using IdentityBase.EntityFramework.DbContexts; using IdentityBase.EntityFramework.Mappers; using IdentityBase.EntityFramework.Configuration; using IdentityBase.EntityFramework.Stores; using IdentityModel; using IdentityServer4.Models; using IdentityServer4.Stores; using Microsoft.EntityFrameworkCore; using ServiceBase.Logging; using Xunit; public class ScopeStoreTests : IClassFixture<DatabaseProviderFixture<ConfigurationDbContext>> { private static readonly EntityFrameworkOptions StoreOptions = new EntityFrameworkOptions(); public static readonly TheoryData<DbContextOptions<ConfigurationDbContext>> TestDatabaseProviders = new TheoryData<DbContextOptions<ConfigurationDbContext>> { DatabaseProviderBuilder.BuildInMemory<ConfigurationDbContext>( nameof(ScopeStoreTests), StoreOptions), DatabaseProviderBuilder.BuildSqlite<ConfigurationDbContext>( nameof(ScopeStoreTests), StoreOptions), DatabaseProviderBuilder.BuildSqlServer<ConfigurationDbContext>( nameof(ScopeStoreTests), StoreOptions) }; public ScopeStoreTests( DatabaseProviderFixture<ConfigurationDbContext> fixture) { fixture.Options = TestDatabaseProviders .SelectMany(x => x .Select(y => (DbContextOptions<ConfigurationDbContext>)y)) .ToList(); fixture.StoreOptions = StoreOptions; } private static IdentityResource CreateIdentityTestResource() { return new IdentityResource() { Name = Guid.NewGuid().ToString(), DisplayName = Guid.NewGuid().ToString(), Description = Guid.NewGuid().ToString(), ShowInDiscoveryDocument = true, UserClaims = { JwtClaimTypes.Subject, JwtClaimTypes.Name, } }; } private static ApiResource CreateApiTestResource() { return new ApiResource() { Name = Guid.NewGuid().ToString(), ApiSecrets = new List<Secret> { new Secret("secret".Sha256()) }, Scopes = new List<Scope> { new Scope { Name = Guid.NewGuid().ToString(), UserClaims = {Guid.NewGuid().ToString()} } }, UserClaims = { Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), } }; } [Theory, MemberData(nameof(TestDatabaseProviders))] public void FindResourcesAsync_WhenResourcesExist_ExpectResourcesReturned( DbContextOptions<ConfigurationDbContext> options) { var testIdentityResource = CreateIdentityTestResource(); var testApiResource = CreateApiTestResource(); using (var context = new ConfigurationDbContext(options, StoreOptions)) { context.IdentityResources.Add(testIdentityResource.ToEntity()); context.ApiResources.Add(testApiResource.ToEntity()); context.SaveChanges(); } Resources resources; using (var context = new ConfigurationDbContext(options, StoreOptions)) { var store = new ResourceStore( context, NullLogger<ResourceStore>.Create() ); resources = store.FindResourcesByScopeAsync(new List<string> { testIdentityResource.Name, testApiResource.Scopes.First().Name }).Result; } Assert.NotNull(resources); Assert.NotNull(resources.IdentityResources); Assert.NotEmpty(resources.IdentityResources); Assert.NotNull(resources.ApiResources); Assert.NotEmpty(resources.ApiResources); Assert.NotNull(resources.IdentityResources .FirstOrDefault(x => x.Name == testIdentityResource.Name)); Assert.NotNull(resources.ApiResources .FirstOrDefault(x => x.Name == testApiResource.Name)); } [Theory, MemberData(nameof(TestDatabaseProviders))] public void FindResourcesAsync_WhenResourcesExist_ExpectOnlyResourcesRequestedReturned( DbContextOptions<ConfigurationDbContext> options) { var testIdentityResource = CreateIdentityTestResource(); var testApiResource = CreateApiTestResource(); using (var context = new ConfigurationDbContext(options, StoreOptions)) { context.IdentityResources.Add(testIdentityResource.ToEntity()); context.ApiResources.Add(testApiResource.ToEntity()); context.IdentityResources .Add(CreateIdentityTestResource().ToEntity()); context.ApiResources.Add(CreateApiTestResource().ToEntity()); context.SaveChanges(); } Resources resources; using (var context = new ConfigurationDbContext(options, StoreOptions)) { var store = new ResourceStore( context, NullLogger<ResourceStore>.Create() ); resources = store.FindResourcesByScopeAsync(new List<string> { testIdentityResource.Name, testApiResource.Scopes.First().Name }).Result; } Assert.NotNull(resources); Assert.NotNull(resources.IdentityResources); Assert.NotEmpty(resources.IdentityResources); Assert.NotNull(resources.ApiResources); Assert.NotEmpty(resources.ApiResources); Assert.Equal(1, resources.IdentityResources.Count); Assert.Equal(1, resources.ApiResources.Count); } [Theory, MemberData(nameof(TestDatabaseProviders))] public void GetAllResources_WhenAllResourcesRequested_ExpectAllResourcesIncludingHidden( DbContextOptions<ConfigurationDbContext> options) { var visibleIdentityResource = CreateIdentityTestResource(); var visibleApiResource = CreateApiTestResource(); var hiddenIdentityResource = new IdentityResource { Name = Guid.NewGuid().ToString(), ShowInDiscoveryDocument = false }; var hiddenApiResource = new ApiResource { Name = Guid.NewGuid().ToString(), Scopes = new List<Scope> { new Scope { Name = Guid.NewGuid().ToString(), ShowInDiscoveryDocument = false } } }; using (var context = new ConfigurationDbContext(options, StoreOptions)) { context.IdentityResources .Add(visibleIdentityResource.ToEntity()); context.ApiResources.Add(visibleApiResource.ToEntity()); context.IdentityResources .Add(hiddenIdentityResource.ToEntity()); context.ApiResources.Add(hiddenApiResource.ToEntity()); context.SaveChanges(); } Resources resources; using (var context = new ConfigurationDbContext(options, StoreOptions)) { var store = new ResourceStore( context, NullLogger<ResourceStore>.Create() ); resources = store.GetAllResourcesAsync().Result; } Assert.NotNull(resources); Assert.NotEmpty(resources.IdentityResources); Assert.NotEmpty(resources.ApiResources); Assert.Contains(resources.IdentityResources, x => !x.ShowInDiscoveryDocument); Assert.Contains(resources.ApiResources, x => !x.Scopes.Any(y => y.ShowInDiscoveryDocument)); } [Theory, MemberData(nameof(TestDatabaseProviders))] public void FindIdentityResourcesByScopeAsync_WhenResourceExists_ExpectResourceAndCollectionsReturned( DbContextOptions<ConfigurationDbContext> options) { var resource = CreateIdentityTestResource(); using (var context = new ConfigurationDbContext(options, StoreOptions)) { context.IdentityResources.Add(resource.ToEntity()); context.SaveChanges(); } IList<IdentityResource> resources; using (var context = new ConfigurationDbContext(options, StoreOptions)) { var store = new ResourceStore( context, NullLogger<ResourceStore>.Create() ); resources = store.FindIdentityResourcesByScopeAsync( new List<string> { resource.Name } ).Result.ToList(); } Assert.NotNull(resources); Assert.NotEmpty(resources); var foundScope = resources.Single(); Assert.Equal(resource.Name, foundScope.Name); Assert.NotNull(foundScope.UserClaims); Assert.NotEmpty(foundScope.UserClaims); } [Theory, MemberData(nameof(TestDatabaseProviders))] public void FindIdentityResourcesByScopeAsync_WhenResourcesExist_ExpectOnlyRequestedReturned( DbContextOptions<ConfigurationDbContext> options) { var resource = CreateIdentityTestResource(); using (var context = new ConfigurationDbContext(options, StoreOptions)) { context.IdentityResources.Add(resource.ToEntity()); context.IdentityResources .Add(CreateIdentityTestResource().ToEntity()); context.SaveChanges(); } IList<IdentityResource> resources; using (var context = new ConfigurationDbContext(options, StoreOptions)) { var store = new ResourceStore( context, NullLogger<ResourceStore>.Create() ); resources = store .FindIdentityResourcesByScopeAsync(new List<string> { resource.Name }).Result.ToList(); } Assert.NotNull(resources); Assert.NotEmpty(resources); Assert.Equal(1, resources.Count); } [Theory, MemberData(nameof(TestDatabaseProviders))] public void FindApiResourceAsync_WhenResourceExists_ExpectResourceAndCollectionsReturned( DbContextOptions<ConfigurationDbContext> options) { var resource = CreateApiTestResource(); using (var context = new ConfigurationDbContext(options, StoreOptions)) { context.ApiResources.Add(resource.ToEntity()); context.SaveChanges(); } ApiResource foundResource; using (var context = new ConfigurationDbContext(options, StoreOptions)) { var store = new ResourceStore( context, NullLogger<ResourceStore>.Create() ); foundResource = store .FindApiResourceAsync(resource.Name).Result; } Assert.NotNull(foundResource); Assert.NotNull(foundResource.UserClaims); Assert.NotEmpty(foundResource.UserClaims); Assert.NotNull(foundResource.ApiSecrets); Assert.NotEmpty(foundResource.ApiSecrets); Assert.NotNull(foundResource.Scopes); Assert.NotEmpty(foundResource.Scopes); Assert.Contains(foundResource.Scopes, x => x.UserClaims.Any()); } [Theory, MemberData(nameof(TestDatabaseProviders))] public void FindApiResourcesByScopeAsync_WhenResourceExists_ExpectResourceAndCollectionsReturned( DbContextOptions<ConfigurationDbContext> options) { var resource = CreateApiTestResource(); using (var context = new ConfigurationDbContext(options, StoreOptions)) { context.ApiResources.Add(resource.ToEntity()); context.SaveChanges(); } IList<ApiResource> resources; using (var context = new ConfigurationDbContext(options, StoreOptions)) { var store = new ResourceStore( context, NullLogger<ResourceStore>.Create()); resources = store.FindApiResourcesByScopeAsync( new List<string> { resource.Scopes.First().Name } ).Result.ToList(); } Assert.NotEmpty(resources); Assert.NotNull(resources); Assert.NotNull(resources.First().UserClaims); Assert.NotEmpty(resources.First().UserClaims); Assert.NotNull(resources.First().ApiSecrets); Assert.NotEmpty(resources.First().ApiSecrets); Assert.NotNull(resources.First().Scopes); Assert.NotEmpty(resources.First().Scopes); Assert.Contains(resources.First().Scopes, x => x.UserClaims.Any()); } [Theory, MemberData(nameof(TestDatabaseProviders))] public void FindApiResourcesByScopeAsync_WhenMultipleResourcesExist_ExpectOnlyRequestedResourcesReturned( DbContextOptions<ConfigurationDbContext> options) { var resource = CreateApiTestResource(); using (var context = new ConfigurationDbContext(options, StoreOptions)) { context.ApiResources.Add(resource.ToEntity()); context.ApiResources.Add(CreateApiTestResource().ToEntity()); context.ApiResources.Add(CreateApiTestResource().ToEntity()); context.SaveChanges(); } IList<ApiResource> resources; using (var context = new ConfigurationDbContext(options, StoreOptions)) { var store = new ResourceStore( context, NullLogger<ResourceStore>.Create() ); resources = store .FindApiResourcesByScopeAsync(new List<string> { resource.Scopes.First().Name }).Result.ToList(); } Assert.NotNull(resources); Assert.NotEmpty(resources); Assert.Equal(1, resources.Count); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Northwind.Web.Areas.HelpPage.ModelDescriptions; using Northwind.Web.Areas.HelpPage.Models; namespace Northwind.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Services.InventoryService; using System; using System.Collections.Generic; using System.Reflection; namespace OpenSim.Services.HypergridService { /// <summary> /// Hypergrid inventory service. It serves the IInventoryService interface, /// but implements it in ways that are appropriate for inter-grid /// inventory exchanges. Specifically, it does not performs deletions /// and it responds to GetRootFolder requests with the ID of the /// Suitcase folder, not the actual "My Inventory" folder. /// </summary> public class HGSuitcaseInventoryService : XInventoryService, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private ExpiringCache<UUID, AvatarAppearance> m_Appearances = new ExpiringCache<UUID, AvatarAppearance>(); private IAvatarService m_AvatarService; private ExpiringCache<UUID, List<XInventoryFolder>> m_SuitcaseTrees = new ExpiringCache<UUID, List<XInventoryFolder>>(); // private string m_HomeURL; private IUserAccountService m_UserAccountService; // private UserAccountCache m_Cache; public HGSuitcaseInventoryService(IConfigSource config, string configName) : base(config, configName) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Starting with config name {0}", configName); if (configName != string.Empty) m_ConfigName = configName; if (m_Database == null) m_log.ErrorFormat("[HG SUITCASE INVENTORY SERVICE]: m_Database is null!"); // // Try reading the [InventoryService] section, if it exists // IConfig invConfig = config.Configs[m_ConfigName]; if (invConfig != null) { string userAccountsDll = invConfig.GetString("UserAccountsService", string.Empty); if (userAccountsDll == string.Empty) throw new Exception("Please specify UserAccountsService in HGInventoryService configuration"); Object[] args = new Object[] { config }; m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(userAccountsDll, args); if (m_UserAccountService == null) throw new Exception(String.Format("Unable to create UserAccountService from {0}", userAccountsDll)); string avatarDll = invConfig.GetString("AvatarService", string.Empty); if (avatarDll == string.Empty) throw new Exception("Please specify AvatarService in HGInventoryService configuration"); m_AvatarService = ServerUtils.LoadPlugin<IAvatarService>(avatarDll, args); if (m_AvatarService == null) throw new Exception(String.Format("Unable to create m_AvatarService from {0}", avatarDll)); // m_HomeURL = Util.GetConfigVarFromSections<string>(config, "HomeURI", // new string[] { "Startup", "Hypergrid", m_ConfigName }, String.Empty); // m_Cache = UserAccountCache.CreateUserAccountCache(m_UserAccountService); } m_log.Debug("[HG SUITCASE INVENTORY SERVICE]: Starting..."); } public override bool AddFolder(InventoryFolderBase folder) { //m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: AddFolder {0} {1}", folder.Name, folder.ParentID); // Let's do a bit of sanity checking, more than the base service does // make sure the given folder's parent folder exists under the suitcase tree of this user if (!IsWithinSuitcaseTree(folder.Owner, folder.ParentID)) return false; // OK, it's legit if (base.AddFolder(folder)) { List<XInventoryFolder> tree; if (m_SuitcaseTrees.TryGetValue(folder.Owner, out tree)) tree.Add(ConvertFromOpenSim(folder)); return true; } return false; } public override bool AddItem(InventoryItemBase item) { // Let's do a bit of sanity checking, more than the base service does // make sure the given folder's parent folder exists under the suitcase tree of this user if (!IsWithinSuitcaseTree(item.Owner, item.Folder)) return false; // OK, it's legit return base.AddItem(item); } public override bool CreateUserInventory(UUID principalID) { // NOGO return false; } public override bool DeleteFolders(UUID principalID, List<UUID> folderIDs) { // NOGO return false; } public override bool DeleteItems(UUID principalID, List<UUID> itemIDs) { return false; } public new InventoryFolderBase GetFolder(InventoryFolderBase folder) { InventoryFolderBase f = base.GetFolder(folder); if (f != null) { if (!IsWithinSuitcaseTree(f.Owner, f.ID)) return null; } return f; } public override InventoryCollection GetFolderContent(UUID principalID, UUID folderID) { InventoryCollection coll = null; if (!IsWithinSuitcaseTree(principalID, folderID)) return new InventoryCollection(); coll = base.GetFolderContent(principalID, folderID); if (coll == null) { m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Something wrong with user {0}'s suitcase folder", principalID); coll = new InventoryCollection(); } return coll; } public override InventoryFolderBase GetFolderForType(UUID principalID, AssetType type) { //m_log.DebugFormat("[HG INVENTORY SERVICE]: GetFolderForType for {0} {0}", principalID, type); XInventoryFolder suitcase = GetSuitcaseXFolder(principalID); if (suitcase == null) { m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Found no suitcase folder for user {0} when looking for child type folder {1}", principalID, type); return null; } XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "type", "parentFolderID" }, new string[] { principalID.ToString(), ((int)type).ToString(), suitcase.folderID.ToString() }); if (folders.Length == 0) { m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Found no folder for type {0} for user {1}", type, principalID); return null; } m_log.DebugFormat( "[HG SUITCASE INVENTORY SERVICE]: Found folder {0} {1} for type {2} for user {3}", folders[0].folderName, folders[0].folderID, type, principalID); return ConvertToOpenSim(folders[0]); } public override List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID) { // Let's do a bit of sanity checking, more than the base service does // make sure the given folder exists under the suitcase tree of this user if (!IsWithinSuitcaseTree(principalID, folderID)) return new List<InventoryItemBase>(); return base.GetFolderItems(principalID, folderID); } public override List<InventoryFolderBase> GetInventorySkeleton(UUID principalID) { XInventoryFolder suitcase = GetSuitcaseXFolder(principalID); if (suitcase == null) { m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Found no suitcase folder for user {0} when looking for inventory skeleton", principalID); return null; } List<XInventoryFolder> tree = GetFolderTree(principalID, suitcase.folderID); if (tree == null || (tree != null && tree.Count == 0)) return null; List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); foreach (XInventoryFolder x in tree) { folders.Add(ConvertToOpenSim(x)); } SetAsNormalFolder(suitcase); folders.Add(ConvertToOpenSim(suitcase)); return folders; } public new InventoryItemBase GetItem(InventoryItemBase item) { InventoryItemBase it = base.GetItem(item); if (it == null) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Unable to retrieve item {0} ({1}) in folder {2}", item.Name, item.ID, item.Folder); return null; } if (!IsWithinSuitcaseTree(it.Owner, it.Folder) && !IsPartOfAppearance(it.Owner, it.ID)) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Item {0} (folder {1}) is not within Suitcase", it.Name, it.Folder); return null; } // UserAccount user = m_Cache.GetUser(it.CreatorId); // // Adjust the creator data // if (user != null && it != null && (it.CreatorData == null || it.CreatorData == string.Empty)) // it.CreatorData = m_HomeURL + ";" + user.FirstName + " " + user.LastName; //} return it; } public override InventoryFolderBase GetRootFolder(UUID principalID) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: GetRootFolder for {0}", principalID); // Let's find out the local root folder XInventoryFolder root = GetRootXFolder(principalID); if (root == null) { m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Unable to retrieve local root folder for user {0}", principalID); return null; } // Warp! Root folder for travelers is the suitcase folder XInventoryFolder suitcase = GetSuitcaseXFolder(principalID); if (suitcase == null) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: User {0} does not have a Suitcase folder. Creating it...", principalID); // make one, and let's add it to the user's inventory as a direct child of the root folder // In the DB we tag it as type 100, but we use -1 (Unknown) outside suitcase = CreateFolder(principalID, root.folderID, 100, "My Suitcase"); if (suitcase == null) { m_log.ErrorFormat("[HG SUITCASE INVENTORY SERVICE]: Unable to create suitcase folder"); return null; } m_Database.StoreFolder(suitcase); CreateSystemFolders(principalID, suitcase.folderID); } SetAsNormalFolder(suitcase); return ConvertToOpenSim(suitcase); } public override bool MoveFolder(InventoryFolderBase folder) { if (!IsWithinSuitcaseTree(folder.Owner, folder.ID) || !IsWithinSuitcaseTree(folder.Owner, folder.ParentID)) return false; return base.MoveFolder(folder); } public override bool MoveItems(UUID principalID, List<InventoryItemBase> items) { // Principal is b0rked. *sigh* if (!IsWithinSuitcaseTree(items[0].Owner, items[0].Folder)) return false; return base.MoveItems(principalID, items); } public override bool PurgeFolder(InventoryFolderBase folder) { // NOGO return false; } public override bool UpdateFolder(InventoryFolderBase folder) { //m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Update folder {0}, version {1}", folder.ID, folder.Version); if (!IsWithinSuitcaseTree(folder.Owner, folder.ID)) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: folder {0} not within Suitcase tree", folder.Name); return false; } // For all others return base.UpdateFolder(folder); } public override bool UpdateItem(InventoryItemBase item) { if (!IsWithinSuitcaseTree(item.Owner, item.Folder)) return false; return base.UpdateItem(item); } protected void CreateSystemFolders(UUID principalID, UUID rootID) { m_log.Debug("[HG SUITCASE INVENTORY SERVICE]: Creating System folders under Suitcase..."); XInventoryFolder[] sysFolders = GetSystemFolders(principalID, rootID); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Animation) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Animation, "Animations"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Bodypart) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Bodypart, "Body Parts"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.CallingCard) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.CallingCard, "Calling Cards"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Clothing) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Clothing, "Clothing"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Gesture) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Gesture, "Gestures"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Landmark) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Landmark, "Landmarks"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.LostAndFoundFolder) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.LostAndFoundFolder, "Lost And Found"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Notecard) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Notecard, "Notecards"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Object) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Object, "Objects"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.SnapshotFolder) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.SnapshotFolder, "Photo Album"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.LSLText) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.LSLText, "Scripts"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Sound) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Sound, "Sounds"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Texture) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Texture, "Textures"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.TrashFolder) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.TrashFolder, "Trash"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.FavoriteFolder) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.FavoriteFolder, "Favorites"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.CurrentOutfitFolder) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.CurrentOutfitFolder, "Current Outfit"); } //public List<InventoryItemBase> GetActiveGestures(UUID principalID) //{ //} #region Auxiliary functions private XInventoryFolder GetCurrentOutfitXFolder(UUID userID) { XInventoryFolder root = GetRootXFolder(userID); if (root == null) return null; XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "type", "parentFolderID" }, new string[] { userID.ToString(), ((int)AssetType.CurrentOutfitFolder).ToString(), root.folderID.ToString() }); if (folders.Length == 0) return null; return folders[0]; } private List<XInventoryFolder> GetFolderTree(UUID principalID, UUID folder) { List<XInventoryFolder> t = null; if (m_SuitcaseTrees.TryGetValue(principalID, out t)) return t; // Get the tree of the suitcase folder t = GetFolderTreeRecursive(folder); m_SuitcaseTrees.AddOrUpdate(principalID, t, 5 * 60); // 5minutes return t; } private List<XInventoryFolder> GetFolderTreeRecursive(UUID root) { List<XInventoryFolder> tree = new List<XInventoryFolder>(); XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "parentFolderID" }, new string[] { root.ToString() }); if (folders == null || (folders != null && folders.Length == 0)) return tree; // empty tree else { foreach (XInventoryFolder f in folders) { tree.Add(f); tree.AddRange(GetFolderTreeRecursive(f.folderID)); } return tree; } } private XInventoryFolder GetRootXFolder(UUID principalID) { XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "folderName", "type" }, new string[] { principalID.ToString(), "My Inventory", ((int)AssetType.RootFolder).ToString() }); if (folders != null && folders.Length > 0) return folders[0]; // OK, so the RootFolder type didn't work. Let's look for any type with parent UUID.Zero. folders = m_Database.GetFolders( new string[] { "agentID", "folderName", "parentFolderID" }, new string[] { principalID.ToString(), "My Inventory", UUID.Zero.ToString() }); if (folders != null && folders.Length > 0) return folders[0]; return null; } private XInventoryFolder GetSuitcaseXFolder(UUID principalID) { // Warp! Root folder for travelers XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "type" }, new string[] { principalID.ToString(), "100" }); // This is a special folder type... if (folders != null && folders.Length > 0) return folders[0]; // check to see if we have the old Suitcase folder folders = m_Database.GetFolders( new string[] { "agentID", "folderName", "parentFolderID" }, new string[] { principalID.ToString(), "My Suitcase", UUID.Zero.ToString() }); if (folders != null && folders.Length > 0) { // Move it to under the root folder XInventoryFolder root = GetRootXFolder(principalID); folders[0].parentFolderID = root.folderID; folders[0].type = 100; m_Database.StoreFolder(folders[0]); return folders[0]; } return null; } private XInventoryFolder GetXFolder(UUID userID, UUID folderID) { XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "folderID" }, new string[] { userID.ToString(), folderID.ToString() }); if (folders.Length == 0) return null; return folders[0]; } /// <summary> /// Return true if the folderID is a subfolder of the Suitcase or the suitcase folder itself /// </summary> /// <param name="folderID"></param> /// <param name="root"></param> /// <param name="suitcase"></param> /// <returns></returns> private bool IsWithinSuitcaseTree(UUID principalID, UUID folderID) { XInventoryFolder suitcase = GetSuitcaseXFolder(principalID); if (suitcase == null) { m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: User {0} does not have a Suitcase folder", principalID); return false; } List<XInventoryFolder> tree = new List<XInventoryFolder>(); tree.Add(suitcase); // Warp! the tree is the real root folder plus the children of the suitcase folder tree.AddRange(GetFolderTree(principalID, suitcase.folderID)); // Also add the Current Outfit folder to the list of available folders tree.Add(GetCurrentOutfitXFolder(principalID)); XInventoryFolder f = tree.Find(delegate(XInventoryFolder fl) { if (fl.folderID == folderID) return true; else return false; }); if (f == null) return false; else return true; } private void SetAsNormalFolder(XInventoryFolder suitcase) { suitcase.type = (short)AssetType.Folder; } #endregion Auxiliary functions #region Avatar Appearance private AvatarAppearance GetAppearance(UUID principalID) { AvatarAppearance a = null; if (m_Appearances.TryGetValue(principalID, out a)) return a; a = m_AvatarService.GetAppearance(principalID); m_Appearances.AddOrUpdate(principalID, a, 5 * 60); // 5minutes return a; } private bool IsPartOfAppearance(UUID principalID, UUID itemID) { AvatarAppearance a = GetAppearance(principalID); if (a == null) return false; // Check wearables (body parts and clothes) for (int i = 0; i < a.Wearables.Length; i++) { for (int j = 0; j < a.Wearables[i].Count; j++) { if (a.Wearables[i][j].ItemID == itemID) { //m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: item {0} is a wearable", itemID); return true; } } } // Check attachments if (a.GetAttachmentForItem(itemID) != null) { //m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: item {0} is an attachment", itemID); return true; } return false; } #endregion Avatar Appearance } }
namespace java.nio { [global::MonoJavaBridge.JavaClass(typeof(global::java.nio.MappedByteBuffer_))] public abstract partial class MappedByteBuffer : java.nio.ByteBuffer { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected MappedByteBuffer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual global::java.nio.MappedByteBuffer load() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer.staticClass, "load", "()Ljava/nio/MappedByteBuffer;", ref global::java.nio.MappedByteBuffer._m0) as java.nio.MappedByteBuffer; } private static global::MonoJavaBridge.MethodId _m1; public virtual bool isLoaded() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.nio.MappedByteBuffer.staticClass, "isLoaded", "()Z", ref global::java.nio.MappedByteBuffer._m1); } private static global::MonoJavaBridge.MethodId _m2; public virtual global::java.nio.MappedByteBuffer force() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer.staticClass, "force", "()Ljava/nio/MappedByteBuffer;", ref global::java.nio.MappedByteBuffer._m2) as java.nio.MappedByteBuffer; } static MappedByteBuffer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.nio.MappedByteBuffer.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/MappedByteBuffer")); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.MappedByteBuffer))] internal sealed partial class MappedByteBuffer_ : java.nio.MappedByteBuffer { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal MappedByteBuffer_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override byte get() { return global::MonoJavaBridge.JavaBridge.CallByteMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "get", "()B", ref global::java.nio.MappedByteBuffer_._m0); } private static global::MonoJavaBridge.MethodId _m1; public override byte get(int arg0) { return global::MonoJavaBridge.JavaBridge.CallByteMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "get", "(I)B", ref global::java.nio.MappedByteBuffer_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; public override global::java.nio.ByteBuffer put(byte arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "put", "(B)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m3; public override global::java.nio.ByteBuffer put(int arg0, byte arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "put", "(IB)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m4; public override short getShort(int arg0) { return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getShort", "(I)S", ref global::java.nio.MappedByteBuffer_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public override short getShort() { return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getShort", "()S", ref global::java.nio.MappedByteBuffer_._m5); } private static global::MonoJavaBridge.MethodId _m6; public override global::java.nio.ByteBuffer putShort(int arg0, short arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putShort", "(IS)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m7; public override global::java.nio.ByteBuffer putShort(short arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putShort", "(S)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m8; public override char getChar() { return global::MonoJavaBridge.JavaBridge.CallCharMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getChar", "()C", ref global::java.nio.MappedByteBuffer_._m8); } private static global::MonoJavaBridge.MethodId _m9; public override char getChar(int arg0) { return global::MonoJavaBridge.JavaBridge.CallCharMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getChar", "(I)C", ref global::java.nio.MappedByteBuffer_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m10; public override global::java.nio.ByteBuffer putChar(int arg0, char arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putChar", "(IC)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m11; public override global::java.nio.ByteBuffer putChar(char arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putChar", "(C)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m12; public override int getInt() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getInt", "()I", ref global::java.nio.MappedByteBuffer_._m12); } private static global::MonoJavaBridge.MethodId _m13; public override int getInt(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getInt", "(I)I", ref global::java.nio.MappedByteBuffer_._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m14; public override global::java.nio.ByteBuffer putInt(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putInt", "(II)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m15; public override global::java.nio.ByteBuffer putInt(int arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putInt", "(I)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m16; public override long getLong(int arg0) { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getLong", "(I)J", ref global::java.nio.MappedByteBuffer_._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m17; public override long getLong() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getLong", "()J", ref global::java.nio.MappedByteBuffer_._m17); } private static global::MonoJavaBridge.MethodId _m18; public override global::java.nio.ByteBuffer putLong(long arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putLong", "(J)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m19; public override global::java.nio.ByteBuffer putLong(int arg0, long arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putLong", "(IJ)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m20; public override float getFloat() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getFloat", "()F", ref global::java.nio.MappedByteBuffer_._m20); } private static global::MonoJavaBridge.MethodId _m21; public override float getFloat(int arg0) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getFloat", "(I)F", ref global::java.nio.MappedByteBuffer_._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m22; public override global::java.nio.ByteBuffer putFloat(float arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putFloat", "(F)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m23; public override global::java.nio.ByteBuffer putFloat(int arg0, float arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putFloat", "(IF)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m24; public override double getDouble() { return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getDouble", "()D", ref global::java.nio.MappedByteBuffer_._m24); } private static global::MonoJavaBridge.MethodId _m25; public override double getDouble(int arg0) { return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "getDouble", "(I)D", ref global::java.nio.MappedByteBuffer_._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m26; public override global::java.nio.ByteBuffer putDouble(int arg0, double arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putDouble", "(ID)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m27; public override global::java.nio.ByteBuffer putDouble(double arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "putDouble", "(D)Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m28; public override bool isDirect() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "isDirect", "()Z", ref global::java.nio.MappedByteBuffer_._m28); } private static global::MonoJavaBridge.MethodId _m29; public override global::java.nio.ByteBuffer duplicate() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "duplicate", "()Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m29) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m30; public override global::java.nio.ByteBuffer slice() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "slice", "()Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m30) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m31; public override global::java.nio.ByteBuffer asReadOnlyBuffer() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "asReadOnlyBuffer", "()Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m31) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m32; public override global::java.nio.ByteBuffer compact() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "compact", "()Ljava/nio/ByteBuffer;", ref global::java.nio.MappedByteBuffer_._m32) as java.nio.ByteBuffer; } private static global::MonoJavaBridge.MethodId _m33; public override global::java.nio.CharBuffer asCharBuffer() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "asCharBuffer", "()Ljava/nio/CharBuffer;", ref global::java.nio.MappedByteBuffer_._m33) as java.nio.CharBuffer; } private static global::MonoJavaBridge.MethodId _m34; public override global::java.nio.ShortBuffer asShortBuffer() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "asShortBuffer", "()Ljava/nio/ShortBuffer;", ref global::java.nio.MappedByteBuffer_._m34) as java.nio.ShortBuffer; } private static global::MonoJavaBridge.MethodId _m35; public override global::java.nio.IntBuffer asIntBuffer() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "asIntBuffer", "()Ljava/nio/IntBuffer;", ref global::java.nio.MappedByteBuffer_._m35) as java.nio.IntBuffer; } private static global::MonoJavaBridge.MethodId _m36; public override global::java.nio.LongBuffer asLongBuffer() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "asLongBuffer", "()Ljava/nio/LongBuffer;", ref global::java.nio.MappedByteBuffer_._m36) as java.nio.LongBuffer; } private static global::MonoJavaBridge.MethodId _m37; public override global::java.nio.FloatBuffer asFloatBuffer() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "asFloatBuffer", "()Ljava/nio/FloatBuffer;", ref global::java.nio.MappedByteBuffer_._m37) as java.nio.FloatBuffer; } private static global::MonoJavaBridge.MethodId _m38; public override global::java.nio.DoubleBuffer asDoubleBuffer() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "asDoubleBuffer", "()Ljava/nio/DoubleBuffer;", ref global::java.nio.MappedByteBuffer_._m38) as java.nio.DoubleBuffer; } private static global::MonoJavaBridge.MethodId _m39; public override bool isReadOnly() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.nio.MappedByteBuffer_.staticClass, "isReadOnly", "()Z", ref global::java.nio.MappedByteBuffer_._m39); } static MappedByteBuffer_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.nio.MappedByteBuffer_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/MappedByteBuffer")); } } }
using System; using System.Collections; using Server; using Server.Items; using Server.Network; using Server.Mobiles; using Server.Prompts; using Server.Targeting; using Server.Engines.XmlSpawner2; namespace Server.Gumps { public class XmlQuestStatusGump : Gump { public static string Color(string text, string color) { return String.Format("<BASEFONT COLOR=#{0}>{1}</BASEFONT>", color, text); } public void DisplayQuestStatus(int x, int y, string objectivestr, string statestr, bool status, string descriptionstr) { if (objectivestr != null && objectivestr.Length > 0) { // look for special keywords string[] arglist = BaseXmlSpawner.ParseString(objectivestr, 5, ","); int targetcount = 1; bool foundkill = false; bool foundcollect = false; bool foundgive = false; bool foundescort = false; string name = null; string mobname = null; string type = null; string status_str; string text = null; string typestr; bool checkprop; if (arglist.Length > 0) switch (arglist[0]) { case "GIVE": // format for the objective string will be GIVE,mobname,itemtype[,count][,proptest] if (arglist.Length > 2) { mobname = arglist[1]; //name = arglist[2]; type = arglist[2]; } XmlQuest.CheckArgList(arglist, 3, null, out typestr, out targetcount, out checkprop, out status_str); foundgive = true; break; case "GIVENAMED": // format for the objective string will be GIVENAMED,mobname,itemname[,type][,count][,proptest] if (arglist.Length > 2) { mobname = arglist[1]; name = arglist[2]; } XmlQuest.CheckArgList(arglist, 3, null, out typestr, out targetcount, out checkprop, out status_str); if (typestr != null) type = typestr; foundgive = true; break; case "KILL": // format for the objective string will be KILL,mobtype[,count][,proptest] if (arglist.Length > 1) { //name = arglist[1]; type = arglist[1]; } XmlQuest.CheckArgList(arglist, 2, null, out typestr, out targetcount, out checkprop, out status_str); foundkill = true; break; case "KILLNAMED": // format for the objective string KILLNAMED,mobname[,type][,count][,proptest] if (arglist.Length > 1) { name = arglist[1]; } XmlQuest.CheckArgList(arglist, 2, null, out typestr, out targetcount, out checkprop, out status_str); if (typestr != null) type = typestr; foundkill = true; break; case "COLLECT": // format for the objective string will be COLLECT,itemtype[,count][,proptest] if (arglist.Length > 1) { //name = arglist[1]; type = arglist[1]; } XmlQuest.CheckArgList(arglist, 2, null, out typestr, out targetcount, out checkprop, out status_str); foundcollect = true; break; case "COLLECTNAMED": // format for the objective string will be COLLECTNAMED,itemname[,itemtype][,count][,proptest] if (arglist.Length > 1) { name = arglist[1]; } XmlQuest.CheckArgList(arglist, 2, null, out typestr, out targetcount, out checkprop, out status_str); if (typestr != null) type = typestr; foundcollect = true; break; case "ESCORT": // format for the objective string will be ESCORT,mobname[,proptest] if (arglist.Length > 1) { name = arglist[1]; } foundescort = true; break; } if (foundkill) { // get the current kill status int killed = 0; try { killed = int.Parse(statestr); } catch { } int remaining = targetcount - killed; if (remaining < 0) remaining = 0; // report the kill task objective status if (descriptionstr != null) text = String.Format("{0} ({1} left)", descriptionstr, remaining); else { if (name != null) { if (type == null) type = "mob"; text = String.Format("Kill {0} {1}(s) named {2} ({3} left)", targetcount, type, name, remaining); } else text = String.Format("Kill {0} {1}(s) ({2} left)", targetcount, type, remaining); } } else if (foundescort) { // get the current escort status int escorted = 0; try { escorted = int.Parse(statestr); } catch { } int remaining = targetcount - escorted; if (remaining < 0) remaining = 0; // report the escort task objective status if (descriptionstr != null) text = descriptionstr; else text = String.Format("Escort {0}", name); } else if (foundcollect) { // get the current collection status int collected = 0; try { collected = int.Parse(statestr); } catch { } int remaining = targetcount - collected; if (remaining < 0) remaining = 0; // report the collect task objective status if (descriptionstr != null) text = String.Format("{0} ({1} left)", descriptionstr, remaining); else { if (name != null) { if (type == null) type = "mob"; text = String.Format("Collect {0} {1}(s) named {2} ({3} left)", targetcount, type, name, remaining); } else text = String.Format("Collect {0} {1}(s) ({2} left)", targetcount, type, remaining); } } else if (foundgive) { // get the current give status int collected = 0; try { collected = int.Parse(statestr); } catch { } int remaining = targetcount - collected; if (remaining < 0) remaining = 0; // report the collect task objective status if (descriptionstr != null) text = String.Format("{0} ({1} left)", descriptionstr, remaining); else { if (name != null) { if (type == null) type = "item"; text = String.Format("Give {0} {1}(s) named {2} to {3} ({4} left)", targetcount, type, name, mobname, remaining); } else text = String.Format("Give {0} {1}(s) to {2} ({3} left)", targetcount, type, mobname, remaining); } } else { // just report the objectivestring text = objectivestr; } AddHtml(x, y, 223, 35, XmlSimpleGump.Color(text, "EFEF5A"), false, false); if (status) { AddImage(x - 20, y + 3, 0x939); // bullet AddHtmlLocalized(x + 222, y, 225, 37, 1046033, 0xff42, false, false); // Complete } else { AddImage(x - 20, y + 3, 0x938); // bullet AddHtmlLocalized(x + 222, y, 225, 37, 1046034, 0x7fff, false, false); // Incomplete } } } private IXmlQuest m_questitem; private string m_gumptitle; private int m_X; private int m_Y; private bool m_solid; private int m_screen; public XmlQuestStatusGump(IXmlQuest questitem, string gumptitle) : this(questitem, gumptitle, 0, 0, false, 0) { } public XmlQuestStatusGump(IXmlQuest questitem, string gumptitle, int X, int Y, bool solid) : this(questitem, gumptitle, X, Y, solid, 0) { } public XmlQuestStatusGump(IXmlQuest questitem, string gumptitle, int X, int Y, bool solid, int screen) : base(X, Y) { Closable = true; Dragable = true; m_X = X; m_Y = Y; m_solid = solid; m_questitem = questitem; m_gumptitle = gumptitle; m_screen = screen; AddPage(0); if (!solid) { AddImageTiled(54, 33, 369, 400, 2624); AddAlphaRegion(54, 33, 369, 400); } else { AddBackground(54, 33, 369, 400, 5054); } AddImageTiled(416, 39, 44, 389, 203); // AddButton( 338, 392, 2130, 2129, 3, GumpButtonType.Reply, 0 ); // Okay button AddHtmlLocalized(139, 59, 200, 30, 1046026, 0x7fff, false, false); // Quest Log AddImage(97, 49, 9005); // quest ribbon AddImageTiled(58, 39, 29, 390, 10460); // left hand border AddImageTiled(412, 37, 31, 389, 10460); // right hand border AddImage(430, 9, 10441); AddImageTiled(40, 38, 17, 391, 9263); AddImage(6, 25, 10421); AddImage(34, 12, 10420); AddImageTiled(94, 25, 342, 15, 10304); // top border AddImageTiled(40, 414, 415, 16, 10304); // bottom border AddImage(-10, 314, 10402); AddImage(56, 150, 10411); AddImage(136, 84, 96); AddImage(372, 57, 1417); AddImage(381, 66, 5576); // add the status and journal tabs AddImageTiled(90, 34, 322, 5, 0x145E); // top border int tab1 = 0x138F; int tab2 = 0x138E; if (screen == 1) { tab1 = 0x138E; tab2 = 0x138F; } AddButton(100, 18, tab1, tab2, 900, GumpButtonType.Reply, 0); AddLabel(115, 17, 0, "Status"); AddButton(189, 18, tab2, tab1, 901, GumpButtonType.Reply, 0); AddLabel(205, 17, 0, "Journal"); if (screen == 1) { // display the journal if (questitem.Journal != null && questitem.Journal.Count > 0) { string journaltext = null; for (int i = 0; i < questitem.Journal.Count; i++) { journaltext += "<u>"; journaltext += ((XmlQuest.JournalEntry)questitem.Journal[i]).EntryID; journaltext += ":</u><br>"; journaltext += ((XmlQuest.JournalEntry)questitem.Journal[i]).EntryText; journaltext += "<br><br>"; } AddHtml(100, 90, 270, 300, journaltext, true, true); } // add the add journal entry button AddButton(300, 49, 0x99C, 0x99D, 952, GumpButtonType.Reply, 0); //AddButton(300, 49, 0x159E, 0x159D, 952, GumpButtonType.Reply, 0); } else { if (gumptitle != null && gumptitle.Length > 0) { // display the title if it is there AddImage(146, 91, 2103); // bullet AddHtml(164, 86, 200, 30, XmlSimpleGump.Color(gumptitle, "00FF42"), false, false); } if (questitem.NoteString != null && questitem.NoteString.Length > 0) { // display the note string if it is there AddHtml(100, 106, 270, 80, questitem.NoteString, true, true); } DisplayQuestStatus(130, 192, questitem.Objective1, questitem.State1, questitem.Completed1, questitem.Description1); DisplayQuestStatus(130, 224, questitem.Objective2, questitem.State2, questitem.Completed2, questitem.Description2); DisplayQuestStatus(130, 256, questitem.Objective3, questitem.State3, questitem.Completed3, questitem.Description3); DisplayQuestStatus(130, 288, questitem.Objective4, questitem.State4, questitem.Completed4, questitem.Description4); DisplayQuestStatus(130, 320, questitem.Objective5, questitem.State5, questitem.Completed5, questitem.Description5); //if(questitem.HasCollect){ AddButton(100, 350, 0x2A4E, 0x2A3A, 700, GumpButtonType.Reply, 0); AddLabel(135, 356, 0x384, "Collect"); //} if ((questitem.RewardItem != null && !questitem.RewardItem.Deleted)) { m_questitem.CheckRewardItem(); if (questitem.RewardItem.Amount > 1) { AddLabel(230, 356, 55, String.Format("Reward: {0} ({1})", questitem.RewardItem.GetType().Name, questitem.RewardItem.Amount)); AddLabel(230, 373, 55, String.Format("Weight: {0}", questitem.RewardItem.Weight * questitem.RewardItem.Amount)); } else if (questitem.RewardItem is Container) { AddLabel(230, 356, 55, String.Format("Reward: {0} ({1} items)", questitem.RewardItem.GetType().Name, questitem.RewardItem.TotalItems)); AddLabel(230, 373, 55, String.Format("Weight: {0}", questitem.RewardItem.TotalWeight + questitem.RewardItem.Weight)); } else { AddLabel(230, 356, 55, String.Format("Reward: {0}", questitem.RewardItem.GetType().Name)); AddLabel(230, 373, 55, String.Format("Weight: {0}", questitem.RewardItem.Weight)); } AddImageTiled(330, 373, 81, 40, 200); AddItem(340, 376, questitem.RewardItem.ItemID); } if (questitem.RewardAttachment != null && !questitem.RewardAttachment.Deleted) { AddLabel(230, 339, 55, String.Format("Bonus: {0}", questitem.RewardAttachment.GetType().Name)); } if ((questitem.RewardItem != null && !questitem.RewardItem.Deleted) || (questitem.RewardAttachment != null && !questitem.RewardAttachment.Deleted)) { if (questitem.CanSeeReward) { AddButton(400, 380, 2103, 2103, 800, GumpButtonType.Reply, 0); } } // indicate any status info XmlQuest.VerifyObjectives(questitem); if (questitem.Status != null) { AddLabel(100, 392, 33, questitem.Status); } else // indicate the expiration time if (questitem.IsValid) { //AddHtmlLocalized(150, 400, 50, 37, 1046033, 0xf0000 , false , false ); // Expires AddHtml(130, 392, 200, 37, XmlSimpleGump.Color(questitem.ExpirationString, "00FF42"), false, false); } else if (questitem.AlreadyDone) { if (!questitem.Repeatable) { AddLabel(100, 392, 33, "Already done - cannot be repeated"); } else { ArrayList a = XmlAttach.FindAttachments(questitem.Owner, typeof(XmlQuestAttachment), questitem.Name); if (a != null && a.Count > 0) { AddLabel(100, 392, 33, String.Format("Repeatable in {0}", ((XmlQuestAttachment)a[0]).Expiration)); } else { AddLabel(150, 392, 33, "Already done - ???"); } } } else { //AddHtml( 150, 384, 200, 37, XmlSimpleGump.Color( "No longer valid", "00FF42" ), false, false ); AddLabel(150, 392, 33, "No longer valid"); } if (XmlQuest.QuestPointsEnabled) { AddHtml(250, 40, 200, 30, XmlSimpleGump.Color(String.Format("Difficulty Level {0}", questitem.Difficulty), "00FF42"), false, false); } if (questitem.PartyEnabled) { AddHtml(250, 55, 200, 30, XmlSimpleGump.Color("Party Quest", "00FF42"), false, false); if (questitem.PartyRange >= 0) { AddHtml(250, 70, 200, 30, XmlSimpleGump.Color(String.Format("Party Range {0}", questitem.PartyRange), "00FF42"), false, false); } else { AddHtml(250, 70, 200, 30, XmlSimpleGump.Color("No Range Limit", "00FF42"), false, false); } } else { AddHtml(250, 55, 200, 30, XmlSimpleGump.Color("Solo Quest", "00FF42"), false, false); } } } public override void OnResponse(NetState state, RelayInfo info) { if (info == null || state == null || state.Mobile == null || state.Mobile.Deleted || m_questitem == null || m_questitem.Deleted) return; switch (info.ButtonID) { case 700: state.Mobile.Target = new XmlQuest.GetCollectTarget(m_questitem); state.Mobile.SendGump(new XmlQuestStatusGump(m_questitem, m_gumptitle, m_X, m_Y, m_solid, m_screen)); break; case 800: if (m_questitem.RewardItem != null || m_questitem.RewardAttachment != null) { // open a new status gump state.Mobile.SendGump(new XmlQuestStatusGump(m_questitem, m_gumptitle, m_X, m_Y, m_solid, m_screen)); } // display the reward item if (m_questitem.RewardItem != null) { // show the contents of the xmlquest pack if (m_questitem.Pack != null) m_questitem.Pack.DisplayTo(state.Mobile); } // identify the reward attachment if (m_questitem.RewardAttachment != null) { //state.Mobile.SendMessage("{0}",m_questitem.RewardAttachment.OnIdentify(state.Mobile)); state.Mobile.CloseGump(typeof(DisplayAttachmentGump)); state.Mobile.SendGump(new DisplayAttachmentGump(state.Mobile, m_questitem.RewardAttachment.OnIdentify(state.Mobile))); } break; case 900: // open a new status gump with status display state.Mobile.SendGump(new XmlQuestStatusGump(m_questitem, m_gumptitle, m_X, m_Y, m_solid, 0)); break; case 901: // open a new status gump with journal display state.Mobile.SendGump(new XmlQuestStatusGump(m_questitem, m_gumptitle, m_X, m_Y, m_solid, 1)); break; case 952: // open a new status gump with journal display state.Mobile.SendGump(new XmlQuestStatusGump(m_questitem, m_gumptitle, m_X, m_Y, m_solid, 1)); // and open the journal entry editing gump // only allow this to be used if the questholder is theirs if (m_questitem.Owner == state.Mobile) { state.Mobile.SendGump(new JournalEntryGump(m_questitem, m_gumptitle, m_X, m_Y, m_solid)); } break; } } public class JournalEntryGump : Gump { private IXmlQuest m_questitem; private string m_gumptitle; private int m_X, m_Y; private bool m_solid; public JournalEntryGump(IXmlQuest questitem, string gumptitle, int X, int Y, bool solid) : base(X, Y) { if (questitem == null || questitem.Deleted) return; m_questitem = questitem; m_gumptitle = gumptitle; m_X = X; m_Y = Y; m_solid = solid; AddPage(0); //AddBackground(0, 0, 260, 354, 5054); //AddAlphaRegion(20, 0, 220, 354); AddImage(0, 0, 0x24AE); // left top scroll AddImage(114, 0, 0x24AF); // middle top scroll AddImage(170, 0, 0x24B0); // right top scroll AddImageTiled(0, 140, 114, 100, 0x24B1); // left middle scroll AddImageTiled(114, 140, 114, 100, 0x24B2); // middle middle scroll AddImageTiled(170, 140, 114, 100, 0x24B3); // right middle scroll AddImage(0, 210, 0x24B4); // left bottom scroll AddImage(114, 210, 0x24B5); // middle bottom scroll AddImage(170, 210, 0x24B6); // right bottom scroll //AddImageTiled(23, 40, 214, 290, 0x52); //AddImageTiled(24, 41, 213, 281, 0xBBC); // OK button AddButton(25, 327, 0xFB7, 0xFB9, 1, GumpButtonType.Reply, 0); // Close button AddButton(230, 327, 0xFB1, 0xFB3, 0, GumpButtonType.Reply, 0); // Edit button //AddButton(100, 325, 0xEF, 0xEE, 2, GumpButtonType.Reply, 0); string str = null; int entrynumber = 0; if (questitem.Journal != null && questitem.Journal.Count > 0) { entrynumber = questitem.Journal.Count; } string m_entryid = "Personal entry #" + entrynumber; // entryid text entry area //AddImageTiled(23, 0, 214, 23, 0x52); //AddImageTiled(24, 1, 213, 21, 0xBBC); AddTextEntry(35, 5, 200, 21, 0, 1, m_entryid); // main text entry area AddTextEntry(35, 40, 200, 271, 0, 0, str); // editing text entry areas // background for text entry area /* AddImageTiled(23, 275, 214, 23, 0x52); AddImageTiled(24, 276, 213, 21, 0xBBC); AddImageTiled(23, 300, 214, 23, 0x52); AddImageTiled(24, 301, 213, 21, 0xBBC); AddTextEntry(35, 275, 200, 21, 0, 1, null); AddTextEntry(35, 300, 200, 21, 0, 2, null); */ } public override void OnResponse(NetState state, RelayInfo info) { if (info == null || state == null || state.Mobile == null) return; if (m_questitem == null || m_questitem.Deleted) return; bool update_entry = false; //bool edit_entry = false; switch (info.ButtonID) { case 0: // Close { update_entry = false; break; } case 1: // Okay { update_entry = true; break; } case 2: // Edit { //edit_entry = true; break; } default: update_entry = true; break; } if (update_entry) { string entrytext = null; string entryid = null; TextRelay entry = info.GetTextEntry(0); if (entry != null) { entrytext = entry.Text; } entry = info.GetTextEntry(1); if (entry != null) { entryid = entry.Text; } m_questitem.AddJournalEntry = entryid + ":" + entrytext; } // open a new journal gump state.Mobile.CloseGump(typeof(XmlQuestStatusGump)); state.Mobile.SendGump(new XmlQuestStatusGump(m_questitem, m_gumptitle, m_X, m_Y, m_solid, 1)); } } private class DisplayAttachmentGump : Gump { public DisplayAttachmentGump(Mobile from, string text) : base(0, 0) { // prepare the page AddPage(0); AddBackground(0, 0, 400, 150, 5054); AddAlphaRegion(0, 0, 400, 150); AddLabel(20, 2, 55, "Quest Attachment Description"); AddHtml(20, 20, 360, 110, text, true, true); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Xml; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; using log4net; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Yengine { public partial class XMRInstance { /********************************************************************************\ * The only method of interest to outside this module is GetExecutionState() * * which captures the current state of the script into an XML document. * * * * The rest of this module contains support routines for GetExecutionState(). * \********************************************************************************/ /** * @brief Create an XML element that gives the current state of the script. * <ScriptState Engine="YEngine" SourceHash=m_ObjCode.sourceHash Asset=m_Item.AssetID> * <Snapshot>globalsandstackdump</Snapshot> * <Running>m_Running</Running> * <DetectArray ... * <EventQueue ... * <Permissions ... * <Plugins /> * </ScriptState> * Updates the .state file while we're at it. */ public XmlElement GetExecutionState(XmlDocument doc) { // When we're detaching an attachment, we need to wait here. // Change this to a 5 second timeout. If things do mess up, // we don't want to be stuck forever. // m_DetachReady.WaitOne(5000, false); XmlElement scriptStateN = doc.CreateElement("", "ScriptState", ""); scriptStateN.SetAttribute("Engine", m_Engine.ScriptEngineName); scriptStateN.SetAttribute("Asset", m_Item.AssetID.ToString()); scriptStateN.SetAttribute("SourceHash", m_ObjCode.sourceHash); // Make sure we aren't executing part of the script so it stays // stable. Setting suspendOnCheckRun tells CheckRun() to suspend // and return out so RunOne() will release the lock asap. suspendOnCheckRunHold = true; lock(m_RunLock) { m_RunOnePhase = "GetExecutionState enter"; CheckRunLockInvariants(true); // Get copy of script globals and stack in relocateable form. MemoryStream snapshotStream = new MemoryStream(); MigrateOutEventHandler(snapshotStream); Byte[] snapshotBytes = snapshotStream.ToArray(); snapshotStream.Close(); string snapshotString = Convert.ToBase64String(snapshotBytes); XmlElement snapshotN = doc.CreateElement("", "Snapshot", ""); snapshotN.AppendChild(doc.CreateTextNode(snapshotString)); scriptStateN.AppendChild(snapshotN); m_RunOnePhase = "GetExecutionState B"; CheckRunLockInvariants(true); // "Running" says whether or not we are accepting new events. XmlElement runningN = doc.CreateElement("", "Running", ""); runningN.AppendChild(doc.CreateTextNode(m_Running.ToString())); scriptStateN.AppendChild(runningN); m_RunOnePhase = "GetExecutionState C"; CheckRunLockInvariants(true); // "DoGblInit" says whether or not default:state_entry() will init global vars. XmlElement doGblInitN = doc.CreateElement("", "DoGblInit", ""); doGblInitN.AppendChild(doc.CreateTextNode(doGblInit.ToString())); scriptStateN.AppendChild(doGblInitN); m_RunOnePhase = "GetExecutionState D"; CheckRunLockInvariants(true); // More misc data. XmlNode permissionsN = doc.CreateElement("", "Permissions", ""); scriptStateN.AppendChild(permissionsN); XmlAttribute granterA = doc.CreateAttribute("", "granter", ""); granterA.Value = m_Item.PermsGranter.ToString(); permissionsN.Attributes.Append(granterA); XmlAttribute maskA = doc.CreateAttribute("", "mask", ""); maskA.Value = m_Item.PermsMask.ToString(); permissionsN.Attributes.Append(maskA); m_RunOnePhase = "GetExecutionState E"; CheckRunLockInvariants(true); // "DetectParams" are returned by llDetected...() script functions // for the currently active event, if any. if(m_DetectParams != null) { XmlElement detParArrayN = doc.CreateElement("", "DetectArray", ""); AppendXMLDetectArray(doc, detParArrayN, m_DetectParams); scriptStateN.AppendChild(detParArrayN); } m_RunOnePhase = "GetExecutionState F"; CheckRunLockInvariants(true); // Save any events we have in the queue. // <EventQueue> // <Event Name="..."> // <param>...</param> ... // <DetectParams>...</DetectParams> ... // </Event> // ... // </EventQueue> XmlElement queuedEventsN = doc.CreateElement("", "EventQueue", ""); lock(m_QueueLock) { foreach(EventParams evt in m_EventQueue) { XmlElement singleEventN = doc.CreateElement("", "Event", ""); singleEventN.SetAttribute("Name", evt.EventName); AppendXMLObjectArray(doc, singleEventN, evt.Params, "param"); AppendXMLDetectArray(doc, singleEventN, evt.DetectParams); queuedEventsN.AppendChild(singleEventN); } } scriptStateN.AppendChild(queuedEventsN); m_RunOnePhase = "GetExecutionState G"; CheckRunLockInvariants(true); // "Plugins" indicate enabled timers and listens, etc. Object[] pluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID); XmlNode plugins = doc.CreateElement("", "Plugins", ""); AppendXMLObjectArray(doc, plugins, pluginData, "plugin"); scriptStateN.AppendChild(plugins); m_RunOnePhase = "GetExecutionState H"; CheckRunLockInvariants(true); // Let script run again. suspendOnCheckRunHold = false; m_RunOnePhase = "GetExecutionState leave"; CheckRunLockInvariants(true); } // scriptStateN represents the contents of the .state file so // write the .state file while we are here. FileStream fs = File.Create(m_StateFileName); StreamWriter sw = new StreamWriter(fs); sw.Write(scriptStateN.OuterXml); sw.Close(); fs.Close(); return scriptStateN; } /** * @brief Write script state to output stream. * Input: * stream = stream to write event handler state information to */ private void MigrateOutEventHandler(Stream stream) { // Write script state out, frames and all, to the stream. // Does not change script state. stream.WriteByte(migrationVersion); stream.WriteByte((byte)16); this.MigrateOut(new BinaryWriter(stream)); } /** * @brief Convert an DetectParams[] to corresponding XML. * DetectParams[] holds the values retrievable by llDetected...() for * a given event. */ private static void AppendXMLDetectArray(XmlDocument doc, XmlElement parent, DetectParams[] detect) { foreach(DetectParams d in detect) { XmlElement detectParamsN = GetXMLDetect(doc, d); parent.AppendChild(detectParamsN); } } private static XmlElement GetXMLDetect(XmlDocument doc, DetectParams d) { XmlElement detectParamsN = doc.CreateElement("", "DetectParams", ""); XmlAttribute d_key = doc.CreateAttribute("", "key", ""); d_key.Value = d.Key.ToString(); detectParamsN.Attributes.Append(d_key); XmlAttribute pos = doc.CreateAttribute("", "pos", ""); pos.Value = d.OffsetPos.ToString(); detectParamsN.Attributes.Append(pos); XmlAttribute d_linkNum = doc.CreateAttribute("", "linkNum", ""); d_linkNum.Value = d.LinkNum.ToString(); detectParamsN.Attributes.Append(d_linkNum); XmlAttribute d_group = doc.CreateAttribute("", "group", ""); d_group.Value = d.Group.ToString(); detectParamsN.Attributes.Append(d_group); XmlAttribute d_name = doc.CreateAttribute("", "name", ""); d_name.Value = d.Name.ToString(); detectParamsN.Attributes.Append(d_name); XmlAttribute d_owner = doc.CreateAttribute("", "owner", ""); d_owner.Value = d.Owner.ToString(); detectParamsN.Attributes.Append(d_owner); XmlAttribute d_position = doc.CreateAttribute("", "position", ""); d_position.Value = d.Position.ToString(); detectParamsN.Attributes.Append(d_position); XmlAttribute d_rotation = doc.CreateAttribute("", "rotation", ""); d_rotation.Value = d.Rotation.ToString(); detectParamsN.Attributes.Append(d_rotation); XmlAttribute d_type = doc.CreateAttribute("", "type", ""); d_type.Value = d.Type.ToString(); detectParamsN.Attributes.Append(d_type); XmlAttribute d_velocity = doc.CreateAttribute("", "velocity", ""); d_velocity.Value = d.Velocity.ToString(); detectParamsN.Attributes.Append(d_velocity); return detectParamsN; } /** * @brief Append elements of an array of objects to an XML parent. * @param doc = document the parent is part of * @param parent = parent to append the items to * @param array = array of objects * @param tag = <tag ..>...</tag> for each element */ private static void AppendXMLObjectArray(XmlDocument doc, XmlNode parent, object[] array, string tag) { foreach(object o in array) { XmlElement element = GetXMLObject(doc, o, tag); parent.AppendChild(element); } } /** * @brief Get and XML representation of an object. * @param doc = document the tag will be put in * @param o = object to be represented * @param tag = <tag ...>...</tag> */ private static XmlElement GetXMLObject(XmlDocument doc, object o, string tag) { XmlAttribute typ = doc.CreateAttribute("", "type", ""); XmlElement n = doc.CreateElement("", tag, ""); if(o is LSL_List) { typ.Value = "list"; n.Attributes.Append(typ); AppendXMLObjectArray(doc, n, ((LSL_List)o).Data, "item"); } else { typ.Value = o.GetType().ToString(); n.Attributes.Append(typ); n.AppendChild(doc.CreateTextNode(o.ToString())); } return n; } } }
using System; using Spring.Threading.Collections; using Spring.Threading.Collections.Generic; using Spring.Threading.Future; namespace Spring.Threading.Execution { /// <summary> /// A <see cref="ICompletionService{T}"/> that uses a supplied <see cref="IExecutor"/> /// to execute tasks. /// </summary> /// <remarks> /// <para> /// This class arranges that submitted tasks are, upon completion, placed /// on a queue accessible using <see cref="Take()"/>. The class is /// lightweight enough to be suitable for transient use when processing /// groups of tasks. /// </para> /// <example> /// Usage Examples. /// <para> /// Suppose you have a set of solvers for a certain problem, each /// returning a value of some type <c>Result</c>, and would like to run /// them concurrently, processing the results of each of them that /// return a non-null value, in some method <c>Use(Result r)</c>. You /// could write this as: /// </para> /// <code language="c#"> /// void Solve(IExecutor e, /// ICollection&lt;ICallable&lt;Result&gt;&gt; solvers) /// { /// ICompletionService&lt;Result&gt; ecs /// = new ExecutorCompletionService&lt;Result&gt;(e); /// foreach (ICallable&lt;Result&gt; s in solvers) /// ecs.Submit(s); /// int n = solvers.size(); /// for (int i = 0; i &lt; n; ++i) { /// Result r = ecs.Take().GetResult(); /// if (r != null) Use(r); /// } /// } /// </code> /// <para> /// Suppose instead that you would like to use the first non-null result /// of the set of tasks, ignoring any that encounter exceptions, /// and cancelling all other tasks when the first one is ready: /// </para> /// <code language="c#"> /// void Solve(IExecutor e, /// ICollection&lt;ICallable&lt;Result&gt;&gt; solvers) /// { /// ICompletionService&lt;Result&gt; ecs /// = new ExecutorCompletionService&lt;Result&gt;(e); /// int n = solvers.Count; /// IList&lt;IFuture&lt;Result&gt;&gt; futures /// = new List&lt;IFuture&lt;Result&gt;&gt;(n); /// Result result = null; /// try { /// foreach (ICallable&lt;Result&gt; s in solvers) /// futures.Add(ecs.Submit(s)); /// for (int i = 0; i &lt; n; ++i) { /// try { /// Result r = ecs.Take().GetResult(); /// if (r != null) { /// result = r; /// break; /// } /// } catch (ExecutionException ignore) {} /// } /// } /// finally { /// for (IFuture&lt;Result&gt; f : futures) /// f.Cancel(true); /// } /// /// if (result != null) /// Use(result); /// } /// </code> /// </example> /// </remarks> /// <author>Doug Lea</author> /// <author>Griffin Caprio (.NET)</author> /// <author>Kenneth Xu (.NET)</author> public class ExecutorCompletionService<T> : ICompletionService<T> { private readonly IExecutor _executor; private readonly AbstractExecutorService _aes; private readonly IBlockingQueue<IFuture<T>> _completionQueue; /// <summary> /// <see cref="FutureTask{T}"/> extension to enqueue upon completion /// </summary> private class QueueingFuture : FutureTask<object> { private readonly ExecutorCompletionService<T> _enclosingInstance; private readonly IFuture<T> _task; internal QueueingFuture(ExecutorCompletionService<T> enclosingInstance, IRunnableFuture<T> task) : base(task, null) { _enclosingInstance = enclosingInstance; _task = task; } protected internal override void Done() { _enclosingInstance._completionQueue.Add(_task); } } private IRunnableFuture<T> NewTaskFor(ICallable<T> task) { if (_aes == null) return new FutureTask<T>(task); else return _aes.NewTaskFor(task); } private IRunnableFuture<T> NewTaskFor(IRunnable task, T result) { if (_aes == null) return new FutureTask<T>(task, result); else return _aes.NewTaskFor(task, result); } /// <summary> /// Creates an <see cref="ExecutorCompletionService{T}"/> using the supplied /// executor for base task execution and a /// <see cref="LinkedBlockingQueue{T}"/> as a completion queue. /// </summary> /// <param name="executor">the executor to use</param> /// <exception cref="System.ArgumentNullException"> /// if the executor is null /// </exception> public ExecutorCompletionService(IExecutor executor) : this( executor, new LinkedBlockingQueue<IFuture<T>>()) { } /// <summary> /// Creates an <see cref="ExecutorCompletionService{T}"/> using the supplied /// executor for base task execution and the supplied queue as its /// completion queue. /// </summary> /// <param name="executor">the executor to use</param> /// <param name="completionQueue">the queue to use as the completion queue /// normally one dedicated for use by this service /// </param> /// <exception cref="System.ArgumentNullException"> /// if the executor is null /// </exception> public ExecutorCompletionService(IExecutor executor, IBlockingQueue<IFuture<T>> completionQueue) { if (executor == null) throw new ArgumentNullException("executor", "Executor cannot be null."); if (completionQueue == null) throw new ArgumentNullException("completionQueue", "Completion Queue cannot be null."); _executor = executor; _aes = executor as AbstractExecutorService; _completionQueue = completionQueue; } /// <summary> /// Submits a value-returning task for execution and returns a <see cref="IFuture{T}"/> /// representing the pending results of the task. Upon completion, /// this task may be taken or polled. /// </summary> /// <param name="task">the task to submit</param> /// <returns> a <see cref="IFuture{T}"/> representing pending completion of the task</returns> /// <exception cref="Spring.Threading.Execution.RejectedExecutionException">if the task cannot be accepted for execution.</exception> /// <exception cref="System.ArgumentNullException">if the command is null</exception> public virtual IFuture<T> Submit(ICallable<T> task) { if (task == null) throw new ArgumentNullException("task", "Task cannot be null."); return DoSubmit(NewTaskFor(task)); } /// <summary> /// Submits a <see cref="Spring.Threading.IRunnable"/> task for execution /// and returns a <see cref="IFuture{T}"/> /// representing that task. Upon completion, this task may be taken or polled. /// </summary> /// <param name="task">the task to submit</param> /// <param name="result">the result to return upon successful completion</param> /// <returns> a <see cref="IFuture{T}"/> representing pending completion of the task, /// and whose <see cref="IFuture{T}.GetResult()"/> method will return the given result value /// upon completion /// </returns> /// <exception cref="Spring.Threading.Execution.RejectedExecutionException">if the task cannot be accepted for execution.</exception> /// <exception cref="System.ArgumentNullException">if the command is null</exception> public virtual IFuture<T> Submit(IRunnable task, T result) { if (task == null) throw new ArgumentNullException("task", "Task cannot be null."); return DoSubmit(NewTaskFor(task, result)); } public virtual IFuture<T> Submit(IRunnableFuture<T> runnableFuture) { if (runnableFuture == null) throw new ArgumentNullException("runnableFuture"); return DoSubmit(runnableFuture); } private IFuture<T> DoSubmit(IRunnableFuture<T> runnableFuture) { _executor.Execute(new QueueingFuture(this, runnableFuture)); return runnableFuture; } /// <summary> /// Retrieves and removes the <see cref="IFuture{T}"/> representing the next /// completed task, waiting if none are yet present. /// </summary> /// <returns> the <see cref="IFuture{T}"/> representing the next completed task /// </returns> public virtual IFuture<T> Take() { return _completionQueue.Take(); } /// <summary> /// Retrieves and removes the <see cref="IFuture{T}"/> representing the next /// completed task or <see lang="null"/> if none are present. /// </summary> /// <returns> the <see cref="IFuture{T}"/> representing the next completed task, or /// <see lang="null"/> if none are present. /// </returns> public virtual IFuture<T> Poll() { IFuture<T> next; return _completionQueue.Poll(out next) ? null : next; } /// <summary> /// Retrieves and removes the <see cref="IFuture{T}"/> representing the next /// completed task, waiting, if necessary, up to the specified duration /// if none are yet present. /// </summary> /// <param name="durationToWait">duration to wait if no completed task is present yet.</param> /// <returns> /// the <see cref="IFuture{T}"/> representing the next completed task or /// <see lang="null"/> if the specified waiting time elapses before one /// is present. /// </returns> public virtual IFuture<T> Poll(TimeSpan durationToWait) { IFuture<T> next; return _completionQueue.Poll(durationToWait, out next) ? null : next; } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kodestruct.Common.Mathematics { public static class DoubleExtensions { public static double ToRadians(this double val) { if (val != 0) { return (Math.PI / 180) * val; } else { return 0; } } public static double ToDegrees(this double val) { if (val !=0) { return (180.0 / Math.PI) * val; } else { return 0; } } public static bool AlmostEqualsWithAbsTolerance(this double a, double b, double maxAbsoluteError) { double diff = Math.Abs(a - b); if (a.Equals(b)) { // shortcut, handles infinities return true; } return diff <= maxAbsoluteError; } /// <summary> /// Checks if numbers are approximately equal distinguishing between rounding up and down /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="ToleranceUp"></param> /// <param name="ToleranceDown"></param> /// <returns></returns> public static bool InRange(this double a, double b, double ToleranceUp, double ToleranceDown) { if (a.Equals(b)) { // shortcut, handles infinities return true; } else if (a>b) { return a - b <= ToleranceUp; } else { return b - a <= ToleranceDown; } } public static double Ceiling(this double i, double Precision) { return ((int)Math.Ceiling(i / Precision)) * Precision; } public static double Floor(this double i, double Precision) { return ((int)Math.Floor(i / Precision)) * Precision; } //https://stackoverflow.com/questions/38891250/convert-to-fraction-inches public static string ToFraction64(this double value) { // denominator is fixed int denominator = 64; // integer part, can be signed: 1, 0, -3,... int integer = (int)value; // numerator: always unsigned (the sign belongs to the integer part) // + 0.5 - rounding, nearest one: 37.9 / 64 -> 38 / 64; 38.01 / 64 -> 38 / 64 int numerator = (int)((Math.Abs(value) - Math.Abs(integer)) * denominator + 0.5); // some fractions, e.g. 24 / 64 can be simplified: // both numerator and denominator can be divided by the same number // since 64 = 2 ** 6 we can try 2 powers only // 24/64 -> 12/32 -> 6/16 -> 3/8 // In general case (arbitrary denominator) use gcd (Greatest Common Divisor): // double factor = gcd(denominator, numerator); // denominator /= factor; // numerator /= factor; while ((numerator % 2 == 0) && (denominator % 2 == 0)) { numerator /= 2; denominator /= 2; } // The longest part is formatting out // if we have an actual, not degenerated fraction (not, say, 4 0/1) if (denominator > 1) if (integer != 0) // all three: integer + numerator + denominator return string.Format("{0} {1}/{2}", integer, numerator, denominator); else if (value < 0) // negative numerator/denominator, e.g. -1/4 return string.Format("-{0}/{1}", numerator, denominator); else // positive numerator/denominator, e.g. 3/8 return string.Format("{0}/{1}", numerator, denominator); else return integer.ToString(); // just an integer value, e.g. 0, -3, 12... } //public static double[] Minimum(this double[] values) //{ // double Minimum = double.PositiveInfinity; // for (int i = 0; i < values.Length; i++) // if (values[i] < Minimum) // { // Minimum = values[i]; // } // return Minimum; //} //} //public static class DoubleExtensions //{ //SOURCE: https://github.com/mathnet/mathnet-numerics/blob/master/src/Numerics/Precision.cs // https://github.com/mathnet/mathnet-numerics/blob/master/src/Numerics/Precision.Equality.cs // http://referencesource.microsoft.com/#WindowsBase/Shared/MS/Internal/DoubleUtil.cs // http://stackoverflow.com/questions/2411392/double-epsilon-for-equality-greater-than-less-than-less-than-or-equal-to-gre /// <summary> /// The smallest positive number that when SUBTRACTED from 1D yields a result different from 1D. /// The value is derived from 2^(-53) = 1.1102230246251565e-16, where IEEE 754 binary64 &quot;double precision&quot; floating point numbers have a significand precision that utilize 53 bits. /// /// This number has the following properties: /// (1 - NegativeMachineEpsilon) &lt; 1 and /// (1 + NegativeMachineEpsilon) == 1 /// </summary> public const double NegativeMachineEpsilon = 1.1102230246251565e-16D; //Math.Pow(2, -53); /// <summary> /// The smallest positive number that when ADDED to 1D yields a result different from 1D. /// The value is derived from 2 * 2^(-53) = 2.2204460492503131e-16, where IEEE 754 binary64 &quot;double precision&quot; floating point numbers have a significand precision that utilize 53 bits. /// /// This number has the following properties: /// (1 - PositiveDoublePrecision) &lt; 1 and /// (1 + PositiveDoublePrecision) &gt; 1 /// </summary> public const double PositiveMachineEpsilon = 2D * NegativeMachineEpsilon; /// <summary> /// The smallest positive number that when SUBTRACTED from 1D yields a result different from 1D. /// /// This number has the following properties: /// (1 - NegativeMachineEpsilon) &lt; 1 and /// (1 + NegativeMachineEpsilon) == 1 /// </summary> public static readonly double MeasuredNegativeMachineEpsilon = MeasureNegativeMachineEpsilon(); private static double MeasureNegativeMachineEpsilon() { double epsilon = 1D; do { double nextEpsilon = epsilon / 2D; if ((1D - nextEpsilon) == 1D) //if nextEpsilon is too small return epsilon; epsilon = nextEpsilon; } while (true); } /// <summary> /// The smallest positive number that when ADDED to 1D yields a result different from 1D. /// /// This number has the following properties: /// (1 - PositiveDoublePrecision) &lt; 1 and /// (1 + PositiveDoublePrecision) &gt; 1 /// </summary> public static readonly double MeasuredPositiveMachineEpsilon = MeasurePositiveMachineEpsilon(); private static double MeasurePositiveMachineEpsilon() { double epsilon = 1D; do { double nextEpsilon = epsilon / 2D; if ((1D + nextEpsilon) == 1D) //if nextEpsilon is too small return epsilon; epsilon = nextEpsilon; } while (true); } const double DefaultDoubleAccuracy = NegativeMachineEpsilon * 10D; public static bool IsClose(this double value1, double value2) { return IsClose(value1, value2, DefaultDoubleAccuracy); } public static bool IsClose(this double value1, double value2, double maximumAbsoluteError) { if (double.IsInfinity(value1) || double.IsInfinity(value2)) return value1 == value2; if (double.IsNaN(value1) || double.IsNaN(value2)) return false; double delta = value1 - value2; //return Math.Abs(delta) <= maximumAbsoluteError; if (delta > maximumAbsoluteError || delta < -maximumAbsoluteError) return false; return true; } public static bool LessThan(this double value1, double value2) { return (value1 < value2) && !IsClose(value1, value2); } public static bool GreaterThan(this double value1, double value2) { return (value1 > value2) && !IsClose(value1, value2); } public static bool LessThanOrClose(this double value1, double value2) { return (value1 < value2) || IsClose(value1, value2); } public static bool GreaterThanOrClose(this double value1, double value2) { return (value1 > value2) || IsClose(value1, value2); } public static bool IsOne(this double value) { double delta = value - 1D; //return Math.Abs(delta) <= PositiveMachineEpsilon; if (delta > PositiveMachineEpsilon || delta < -PositiveMachineEpsilon) return false; return true; } public static bool IsZero(this double value) { //return Math.Abs(value) <= PositiveMachineEpsilon; if (value > PositiveMachineEpsilon || value < -PositiveMachineEpsilon) return false; return true; } //https://stackoverflow.com/questions/2453951/c-sharp-double-tostring-formatting-with-two-decimal-places-but-no-rounding public static string To6DecimalPlaces(this double val) { double x = Math.Truncate(val * 1000000) / 1000000; //string s = string.Format("{0:N6}", x); string s = x.ToString(); return s; } } }
// Copyright 2021 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Android.App; using Android.Content; using Android.OS; using Android.Text.Method; using Android.Views; using Android.Widget; using ArcGISRuntime; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Security; using Esri.ArcGISRuntime.UtilityNetworks; using System; using System.Collections.Generic; using System.Linq; namespace ArcGISRuntimeXamarin.Samples.ConfigureSubnetworkTrace { [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Configure subnetwork trace", category: "Utility network", description: "Get a server-defined trace configuration for a given tier and modify its traversability scope, add new condition barriers and control what is included in the subnetwork trace result.", instructions: "The sample loads with a server-defined trace configuration from a tier. Check or uncheck which options to include in the trace - such as containers or barriers. Use the selection boxes to define a new condition network attribute comparison, and then use 'Add' to add the it to the trace configuration. Tap 'Trace' to run a subnetwork trace with this modified configuration from a default starting location.", tags: new[] { "category comparison", "condition barriers", "network analysis", "network attribute comparison", "subnetwork trace", "trace configuration", "traversability", "utility network", "validate consistency" })] public class ConfigureSubnetworkTrace : Activity { // Hold references to the UI controls. private Switch _barrierSwitch; private Switch _containerSwitch; private Button _attributeButton; private Button _comparisonButton; private Button _valueButton; private Button _addButton; private Button _traceButton; private Button _resetButton; private TextView _expressionLabel; private EditText _valueEntry; private View _mainView; // Feature service for an electric utility network in Naperville, Illinois. private const string FeatureServiceUrl = "https://sampleserver7.arcgisonline.com/server/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer"; private UtilityNetwork _utilityNetwork; // For creating the default starting location. private const string DeviceTableName = "Electric Distribution Device"; private const string AssetGroupName = "Circuit Breaker"; private const string AssetTypeName = "Three Phase"; private const string GlobalId = "{1CAF7740-0BF4-4113-8DB2-654E18800028}"; // For creating the default trace configuration. private const string DomainNetworkName = "ElectricDistribution"; private const string TierName = "Medium Voltage Radial"; // Utility element to start the trace from. private UtilityElement _startingLocation; // Holding the initial conditional expression. private UtilityTraceConditionalExpression _initialExpression; // The trace configuration. private UtilityTraceConfiguration _configuration; // The source tier of the utility network. private UtilityTier _sourceTier; // The currently selected values for the barrier expression. private UtilityNetworkAttribute _selectedAttribute; private UtilityAttributeComparisonOperator _selectedComparison; private object _selectedValue; // Attributes in the network private IEnumerable<UtilityNetworkAttribute> _attributes; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Configure subnetwork trace"; CreateLayout(); Initialize(); } private async void Initialize() { // As of ArcGIS Enterprise 10.8.1, using utility network functionality requires a licensed user. The following login for the sample server is licensed to perform utility network operations. AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(async (info) => { try { // WARNING: Never hardcode login information in a production application. This is done solely for the sake of the sample. string sampleServer7User = "viewer01"; string sampleServer7Pass = "I68VGU^nMurF"; return await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri, sampleServer7User, sampleServer7Pass); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return null; } }); try { // Disable interaction until the data is loaded. _mainView.Visibility = ViewStates.Gone; // Create and load the utility network. _utilityNetwork = await UtilityNetwork.CreateAsync(new Uri(FeatureServiceUrl)); // Getthe attributes in the utility network. _attributes = _utilityNetwork.Definition.NetworkAttributes.Where(netattr => !netattr.IsSystemDefined); // Create a default starting location. UtilityNetworkSource networkSource = _utilityNetwork.Definition.GetNetworkSource(DeviceTableName); UtilityAssetGroup assetGroup = networkSource.GetAssetGroup(AssetGroupName); UtilityAssetType assetType = assetGroup.GetAssetType(AssetTypeName); Guid globalId = Guid.Parse(GlobalId); _startingLocation = _utilityNetwork.CreateElement(assetType, globalId); // Set the terminal for this location. (For our case, we use the 'Load' terminal.) _startingLocation.Terminal = _startingLocation.AssetType.TerminalConfiguration?.Terminals.FirstOrDefault(term => term.Name == "Load"); // Get a default trace configuration from a tier to update the UI. UtilityDomainNetwork domainNetwork = _utilityNetwork.Definition.GetDomainNetwork(DomainNetworkName); _sourceTier = domainNetwork.GetTier(TierName); // Set the trace configuration. _configuration = _sourceTier.GetDefaultTraceConfiguration(); // Set the default expression (if provided). if (_sourceTier.GetDefaultTraceConfiguration().Traversability.Barriers is UtilityTraceConditionalExpression expression) { _initialExpression = expression; _expressionLabel.Text = ExpressionToString(_initialExpression); } // Set the traversability scope. _sourceTier.GetDefaultTraceConfiguration().Traversability.Scope = UtilityTraversabilityScope.Junctions; } catch (Exception ex) { new AlertDialog.Builder(this).SetMessage(ex.Message).SetTitle(ex.GetType().Name).Show(); } finally { _mainView.Visibility = ViewStates.Visible; } } private void AttributeClicked(object sender, EventArgs e) { // Get the names of every attribute. string[] options = _attributes.Select(x => x.Name).ToArray(); // Create UI for attribute selection. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetTitle("Select an attribute"); builder.SetItems(options, AttributeSelected); builder.Show(); } private void AttributeSelected(object sender, DialogClickEventArgs e) { _selectedAttribute = _attributes.ElementAt(e.Which); _attributeButton.Text = _selectedAttribute.Name; // Reset the value, this prevents invalid values being used to create expressions. _valueButton.Text = "Value"; _selectedValue = null; } private void ComparisonClicked(object sender, EventArgs e) { // Get the names of every comparison operator. string[] options = Enum.GetNames(typeof(UtilityAttributeComparisonOperator)); // Create UI for attribute selection. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetTitle("Select comparison"); builder.SetItems(options, ComparisonSelected); builder.Show(); } private void ComparisonSelected(object sender, DialogClickEventArgs e) { _selectedComparison = (UtilityAttributeComparisonOperator)Enum.GetValues(typeof(UtilityAttributeComparisonOperator)).GetValue(e.Which); _comparisonButton.Text = _selectedComparison.ToString(); } private void ValueClicked(object sender, EventArgs e) { // Verify that an attribute has been selected. if (_selectedAttribute != null) { AlertDialog.Builder builder = new AlertDialog.Builder(this); if (_selectedAttribute.Domain is CodedValueDomain domain) { // Create a dialog for selecting from the coded values. builder.SetTitle("Select a value"); string[] options = domain.CodedValues.Select(x => x.Name).ToArray(); builder.SetItems(options, ValueSelected); } else { // Create a dialog for entering a value. _valueEntry = new EditText(this) { InputType = Android.Text.InputTypes.ClassNumber }; builder.SetTitle("Enter a value"); builder.SetView(_valueEntry); builder.SetPositiveButton("OK", ValueEntered); } builder.Show(); } } private void ValueSelected(object sender, DialogClickEventArgs e) { _selectedValue = ((CodedValueDomain)_selectedAttribute.Domain).CodedValues[e.Which]; _valueButton.Text = ((CodedValue)_selectedValue).Name; } private void ValueEntered(object sender, DialogClickEventArgs e) { _selectedValue = _valueEntry.Text; _valueButton.Text = _selectedValue.ToString(); } private void AddClicked(object sender, EventArgs e) { try { if (_configuration == null) { _configuration = new UtilityTraceConfiguration(); } if (_configuration.Traversability == null) { _configuration.Traversability = new UtilityTraversability(); } // NOTE: You may also create a UtilityCategoryComparison with UtilityNetworkDefinition.Categories and UtilityCategoryComparisonOperator. if (_selectedAttribute != null) { object selectedValue; // If the value is a coded value. if (_selectedAttribute.Domain is CodedValueDomain && _selectedValue is CodedValue codedValue) { selectedValue = ConvertToDataType(codedValue.Code, _selectedAttribute.DataType); } // If the value is free entry. else { selectedValue = ConvertToDataType(_selectedValue.ToString().Trim(), _selectedAttribute.DataType); } // NOTE: You may also create a UtilityNetworkAttributeComparison with another NetworkAttribute. UtilityTraceConditionalExpression expression = new UtilityNetworkAttributeComparison(_selectedAttribute, _selectedComparison, selectedValue); if (_configuration.Traversability.Barriers is UtilityTraceConditionalExpression otherExpression) { // NOTE: You may also combine expressions with UtilityTraceAndCondition expression = new UtilityTraceOrCondition(otherExpression, expression); } _configuration.Traversability.Barriers = expression; _expressionLabel.Text = ExpressionToString(expression); } } catch (Exception ex) { new AlertDialog.Builder(this).SetMessage(ex.Message).SetTitle(ex.GetType().Name).Show(); } } private async void TraceClicked(object sender, EventArgs e) { if (_utilityNetwork == null || _startingLocation == null) { return; } try { // Create utility trace parameters for the starting location. UtilityTraceParameters parameters = new UtilityTraceParameters(UtilityTraceType.Subnetwork, new[] { _startingLocation }); parameters.TraceConfiguration = _configuration; // Trace the utility network. IEnumerable<UtilityTraceResult> results = await _utilityNetwork.TraceAsync(parameters); // Get the first result. UtilityElementTraceResult elementResult = results?.FirstOrDefault() as UtilityElementTraceResult; // Display the number of elements found by the trace. new AlertDialog.Builder(this).SetMessage($"`{elementResult?.Elements?.Count ?? 0}` elements found.").SetTitle("Trace Result").Show(); } catch (Exception ex) { new AlertDialog.Builder(this).SetMessage(ex.Message).SetTitle(ex.GetType().Name).Show(); } } private void ResetClicked(object sender, EventArgs e) { // Reset the barrier condition to the initial value. UtilityTraceConfiguration traceConfiguration = _configuration; traceConfiguration.Traversability.Barriers = _initialExpression; _expressionLabel.Text = ExpressionToString(_initialExpression); } private object ConvertToDataType(object otherValue, UtilityNetworkAttributeDataType dataType) { switch (dataType) { case UtilityNetworkAttributeDataType.Boolean: return Convert.ToBoolean(otherValue); case UtilityNetworkAttributeDataType.Double: return Convert.ToDouble(otherValue); case UtilityNetworkAttributeDataType.Float: return Convert.ToSingle(otherValue); case UtilityNetworkAttributeDataType.Integer: return Convert.ToInt32(otherValue); } throw new NotSupportedException(); } private string ExpressionToString(UtilityTraceConditionalExpression expression) { if (expression is UtilityCategoryComparison categoryComparison) { return $"`{categoryComparison.Category.Name}` {categoryComparison.ComparisonOperator}"; } else if (expression is UtilityNetworkAttributeComparison attributeComparison) { // Check if attribute domain is a coded value domain. if (attributeComparison.NetworkAttribute.Domain is CodedValueDomain domain) { // Get the coded value using the the attribute comparison value and attribute data type. UtilityNetworkAttributeDataType dataType = attributeComparison.NetworkAttribute.DataType; object attributeValue = ConvertToDataType(attributeComparison.Value, attributeComparison.NetworkAttribute.DataType); CodedValue codedValue = domain.CodedValues.FirstOrDefault(value => ConvertToDataType(value.Code, dataType).Equals(attributeValue)); return $"`{attributeComparison.NetworkAttribute.Name}` {attributeComparison.ComparisonOperator} `{codedValue?.Name}`"; } else { return $"`{attributeComparison.NetworkAttribute.Name}` {attributeComparison.ComparisonOperator} `{attributeComparison.OtherNetworkAttribute?.Name ?? attributeComparison.Value}`"; } } else if (expression is UtilityTraceAndCondition andCondition) { return $"({ExpressionToString(andCondition.LeftExpression)}) AND\n ({ExpressionToString(andCondition.RightExpression)})"; } else if (expression is UtilityTraceOrCondition orCondition) { return $"({ExpressionToString(orCondition.LeftExpression)}) OR\n ({ExpressionToString(orCondition.RightExpression)})"; } else { return null; } } private void CreateLayout() { // Load the layout from the axml resource. (This sample has the same interface as the navigation sample without rerouting) SetContentView(Resource.Layout.ConfigureSubnetworkTrace); _barrierSwitch = FindViewById<Switch>(Resource.Id.barrierSwitch); _containerSwitch = FindViewById<Switch>(Resource.Id.containerSwitch); _attributeButton = FindViewById<Button>(Resource.Id.attributeButton); _comparisonButton = FindViewById<Button>(Resource.Id.comparisonButton); _valueButton = FindViewById<Button>(Resource.Id.valueButton); _addButton = FindViewById<Button>(Resource.Id.addButton); _traceButton = FindViewById<Button>(Resource.Id.traceButton); _resetButton = FindViewById<Button>(Resource.Id.resetButton); _expressionLabel = FindViewById<TextView>(Resource.Id.barrierText); _mainView = FindViewById<View>(Resource.Id.ConfigureSubnetworkTraceView); // Add event handlers for all of the controls. _barrierSwitch.CheckedChange += (s, e) => _sourceTier.GetDefaultTraceConfiguration().IncludeBarriers = e.IsChecked; _containerSwitch.CheckedChange += (s, e) => _sourceTier.GetDefaultTraceConfiguration().IncludeContainers = e.IsChecked; _attributeButton.Click += AttributeClicked; _comparisonButton.Click += ComparisonClicked; _valueButton.Click += ValueClicked; _addButton.Click += AddClicked; _traceButton.Click += TraceClicked; _resetButton.Click += ResetClicked; // Make the label for barrier expression scrollable. _expressionLabel.MovementMethod = new ScrollingMovementMethod(); } } }
using System; using Sharpmake; [module: Sharpmake.Include("*/Sharpmake.*.sharpmake.cs")] namespace SharpmakeGen.Samples { public abstract class SampleProject : Common.SharpmakeBaseProject { public string SharpmakeMainFile = "[project.Name].sharpmake.cs"; protected SampleProject() : base(excludeSharpmakeFiles: false, generateXmlDoc: false) { // samples are special, all the classes are here instead of in the subfolders SourceRootPath = @"[project.SharpmakeCsPath]\[project.Name]"; SourceFilesExcludeRegex.Add( @"\\codebase\\", @"\\projects\\", @"\\reference\\" ); DependenciesCopyLocal = DependenciesCopyLocalTypes.None; } public override void ConfigureAll(Configuration conf, Target target) { base.ConfigureAll(conf, target); conf.SolutionFolder = "Samples"; conf.TargetPath = @"[project.RootPath]\tmp\samples\[target.Optimization]\[project.Name]"; conf.AddPrivateDependency<SharpmakeProject>(target); conf.AddPrivateDependency<SharpmakeApplicationProject>(target); conf.AddPrivateDependency<Platforms.CommonPlatformsProject>(target); conf.CsprojUserFile = new Project.Configuration.CsprojUserFileSettings { StartAction = Project.Configuration.CsprojUserFileSettings.StartActionSetting.Program, StartProgram = @"[project.RootPath]\tmp\bin\[conf.Target.Optimization]\Sharpmake.Application.exe", StartArguments = "/sources(@'[project.SharpmakeMainFile]')", WorkingDirectory = "[project.SourceRootPath]" }; } } [Generate] public class CompileCommandDatabaseProject : SampleProject { public CompileCommandDatabaseProject() { Name = "CompileCommandDatabase"; } public override void ConfigureAll(Configuration conf, Target target) { base.ConfigureAll(conf, target); conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target); } } [Generate] public class ConfigureOrderProject : SampleProject { public ConfigureOrderProject() { Name = "ConfigureOrder"; SharpmakeMainFile = "main.sharpmake.cs"; } } [Generate] public class CPPCLIProject : SampleProject { public CPPCLIProject() { Name = "CPPCLI"; SharpmakeMainFile = "CLRTest.sharpmake.cs"; } } [Generate] public class CSharpHelloWorldProject : SampleProject { public CSharpHelloWorldProject() { Name = "CSharpHelloWorld"; SharpmakeMainFile = "HelloWorld.sharpmake.cs"; } } [Generate] public class CSharpImportsProject : SampleProject { public CSharpImportsProject() { Name = "CSharpImports"; } } [Generate] public class CSharpVsixProject : SampleProject { public CSharpVsixProject() { Name = "CSharpVsix"; } } [Generate] public class CSharpWcfProject : SampleProject { public CSharpWcfProject() { Name = "CSharpWCF"; } } [Generate] public class CustomBuildStepProject : SampleProject { public CustomBuildStepProject() { Name = "CustomBuildStep"; } } [Generate] public class DotNetCoreFrameworkHelloWorldProject : SampleProject { public DotNetCoreFrameworkHelloWorldProject() { Name = "DotNetCoreFrameworkHelloWorld"; SharpmakeMainFile = "HelloWorld.sharpmake.cs"; SourceRootPath = @"[project.SharpmakeCsPath]\NetCore\[project.Name]"; } } [Generate] public class DotNetFrameworkHelloWorldProject : SampleProject { public DotNetFrameworkHelloWorldProject() { Name = "DotNetFrameworkHelloWorld"; SharpmakeMainFile = "HelloWorld.sharpmake.cs"; SourceRootPath = @"[project.SharpmakeCsPath]\NetCore\[project.Name]"; } } [Generate] public class DotNetMultiFrameworksHelloWorldProject : SampleProject { public DotNetMultiFrameworksHelloWorldProject() { Name = "DotNetMultiFrameworksHelloWorld"; SharpmakeMainFile = "HelloWorld.sharpmake.cs"; SourceRootPath = @"[project.SharpmakeCsPath]\NetCore\[project.Name]"; } } [Generate] public class DotNetOSMultiFrameworksHelloWorldProject : SampleProject { public DotNetOSMultiFrameworksHelloWorldProject() { Name = "DotNetOSMultiFrameworksHelloWorld"; SharpmakeMainFile = "HelloWorld.sharpmake.cs"; SourceRootPath = @"[project.SharpmakeCsPath]\NetCore\[project.Name]"; } } [Generate] public class FastBuildSimpleExecutable : SampleProject { public FastBuildSimpleExecutable() { Name = "FastBuildSimpleExecutable"; } } [Generate] public class HelloClangClProject : SampleProject { public HelloClangClProject() { Name = "HelloClangCl"; SharpmakeMainFile = "HelloClangCl.Main.sharpmake.cs"; // This one is special, we have .sharpmake.cs files in the codebase SourceFilesExcludeRegex.Remove(@"\\codebase\\"); } public override void ConfigureAll(Configuration conf, Target target) { base.ConfigureAll(conf, target); conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target); } } [Generate] public class HelloEventsProject : SampleProject { public HelloEventsProject() { Name = "HelloEvents"; SharpmakeMainFile = "HelloEvents.Main.sharpmake.cs"; // This one is special, we have .sharpmake.cs files in the codebase SourceFilesExcludeRegex.Remove(@"\\codebase\\"); } public override void ConfigureAll(Configuration conf, Target target) { base.ConfigureAll(conf, target); conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target); } } [Generate] public class HelloLinuxProject : SampleProject { public HelloLinuxProject() { Name = "HelloLinux"; SharpmakeMainFile = "HelloLinux.Main.sharpmake.cs"; // This one is special, we have .sharpmake.cs files in the codebase SourceFilesExcludeRegex.Remove(@"\\codebase\\"); } public override void ConfigureAll(Configuration conf, Target target) { base.ConfigureAll(conf, target); conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target); } } [Generate] public class HelloAndroidProject : SampleProject { public HelloAndroidProject() { Name = "HelloAndroid"; SharpmakeMainFile = "HelloAndroid.Main.sharpmake.cs"; // This one is special, we have .sharpmake.cs files in the codebase SourceFilesExcludeRegex.Remove(@"\\codebase\\"); } public override void ConfigureAll(Configuration conf, Target target) { base.ConfigureAll(conf, target); conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target); } } [Generate] public class HelloAndroidAgdeProject : SampleProject { public HelloAndroidAgdeProject() { Name = "HelloAndroidAgde"; SharpmakeMainFile = "HelloAndroidAgde.Main.sharpmake.cs"; // This one is special, we have .sharpmake.cs files in the codebase SourceFilesExcludeRegex.Remove(@"\\codebase\\"); } public override void ConfigureAll(Configuration conf, Target target) { base.ConfigureAll(conf, target); conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target); } } [Generate] public class HelloWorldProject : SampleProject { public HelloWorldProject() { Name = "HelloWorld"; } } [Generate] public class HelloXCodeProject : SampleProject { public HelloXCodeProject() { Name = "HelloXCode"; SharpmakeMainFile = "HelloXCode.Main.sharpmake.cs"; // This one is special, we have .sharpmake.cs files in the codebase SourceFilesExcludeRegex.Remove(@"\\codebase\\"); } public override void ConfigureAll(Configuration conf, Target target) { base.ConfigureAll(conf, target); conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target); } } [Generate] public class PackageReferencesProject : SampleProject { public PackageReferencesProject() { Name = "PackageReferences"; } } [Generate] public class QTFileCustomBuildProject : SampleProject { public QTFileCustomBuildProject() { Name = "QTFileCustomBuild"; } } [Generate] public class SimpleExeLibDependencyProject : SampleProject { public SimpleExeLibDependencyProject() { Name = "SimpleExeLibDependency"; } } [Generate] public class VcpkgProject : SampleProject { public VcpkgProject() { Name = "vcpkg"; SharpmakeMainFile = @"sharpmake\main.sharpmake.cs"; } } }
// // Thread.cs // // Author: // Zachary Gramana <[email protected]> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ namespace Sharpen { using System; using System.Threading; using System.Collections.Generic; internal class Thread : Runnable { private static ThreadGroup defaultGroup = new ThreadGroup (); private bool interrupted; private Runnable runnable; private ThreadGroup tgroup; private System.Threading.Thread thread; [ThreadStatic] private static Sharpen.Thread wrapperThread; public Thread () : this(null, null, null) { } public Thread (string name) : this (null, null, name) { } public Thread (ThreadGroup grp, string name) : this (null, grp, name) { } public Thread (Runnable runnable): this (runnable, null, null) { } public Thread (Runnable runnable, string name): this (runnable, null, name) { } Thread (Runnable runnable, ThreadGroup grp, string name) { thread = new System.Threading.Thread (new ThreadStart (InternalRun)); this.runnable = runnable ?? this; tgroup = grp ?? defaultGroup; tgroup.Add (this); if (name != null) thread.Name = name; } private Thread (System.Threading.Thread t) { thread = t; tgroup = defaultGroup; tgroup.Add (this); } public static Sharpen.Thread CurrentThread () { if (wrapperThread == null) { wrapperThread = new Sharpen.Thread (System.Threading.Thread.CurrentThread); } return wrapperThread; } public string GetName () { return thread.Name; } public ThreadGroup GetThreadGroup () { return tgroup; } private void InternalRun () { wrapperThread = this; try { runnable.Run (); } catch (Exception exception) { Console.WriteLine (exception); } finally { tgroup.Remove (this); } } public static void Yield () { } public void Interrupt () { lock (thread) { interrupted = true; thread.Interrupt (); } } public static bool Interrupted () { if (Sharpen.Thread.wrapperThread == null) { return false; } Sharpen.Thread wrapperThread = Sharpen.Thread.wrapperThread; lock (wrapperThread) { bool interrupted = Sharpen.Thread.wrapperThread.interrupted; Sharpen.Thread.wrapperThread.interrupted = false; return interrupted; } } public bool IsAlive () { return thread.IsAlive; } public void Join () { thread.Join (); } public void Join (long timeout) { thread.Join ((int)timeout); } public virtual void Run () { } public void SetDaemon (bool daemon) { thread.IsBackground = daemon; } public void SetName (string name) { thread.Name = name; } public static void Sleep (long milis) { System.Threading.Thread.Sleep ((int)milis); } public void Start () { thread.Start (); } public void Abort () { thread.Abort (); } } internal class ThreadGroup { private List<Thread> threads = new List<Thread> (); public ThreadGroup() { } public ThreadGroup (string name) { } internal void Add (Thread t) { lock (threads) { threads.Add (t); } } internal void Remove (Thread t) { lock (threads) { threads.Remove (t); } } public int Enumerate (Thread[] array) { lock (threads) { int count = Math.Min (array.Length, threads.Count); threads.CopyTo (0, array, 0, count); return count; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using Xunit; public class RegexUnicodeCharTests { // This test case checks the unicode-aware features in theregex engine. private const Int32 MaxUnicodeRange = 2 << 15;//we are adding 0's here? [Fact] public static void RegexUnicodeChar() { //////////// Global Variables used for all tests String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; Char ch1; List<Char> alstValidChars; List<Char> alstInvalidChars; Int32 iCharCount; Int32 iNonCharCount; String pattern; String input; Regex regex; Match match; Int32 iNumLoop; Int32 iWordCharLength; Int32 iNonWordCharLength; StringBuilder sbldr1; StringBuilder sbldr2; Random random; try { ///////////////////////// START TESTS //////////////////////////// /////////////////////////////////////////////////////////////////// //[]Regex engine is Unicode aware now for the \w and \d character classes // \s is not - i.e. it still only recognizes the ASCII space separators, not Unicode ones // The new character classes for this: //[\p{L1}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}] iCountTestcases++; alstValidChars = new List<Char>(); alstInvalidChars = new List<Char>(); for (int i = 0; i < MaxUnicodeRange; i++) { ch1 = (Char)i; switch (CharUnicodeInfo.GetUnicodeCategory(ch1)) { case UnicodeCategory.UppercaseLetter: //Lu case UnicodeCategory.LowercaseLetter: //Li case UnicodeCategory.TitlecaseLetter: // Lt case UnicodeCategory.ModifierLetter: // Lm case UnicodeCategory.OtherLetter: // Lo case UnicodeCategory.DecimalDigitNumber: // Nd // case UnicodeCategory.LetterNumber: // ?? // case UnicodeCategory.OtherNumber: // ?? case UnicodeCategory.NonSpacingMark: // case UnicodeCategory.SpacingCombiningMark: // Mc case UnicodeCategory.ConnectorPunctuation: // Pc alstValidChars.Add(ch1); break; default: alstInvalidChars.Add(ch1); break; } } //[]\w - we will create strings from valid characters that form \w and make sure that the regex engine catches this. //Build a random string with valid characters followed by invalid characters iCountTestcases++; random = new Random(-55); pattern = @"\w*"; regex = new Regex(pattern); iNumLoop = 100; iWordCharLength = 10; iCharCount = alstValidChars.Count; iNonCharCount = alstInvalidChars.Count; iNonWordCharLength = 15; for (int i = 0; i < iNumLoop; i++) { sbldr1 = new StringBuilder(); sbldr2 = new StringBuilder(); for (int j = 0; j < iWordCharLength; j++) { ch1 = alstValidChars[random.Next(iCharCount)]; sbldr1.Append(ch1); sbldr2.Append(ch1); } for (int j = 0; j < iNonWordCharLength; j++) sbldr1.Append(alstInvalidChars[random.Next(iNonCharCount)]); input = sbldr1.ToString(); match = regex.Match(input); if (!match.Success || (match.Index != 0) || (match.Length != iWordCharLength) || !(match.Value.Equals(sbldr2.ToString())) ) { iCountErrors++; Console.WriteLine("Err_753wfgg_" + i + "! Error detected: input-{0}", input); Console.WriteLine("Match index={0}, length={1}, value={2}, match.Value.Equals(expected)={3}\n", match.Index, match.Length, match.Value, match.Value.Equals(sbldr2.ToString())); if (match.Length > iWordCharLength) { Console.WriteLine("FAIL!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n{0}={1}", (int)match.Value[iWordCharLength], CharUnicodeInfo.GetUnicodeCategory(match.Value[iWordCharLength])); } } match = match.NextMatch(); do { //This is tedious. But we report empty Matches for each of the non-matching characters!!! //duh!!! because we say so on the pattern - remember what * stands for :-) if (!match.Value.Equals(String.Empty) || (match.Length != 0) ) { iCountErrors++; Console.WriteLine("Err_2975sg_" + i + "! Error detected: input-{0}", input); Console.WriteLine("Match index={0}, length={1}, value={2}\n", match.Index, match.Length, match.Value); } match = match.NextMatch(); } while (match.Success); } //[]Build a random string with invalid characters followed by valid characters and then again invalid iCountTestcases++; random = new Random(-55); pattern = @"\w+"; regex = new Regex(pattern); iNumLoop = 500; iWordCharLength = 10; iCharCount = alstValidChars.Count; iNonCharCount = alstInvalidChars.Count; iNonWordCharLength = 15; for (int i = 0; i < iNumLoop; i++) { sbldr1 = new StringBuilder(); sbldr2 = new StringBuilder(); for (int j = 0; j < iNonWordCharLength; j++) sbldr1.Append(alstInvalidChars[random.Next(iNonCharCount)]); for (int j = 0; j < iWordCharLength; j++) { ch1 = alstValidChars[random.Next(iCharCount)]; sbldr1.Append(ch1); sbldr2.Append(ch1); } for (int j = 0; j < iNonWordCharLength; j++) sbldr1.Append(alstInvalidChars[random.Next(iNonCharCount)]); input = sbldr1.ToString(); match = regex.Match(input); if (!match.Success || (match.Index != iNonWordCharLength) || (match.Length != iWordCharLength) || !(match.Value.Equals(sbldr2.ToString())) ) { iCountErrors++; Console.WriteLine("Err_2975sgf_" + i + "! Error detected: input-{0}", input); } match = match.NextMatch(); if (match.Success) { iCountErrors++; Console.WriteLine("Err_246sdg_" + i + "! Error detected: input-{0}", input); } } alstValidChars = new List<Char>(); alstInvalidChars = new List<Char>(); for (int i = 0; i < MaxUnicodeRange; i++) { ch1 = (Char)i; switch (CharUnicodeInfo.GetUnicodeCategory(ch1)) { case UnicodeCategory.DecimalDigitNumber: // Nd alstValidChars.Add(ch1); break; default: alstInvalidChars.Add(ch1); break; } } //[]\d - we will create strings from valid characters that form \d and make sure that the regex engine catches this. //[]Build a random string with valid characters and then again invalid iCountTestcases++; pattern = @"\d+"; regex = new Regex(pattern); iNumLoop = 100; iWordCharLength = 10; iNonWordCharLength = 15; iCharCount = alstValidChars.Count; iNonCharCount = alstInvalidChars.Count; for (int i = 0; i < iNumLoop; i++) { sbldr1 = new StringBuilder(); sbldr2 = new StringBuilder(); for (int j = 0; j < iWordCharLength; j++) { ch1 = alstValidChars[random.Next(iCharCount)]; sbldr1.Append(ch1); sbldr2.Append(ch1); } for (int j = 0; j < iNonWordCharLength; j++) sbldr1.Append(alstInvalidChars[random.Next(iNonCharCount)]); input = sbldr1.ToString(); match = regex.Match(input); if (!match.Success || (match.Index != 0) || (match.Length != iWordCharLength) || !(match.Value.Equals(sbldr2.ToString())) ) { iCountErrors++; Console.WriteLine("Err_245sfg_" + i + "! Error detected: input-{0}", input); } match = match.NextMatch(); if (match.Success) { iCountErrors++; Console.WriteLine("Err_29765sg_" + i + "! Error detected: input-{0}", input); } } //[]Build a random string with invalid characters, valid and then again invalid iCountTestcases++; pattern = @"\d+"; regex = new Regex(pattern); iNumLoop = 100; iWordCharLength = 10; iNonWordCharLength = 15; iCharCount = alstValidChars.Count; iNonCharCount = alstInvalidChars.Count; for (int i = 0; i < iNumLoop; i++) { sbldr1 = new StringBuilder(); sbldr2 = new StringBuilder(); for (int j = 0; j < iNonWordCharLength; j++) sbldr1.Append(alstInvalidChars[random.Next(iNonCharCount)]); for (int j = 0; j < iWordCharLength; j++) { ch1 = alstValidChars[random.Next(iCharCount)]; sbldr1.Append(ch1); sbldr2.Append(ch1); } for (int j = 0; j < iNonWordCharLength; j++) sbldr1.Append(alstInvalidChars[random.Next(iNonCharCount)]); input = sbldr1.ToString(); match = regex.Match(input); if (!match.Success || (match.Index != iNonWordCharLength) || (match.Length != iWordCharLength) || !(match.Value.Equals(sbldr2.ToString())) ) { iCountErrors++; Console.WriteLine("Err_29756tsg_" + i + "! Error detected: input-{0}", input); } match = match.NextMatch(); if (match.Success) { iCountErrors++; Console.WriteLine("Err_27sjhr_" + i + "! Error detected: input-{0}", input); } } /////////////////////////////////////////////////////////////////// /////////////////////////// END TESTS ///////////////////////////// } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics Assert.Equal(0, iCountErrors); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Common { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; /// <summary> /// /// </summary> public static class PathUtility { private static readonly Regex UriWithProtocol = new Regex(@"^\w{2,}\:", RegexOptions.Compiled); private static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars(); private static readonly char[] InvalidPathChars = Path.GetInvalidPathChars(); private static readonly string InvalidFileNameCharsRegexString = $"[{Regex.Escape(new string(InvalidFileNameChars))}]"; // refers to http://index/?query=urlencode&rightProject=System&file=%5BRepoRoot%5D%5CNDP%5Cfx%5Csrc%5Cnet%5CSystem%5CNet%5Cwebclient.cs&rightSymbol=fptyy6owkva8 private static readonly string NeedUrlEncodeFileNameCharsRegexString = "[^0-9a-zA-Z-_.!*()]"; private static readonly string InvalidOrNeedUrlEncodeFileNameCharsRegexString = $"{InvalidFileNameCharsRegexString}|{NeedUrlEncodeFileNameCharsRegexString}"; private static readonly Regex InvalidOrNeedUrlEncodeFileNameCharsRegex = new Regex(InvalidOrNeedUrlEncodeFileNameCharsRegexString, RegexOptions.Compiled); public static bool IsPathCaseInsensitive() { return Environment.OSVersion.Platform < PlatformID.Unix; } public static string ToValidFilePath(this string input, char replacement = '_') { if (string.IsNullOrEmpty(input)) { return Path.GetRandomFileName(); } string validPath = new string(input.Select(s => InvalidFileNameChars.Contains(s) ? replacement : s).ToArray()); return validPath; } public static string ToCleanUrlFileName(this string input, string replacement = "-") { if (string.IsNullOrEmpty(input)) { return Path.GetRandomFileName(); } return InvalidOrNeedUrlEncodeFileNameCharsRegex.Replace(input, replacement); } public static void SaveFileListToFile(List<string> fileList, string filePath) { if (string.IsNullOrWhiteSpace(filePath) || fileList == null || fileList.Count == 0) { return; } using (StreamWriter writer = new StreamWriter(filePath)) { fileList.ForEach(s => writer.WriteLine(s)); } } public const string ListFileExtension = ".list"; public static List<string> GetFileListFromFile(string filePath) { if (string.IsNullOrWhiteSpace(filePath)) { return null; } List<string> fileList = new List<string>(); if (Path.GetExtension(filePath) == ListFileExtension) { using (StreamReader reader = new StreamReader(filePath)) { while (!reader.EndOfStream) { fileList.Add(reader.ReadLine()); } } } return fileList; } /// <summary> /// http://stackoverflow.com/questions/422090/in-c-sharp-check-that-filename-is-possibly-valid-not-that-it-exists /// </summary> /// <param name="path"></param> /// <returns></returns> public static bool IsVaildFilePath(string path) { FileInfo fi = null; try { fi = new FileInfo(path); } catch (ArgumentException) { } catch (PathTooLongException) { } catch (NotSupportedException) { } return fi != null; } /// <summary> /// Creates a relative path from one file or folder to another. /// </summary> /// <param name="basePath">Contains the directory that defines the start of the relative path.</param> /// <param name="absolutePath">Contains the path that defines the endpoint of the relative path.</param> /// <returns>The relative path from the start directory to the end path.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="UriFormatException"></exception> /// <exception cref="InvalidOperationException"></exception> public static string MakeRelativePath(string basePath, string absolutePath) { if (string.IsNullOrEmpty(basePath)) { return absolutePath; } if (string.IsNullOrEmpty(absolutePath)) { return null; } if (FilePathComparer.OSPlatformSensitiveComparer.Equals(basePath, absolutePath)) { return string.Empty; } // Append / to the directory if (basePath[basePath.Length - 1] != '/') { basePath = basePath + "/"; } Uri fromUri = new Uri(Path.GetFullPath(basePath)); Uri toUri = new Uri(Path.GetFullPath(absolutePath)); if (fromUri.Scheme != toUri.Scheme) { // path can't be made relative. return absolutePath; } Uri relativeUri = fromUri.MakeRelativeUri(toUri); string relativePath = Uri.UnescapeDataString(relativeUri.ToString()); if (toUri.Scheme.ToUpperInvariant() == "FILE") { relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); } return relativePath.BackSlashToForwardSlash(); } public static IEnumerable<string> CopyFilesToFolder(this IEnumerable<string> files, string sourceFolder, string destinationFolder, bool overwrite, Action<string> messageHandler, Func<string, bool> errorHandler) { IList<string> targetFiles = new List<string>(); if (files == null) { return null; } if (FilePathComparer.OSPlatformSensitiveComparer.Equals(sourceFolder, destinationFolder)) { return null; } foreach (var file in files) { try { var relativePath = MakeRelativePath(sourceFolder, file); var destinationPath = string.IsNullOrEmpty(destinationFolder) ? relativePath : Path.Combine(destinationFolder, relativePath); if (!FilePathComparer.OSPlatformSensitiveComparer.Equals(file, destinationPath)) { messageHandler?.Invoke(string.Format("Copying file from '{0}' to '{1}'", file, destinationPath)); var targetDirectory = Path.GetDirectoryName(destinationPath); if (!string.IsNullOrEmpty(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } File.Copy(file, destinationPath, overwrite); targetFiles.Add(destinationPath); } else { messageHandler?.Invoke(string.Format("{0} is already latest.", destinationPath)); } } catch (Exception e) { if (!overwrite) { if (e is IOException) { continue; } } if (errorHandler?.Invoke(e.Message) ?? false) { continue; } else { throw; } } } if (targetFiles.Count == 0) { return null; } return targetFiles; } public static string GetFullPath(string folder, string href) { if (string.IsNullOrEmpty(href)) { return null; } if (string.IsNullOrEmpty(folder)) { return href; } return Path.GetFullPath(Path.Combine(folder, href)); } public static void CopyFile(string path, string targetPath, bool overwrite = false) { if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(targetPath)) { return; } if (FilePathComparer.OSPlatformSensitiveComparer.Equals(path, targetPath)) { return; } var targetFolder = Path.GetDirectoryName(targetPath); if (!string.IsNullOrEmpty(targetFolder)) { Directory.CreateDirectory(targetFolder); } File.Copy(path, targetPath, overwrite); } public static bool IsRelativePath(string path) { if (string.IsNullOrEmpty(path)) { return false; } // IsWellFormedUriString does not try to escape characters such as '\' ' ', '(', ')' and etc. first. Use TryCreate instead if (Uri.TryCreate(path, UriKind.Absolute, out Uri absoluteUri)) { return false; } if (UriWithProtocol.IsMatch(path)) { return false; } foreach (var ch in InvalidPathChars) { if (path.Contains(ch)) { return false; } } return !Path.IsPathRooted(path); } /// <summary> /// Also change backslash to forward slash /// </summary> /// <param name="path"></param> /// <param name="kind"></param> /// <param name="basePath"></param> /// <returns></returns> public static string FormatPath(this string path, UriKind kind, string basePath = null) { if (kind == UriKind.RelativeOrAbsolute) { return path.BackSlashToForwardSlash(); } if (kind == UriKind.Absolute) { return Path.GetFullPath(path).BackSlashToForwardSlash(); } if (kind == UriKind.Relative) { if (string.IsNullOrEmpty(basePath)) { return path.BackSlashToForwardSlash(); } return MakeRelativePath(basePath, path).BackSlashToForwardSlash(); } return null; } public static bool IsPathUnderSpecificFolder(string path, string folder) { if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(folder)) { return false; } return NormalizePath(path).StartsWith(NormalizePath(folder) + Path.AltDirectorySeparatorChar); } public static string NormalizePath(string path) { if (string.IsNullOrEmpty(path)) { return path; } return Path.GetFullPath(path).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); } public static bool IsDirectory(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException($"{nameof(path)} should not be null or empty string"); } return File.GetAttributes(path).HasFlag(FileAttributes.Directory); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.Rendering; namespace UnityEngine.Experimental.Rendering.HDPipeline { // This must return a float in the range [0.0f...1.0f]. It is a lerp factor between min screen fraction and max screen fraction. public delegate float PerformDynamicRes(); public enum DynamicResScalePolicyType { // If this is the chosen option, then the HDDynamicResolutionHandler expects the m_DynamicResMethod to return a screen percentage to. // The value set will be clamped between the min and max percentage set on the HDRP Asset. ReturnsPercentage, // If this is the chosen option, then the HDDynamicResolutionHandler expects the m_DynamicResMethod to return a lerp factor t such as // current_screen_percentage = lerp(min percentage, max percentage, t). ReturnsMinMaxLerpFactor } public class HDDynamicResolutionHandler { private bool m_Enabled = false; private float m_MinScreenFraction = 1.0f; private float m_MaxScreenFraction = 1.0f; private float m_CurrentFraction = 1.0f; private float m_PrevFraction = -1.0f; private bool m_ForcingRes = false; private bool m_CurrentCameraRequest = true; private bool m_ForceSoftwareFallback = false; private float m_PrevHWScaleWidth = 1.0f; private float m_PrevHWScaleHeight = 1.0f; private Vector2Int m_LastScaledSize = new Vector2Int(0, 0); private DynamicResScalePolicyType m_ScalerType = DynamicResScalePolicyType.ReturnsMinMaxLerpFactor; // Debug public Vector2Int cachedOriginalSize { get; private set; } public bool hasSwitchedResolution { get; private set; } public DynamicResUpscaleFilter filter { get; set; } private DynamicResolutionType type; private PerformDynamicRes m_DynamicResMethod = null; private static HDDynamicResolutionHandler s_Instance = new HDDynamicResolutionHandler(); public static HDDynamicResolutionHandler instance { get { return s_Instance; } } private HDDynamicResolutionHandler() { m_DynamicResMethod = DefaultDynamicResMethod; filter = DynamicResUpscaleFilter.Bilinear; } // TODO: Eventually we will need to provide a good default implementation for this. static public float DefaultDynamicResMethod() { return 1.0f; } private void ProcessSettings(GlobalDynamicResolutionSettings settings) { m_Enabled = settings.enabled; if (!m_Enabled) { m_CurrentFraction = 1.0f; } else { type = settings.dynResType; float minScreenFrac = Mathf.Clamp(settings.minPercentage / 100.0f, 0.1f, 1.0f); m_MinScreenFraction = minScreenFrac; float maxScreenFrac = Mathf.Clamp(settings.maxPercentage / 100.0f, m_MinScreenFraction, 3.0f); m_MaxScreenFraction = maxScreenFrac; filter = settings.upsampleFilter; m_ForcingRes = settings.forceResolution; if (m_ForcingRes) { float fraction = Mathf.Clamp(settings.forcedPercentage / 100.0f, 0.1f, 1.5f); m_CurrentFraction = fraction; } } } static public void SetDynamicResScaler(PerformDynamicRes scaler, DynamicResScalePolicyType scalerType = DynamicResScalePolicyType.ReturnsMinMaxLerpFactor) { s_Instance.m_ScalerType = scalerType; s_Instance.m_DynamicResMethod = scaler; } public void SetCurrentCameraRequest(bool cameraRequest) { m_CurrentCameraRequest = cameraRequest; } public void Update(GlobalDynamicResolutionSettings settings, Action OnResolutionChange = null) { ProcessSettings(settings); if (!m_Enabled) return; if (!m_ForcingRes) { if(m_ScalerType == DynamicResScalePolicyType.ReturnsMinMaxLerpFactor) { float currLerp = m_DynamicResMethod(); float lerpFactor = Mathf.Clamp(currLerp, 0.0f, 1.0f); m_CurrentFraction = Mathf.Lerp(m_MinScreenFraction, m_MaxScreenFraction, lerpFactor); } else if(m_ScalerType == DynamicResScalePolicyType.ReturnsPercentage) { float percentageRequested = Mathf.Max(m_DynamicResMethod(), 5.0f); m_CurrentFraction = Mathf.Clamp(percentageRequested / 100.0f, m_MinScreenFraction, m_MaxScreenFraction); } } if (m_CurrentFraction != m_PrevFraction) { m_PrevFraction = m_CurrentFraction; hasSwitchedResolution = true; if (!m_ForceSoftwareFallback && type == DynamicResolutionType.Hardware) { ScalableBufferManager.ResizeBuffers(m_CurrentFraction, m_CurrentFraction); } OnResolutionChange(); } else { // Unity can change the scale factor by itself so we need to trigger the Action if that happens as well. if (!m_ForceSoftwareFallback && type == DynamicResolutionType.Hardware) { if(ScalableBufferManager.widthScaleFactor != m_PrevHWScaleWidth || ScalableBufferManager.heightScaleFactor != m_PrevHWScaleHeight) { OnResolutionChange(); } } hasSwitchedResolution = false; } m_PrevHWScaleWidth = ScalableBufferManager.widthScaleFactor; m_PrevHWScaleHeight = ScalableBufferManager.heightScaleFactor; } public bool SoftwareDynamicResIsEnabled() { return m_CurrentCameraRequest && m_Enabled && m_CurrentFraction != 1.0f && (m_ForceSoftwareFallback || type == DynamicResolutionType.Software); } public bool HardwareDynamicResIsEnabled() { return !m_ForceSoftwareFallback && m_CurrentCameraRequest && m_Enabled && type == DynamicResolutionType.Hardware; } public bool RequestsHardwareDynamicResolution() { if (m_ForceSoftwareFallback) return false; return type == DynamicResolutionType.Hardware; } public bool DynamicResolutionEnabled() { return m_CurrentCameraRequest && m_Enabled && m_CurrentFraction != 1.0f; } public void ForceSoftwareFallback() { m_ForceSoftwareFallback = true; } public Vector2Int GetRTHandleScale(Vector2Int size) { cachedOriginalSize = size; if (!m_Enabled || !m_CurrentCameraRequest) { return size; } float scaleFractionX = m_CurrentFraction; float scaleFractionY = m_CurrentFraction; if (!m_ForceSoftwareFallback && type == DynamicResolutionType.Hardware) { scaleFractionX = ScalableBufferManager.widthScaleFactor; scaleFractionY = ScalableBufferManager.heightScaleFactor; } Vector2Int scaledSize = new Vector2Int(Mathf.CeilToInt(size.x * scaleFractionX), Mathf.CeilToInt(size.y * scaleFractionY)); if (m_ForceSoftwareFallback || type != DynamicResolutionType.Hardware) { scaledSize.x += (1 & scaledSize.x); scaledSize.y += (1 & scaledSize.y); } m_LastScaledSize = scaledSize; return scaledSize; } public float GetCurrentScale() { return (m_Enabled && m_CurrentCameraRequest) ? m_CurrentFraction : 1.0f; } public Vector2Int GetLastScaledSize() { return m_LastScaledSize; } } }
/** * Couchbase Lite for .NET * * Original iOS version by Jens Alfke * Android Port by Marty Schoch, Traun Leyden * C# Port by Zack Gramana * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System.Collections.Generic; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite { /// <summary>Stores information about a revision -- its docID, revID, and whether it's deleted. /// </summary> /// <remarks> /// Stores information about a revision -- its docID, revID, and whether it's deleted. /// It can also store the sequence number and document contents (they can be added after creation). /// </remarks> public sealed class SavedRevision : Revision { private RevisionInternal revisionInternal; private bool checkedProperties; /// <summary>Constructor</summary> /// <exclude></exclude> [InterfaceAudience.Private] internal SavedRevision(Document document, RevisionInternal revision) : base(document ) { this.revisionInternal = revision; } /// <summary>Constructor</summary> /// <exclude></exclude> [InterfaceAudience.Private] internal SavedRevision(Database database, RevisionInternal revision) : this(database .GetDocument(revision.GetDocId()), revision) { } /// <summary>Get the document this is a revision of</summary> [InterfaceAudience.Public] public override Document GetDocument() { return document; } /// <summary>Has this object fetched its contents from the database yet?</summary> [InterfaceAudience.Public] public bool ArePropertiesAvailable() { return revisionInternal.GetProperties() != null; } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [InterfaceAudience.Public] public override IList<Couchbase.Lite.SavedRevision> GetRevisionHistory() { IList<Couchbase.Lite.SavedRevision> revisions = new AList<Couchbase.Lite.SavedRevision >(); IList<RevisionInternal> internalRevisions = GetDatabase().GetRevisionHistory(revisionInternal ); foreach (RevisionInternal internalRevision in internalRevisions) { if (internalRevision.GetRevId().Equals(GetId())) { revisions.AddItem(this); } else { Couchbase.Lite.SavedRevision revision = document.GetRevisionFromRev(internalRevision ); revisions.AddItem(revision); } } Sharpen.Collections.Reverse(revisions); return Sharpen.Collections.UnmodifiableList(revisions); } /// <summary> /// Creates a new mutable child revision whose properties and attachments are initially identical /// to this one's, which you can modify and then save. /// </summary> /// <remarks> /// Creates a new mutable child revision whose properties and attachments are initially identical /// to this one's, which you can modify and then save. /// </remarks> /// <returns></returns> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [InterfaceAudience.Public] public UnsavedRevision CreateRevision() { UnsavedRevision newRevision = new UnsavedRevision(document, this); return newRevision; } /// <summary>Creates and saves a new revision with the given properties.</summary> /// <remarks> /// Creates and saves a new revision with the given properties. /// This will fail with a 412 error if the receiver is not the current revision of the document. /// </remarks> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [InterfaceAudience.Public] public Couchbase.Lite.SavedRevision CreateRevision(IDictionary<string, object> properties ) { bool allowConflict = false; return document.PutProperties(properties, revisionInternal.GetRevId(), allowConflict ); } [InterfaceAudience.Public] public override string GetId() { return revisionInternal.GetRevId(); } [InterfaceAudience.Public] public override bool IsDeletion() { return revisionInternal.IsDeleted(); } /// <summary>The contents of this revision of the document.</summary> /// <remarks> /// The contents of this revision of the document. /// Any keys in the dictionary that begin with "_", such as "_id" and "_rev", contain CouchbaseLite metadata. /// </remarks> /// <returns>contents of this revision of the document.</returns> [InterfaceAudience.Public] public override IDictionary<string, object> GetProperties() { IDictionary<string, object> properties = revisionInternal.GetProperties(); if (properties == null && !checkedProperties) { if (LoadProperties() == true) { properties = revisionInternal.GetProperties(); } checkedProperties = true; } return Sharpen.Collections.UnmodifiableMap(properties); } /// <summary>Deletes the document by creating a new deletion-marker revision.</summary> /// <remarks>Deletes the document by creating a new deletion-marker revision.</remarks> /// <returns></returns> /// <exception cref="CouchbaseLiteException">CouchbaseLiteException</exception> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [InterfaceAudience.Public] public Couchbase.Lite.SavedRevision DeleteDocument() { return CreateRevision(null); } [InterfaceAudience.Public] public override Couchbase.Lite.SavedRevision GetParent() { return GetDocument().GetRevisionFromRev(GetDatabase().GetParentRevision(revisionInternal )); } [InterfaceAudience.Public] public override string GetParentId() { RevisionInternal parRev = GetDocument().GetDatabase().GetParentRevision(revisionInternal ); if (parRev == null) { return null; } return parRev.GetRevId(); } [InterfaceAudience.Public] internal override long GetSequence() { long sequence = revisionInternal.GetSequence(); if (sequence == 0 && LoadProperties()) { sequence = revisionInternal.GetSequence(); } return sequence; } /// <exclude></exclude> [InterfaceAudience.Private] internal bool LoadProperties() { try { RevisionInternal loadRevision = GetDatabase().LoadRevisionBody(revisionInternal, EnumSet.NoneOf<Database.TDContentOptions>()); if (loadRevision == null) { Log.W(Database.Tag, "Couldn't load body/sequence of %s" + this); return false; } revisionInternal = loadRevision; return true; } catch (CouchbaseLiteException e) { throw new RuntimeException(e); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SignalRSer.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015 FUJIWARA, Yusuke // // 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 -- License Terms -- #if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace MsgPack.Serialization.CollectionSerializers { /// <summary> /// Provides basic features for non-dictionary generic collection serializers. /// </summary> /// <typeparam name="TCollection">The type of the collection.</typeparam> /// <typeparam name="TItem">The type of the item of the collection.</typeparam> /// <remarks> /// This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility. /// If you cannot use this class, you can implement your own serializer which inherits <see cref="MessagePackSerializer{T}"/> and implements <see cref="ICollectionInstanceFactory"/>. /// </remarks> public abstract class EnumerableMessagePackSerializerBase<TCollection, TItem> : MessagePackSerializer<TCollection>, ICollectionInstanceFactory where TCollection : IEnumerable<TItem> { private readonly MessagePackSerializer<TItem> _itemSerializer; internal MessagePackSerializer<TItem> ItemSerializer { get { return this._itemSerializer; } } /// <summary> /// Initializes a new instance of the <see cref="EnumerableMessagePackSerializerBase{TCollection, TItem}"/> class. /// </summary> /// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param> /// <param name="schema"> /// The schema for collection itself or its items for the member this instance will be used to. /// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="ownerContext"/> is <c>null</c>. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] protected EnumerableMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext ) { this._itemSerializer = ownerContext.GetSerializer<TItem>( ( schema ?? PolymorphismSchema.Default ).ItemSchema ); } /// <summary> /// Creates a new collection instance with specified initial capacity. /// </summary> /// <param name="initialCapacity"> /// The initial capacy of creating collection. /// Note that this parameter may <c>0</c> for non-empty collection. /// </param> /// <returns> /// New collection instance. This value will not be <c>null</c>. /// </returns> /// <remarks> /// An author of <see cref="Unpacker" /> could implement unpacker for non-MessagePack format, /// so implementer of this interface should not rely on that <paramref name="initialCapacity" /> reflects actual items count. /// For example, JSON unpacker cannot supply collection items count efficiently. /// </remarks> /// <seealso cref="ICollectionInstanceFactory.CreateInstance"/> protected abstract TCollection CreateInstance( int initialCapacity ); object ICollectionInstanceFactory.CreateInstance( int initialCapacity ) { return this.CreateInstance( initialCapacity ); } /// <summary> /// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>. /// </summary> /// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param> /// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param> /// <exception cref="SerializationException"> /// Failed to deserialize object due to invalid unpacker state, stream content, or so. /// </exception> /// <exception cref="NotSupportedException"> /// <typeparamref name="TCollection"/> is not collection. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )] protected internal sealed override void UnpackToCore( Unpacker unpacker, TCollection collection ) { if ( !unpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } internal void UnpackToCore( Unpacker unpacker, TCollection collection, int itemsCount ) { for ( var i = 0; i < itemsCount; i++ ) { if ( !unpacker.Read() ) { throw SerializationExceptions.NewMissingItem( i ); } TItem item; if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader ) { item = this._itemSerializer.UnpackFrom( unpacker ); } else { using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { item = this._itemSerializer.UnpackFrom( subtreeUnpacker ); } } this.AddItem( collection, item ); } } /// <summary> /// When implemented by derive class, /// adds the deserialized item to the collection on <typeparamref name="TCollection"/> specific manner /// to implement <see cref="UnpackToCore(Unpacker,TCollection)"/>. /// </summary> /// <param name="collection">The collection to be added.</param> /// <param name="item">The item to be added.</param> /// <exception cref="NotSupportedException"> /// This implementation always throws it. /// </exception> protected virtual void AddItem( TCollection collection, TItem item ) { throw SerializationExceptions.NewUnpackToIsNotSupported( typeof( TCollection ), null ); } } #if UNITY internal abstract class UnityEnumerableMessagePackSerializerBase : NonGenericMessagePackSerializer, ICollectionInstanceFactory { private readonly IMessagePackSingleObjectSerializer _itemSerializer; internal IMessagePackSingleObjectSerializer ItemSerializer { get { return this._itemSerializer; } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] protected UnityEnumerableMessagePackSerializerBase( SerializationContext ownerContext, Type targetType, Type itemType, PolymorphismSchema schema ) : base( ownerContext, targetType ) { this._itemSerializer = ownerContext.GetSerializer( itemType, ( schema ?? PolymorphismSchema.Default ).ItemSchema ); } protected abstract object CreateInstance( int initialCapacity ); object ICollectionInstanceFactory.CreateInstance( int initialCapacity ) { return this.CreateInstance( initialCapacity ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )] protected internal sealed override void UnpackToCore( Unpacker unpacker, object collection ) { if ( !unpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } internal void UnpackToCore( Unpacker unpacker, object collection, int itemsCount ) { for ( var i = 0; i < itemsCount; i++ ) { if ( !unpacker.Read() ) { throw SerializationExceptions.NewMissingItem( i ); } object item; if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader ) { item = this._itemSerializer.UnpackFrom( unpacker ); } else { using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { item = this._itemSerializer.UnpackFrom( subtreeUnpacker ); } } this.AddItem( collection, item ); } } protected virtual void AddItem( object collection, object item ) { throw SerializationExceptions.NewUnpackToIsNotSupported( this.TargetType, null ); } } #endif // UNITY }
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft 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 C5; using NUnit.Framework; using SCG = System.Collections.Generic; using System.Reflection; namespace C5UnitTests.Templates.Events { public abstract class CollectionValueTester<TCollection, TItem> : GenericCollectionTester<TCollection, EventTypeEnum> where TCollection : ICollectionValue<TItem> { protected TCollection collection; protected CollectionEventList<TItem> seen; protected EventTypeEnum listenTo; protected void listen() { seen.Listen(collection, listenTo); } public override void SetUp(TCollection list, EventTypeEnum testSpec) { this.collection = list; listenTo = testSpec; seen = new CollectionEventList<TItem>(EqualityComparer<TItem>.Default); } public SCG.IEnumerable<EventTypeEnum> SpecsBasic { get { CircularQueue<EventTypeEnum> specs = new CircularQueue<EventTypeEnum>(); //foreach (EventTypeEnum listenTo in Enum.GetValues(typeof(EventTypeEnum))) // if ((listenTo & ~EventTypeEnum.Basic) == 0) // specs.Enqueue(listenTo); //specs.Enqueue(EventTypeEnum.Added | EventTypeEnum.Removed); for (int spec = 0; spec <= (int)EventTypeEnum.Basic; spec++) specs.Enqueue((EventTypeEnum)spec); return specs; } } public SCG.IEnumerable<EventTypeEnum> SpecsAll { get { CircularQueue<EventTypeEnum> specs = new CircularQueue<EventTypeEnum>(); //foreach (EventTypeEnum listenTo in Enum.GetValues(typeof(EventTypeEnum))) // specs.Enqueue(listenTo); //specs.Enqueue(EventTypeEnum.Added | EventTypeEnum.Removed); for (int spec = 0; spec <= (int)EventTypeEnum.All; spec++) specs.Enqueue((EventTypeEnum)spec); return specs; } } } public abstract class CollectionValueTester<U> : CollectionValueTester<U, int> where U : ICollectionValue<int> { } public class ExtensibleTester<U> : CollectionValueTester<U> where U : IExtensible<int> { public override SCG.IEnumerable<EventTypeEnum> GetSpecs() { return SpecsBasic; } [Test] public virtual void Listenable() { Assert.AreEqual(EventTypeEnum.Basic, collection.ListenableEvents); Assert.AreEqual(EventTypeEnum.None, collection.ActiveEvents); listen(); Assert.AreEqual(listenTo, collection.ActiveEvents); } [Test] public void Add() { listen(); seen.Check(new CollectionEvent<int>[0]); collection.Add(23); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(23, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); } [Test] public void AddAll() { for (int i = 0; i < 10; i++) { collection.Add(10 * i + 5); } listen(); collection.AddAll<int>(new int[] { 45, 200, 56, 67 }); seen.Check(collection.AllowsDuplicates ? collection.DuplicatesByCounting ? new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(45, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(200, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(55, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(65, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)} : new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(45, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(200, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(56, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(67, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)} : new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(200, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.AddAll<int>(new int[] { }); seen.Check(new CollectionEvent<int>[] { }); } } public class CollectionTester<U> : ExtensibleTester<U> where U : ICollection<int> { [Test] public void Update() { collection.Add(4); collection.Add(54); collection.Add(56); collection.Add(8); listen(); collection.Update(53); seen.Check( collection.AllowsDuplicates ? collection.DuplicatesByCounting ? new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(54, 2), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(53, 2), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) } : new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(54, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(53, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) } : new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(54, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(53, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.Update(67); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void FindOrAdd() { collection.Add(4); collection.Add(56); collection.Add(8); listen(); int val = 53; collection.FindOrAdd(ref val); seen.Check(new CollectionEvent<int>[] { }); val = 67; collection.FindOrAdd(ref val); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(67, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); } [Test] public void UpdateOrAdd() { collection.Add(4); collection.Add(56); collection.Add(8); listen(); int val = 53; collection.UpdateOrAdd(val); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(53, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); val = 67; collection.UpdateOrAdd(val); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(67, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.UpdateOrAdd(51, out val); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(53, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(51, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); val = 67; collection.UpdateOrAdd(81, out val); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(81, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); } [Test] public void RemoveItem() { collection.Add(4); collection.Add(56); collection.Add(18); listen(); collection.Remove(53); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.Remove(11); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(18, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); } [Test] public void RemoveAll() { for (int i = 0; i < 10; i++) { collection.Add(10 * i + 5); } listen(); collection.RemoveAll<int>(new int[] { 32, 187, 45 }); //TODO: the order depends on internals of the HashSet seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(35, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(45, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.RemoveAll<int>(new int[] { 200, 300 }); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void RetainAll() { for (int i = 0; i < 10; i++) { collection.Add(10 * i + 5); } listen(); collection.RetainAll<int>(new int[] { 32, 187, 45, 62, 75, 82, 95, 2 }); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(15, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(25, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(55, 1), collection), //new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(75, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.RetainAll<int>(new int[] { 32, 187, 45, 62, 75, 82, 95, 2 }); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void RemoveAllCopies() { for (int i = 0; i < 10; i++) { collection.Add(3 * i + 5); } listen(); collection.RemoveAllCopies(14); seen.Check( collection.AllowsDuplicates ? collection.DuplicatesByCounting ? new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(11, 3), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)} : new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(11, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(14, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(17, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)} : new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(11, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.RemoveAllCopies(14); seen.Check(new CollectionEvent<int>[] { }); } [Test] public virtual void Clear() { collection.Add(4); collection.Add(56); collection.Add(8); listen(); collection.Clear(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Cleared, new ClearedEventArgs(true, collection.AllowsDuplicates ? 3 : 2), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.Clear(); seen.Check(new CollectionEvent<int>[] { }); } } public class IndexedTester<U> : CollectionTester<U> where U : IIndexed<int> { [Test] public void RemoveAt() { collection.Add(4); collection.Add(16); collection.Add(28); listen(); collection.RemoveAt(1); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(16,1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(16, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); } [Test] public void RemoveInterval() { collection.Add(4); collection.Add(56); collection.Add(18); listen(); collection.RemoveInterval(1, 2); seen.Check(new CollectionEvent<int>[] { collection is IList<int> ? new CollectionEvent<int>(EventTypeEnum.Cleared, new ClearedRangeEventArgs(false,2,1), collection): new CollectionEvent<int>(EventTypeEnum.Cleared, new ClearedEventArgs(false,2), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.RemoveInterval(1, 0); seen.Check(new CollectionEvent<int>[] { }); } } public class SortedIndexedTester<U> : IndexedTester<U> where U : IIndexedSorted<int> { [Test] public void DeleteMinMax() { collection.Add(34); collection.Add(56); collection.Add(34); collection.Add(12); listen(); collection.DeleteMax(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.DeleteMin(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(12, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); } [Test] public void AddSorted() { listen(); collection.AddSorted(collection.AllowsDuplicates ? new int[] { 31, 62, 63, 93 } : new int[] { 31, 62, 93 }); seen.Check(collection.AllowsDuplicates ? collection.DuplicatesByCounting ? new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(31, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(62, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(62, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(93, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)} : new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(31, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(62, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(63, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(93, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)} : new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(31, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(62, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(93, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.AddSorted(new int[] { }); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void RemoveRange() { for (int i = 0; i < 20; i++) collection.Add(i * 10 + 5); listen(); collection.RemoveRangeFrom(173); //TODO: fix order to remove in: seen.Check( new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(195, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(185, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(175, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.RemoveRangeFromTo(83, 113); seen.Check( new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(105, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(95, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(85, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.RemoveRangeTo(33); seen.Check( new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(5, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(15, 1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(25, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.RemoveRangeFrom(173); seen.Check(new CollectionEvent<int>[] { }); collection.RemoveRangeFromTo(83, 113); seen.Check(new CollectionEvent<int>[] { }); collection.RemoveRangeTo(33); seen.Check(new CollectionEvent<int>[] { }); } } public class ListTester<U> : IndexedTester<U> where U : IList<int> { public override SCG.IEnumerable<EventTypeEnum> GetSpecs() { return SpecsAll; } [Test] public override void Listenable() { Assert.AreEqual(EventTypeEnum.All, collection.ListenableEvents); Assert.AreEqual(EventTypeEnum.None, collection.ActiveEvents); listen(); Assert.AreEqual(listenTo, collection.ActiveEvents); } [Test] public void SetThis() { collection.Add(4); collection.Add(56); collection.Add(8); listen(); collection[1] = 45; seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), collection), new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(56,1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(45, 1), collection), new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(45,1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); } [Test] public void Insert() { collection.Add(4); collection.Add(56); collection.Add(8); listen(); collection.Insert(1, 45); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(45,1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(45, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); } [Test] public void InsertAll() { collection.Add(4); collection.Add(56); collection.Add(8); listen(); collection.InsertAll<int>(1, new int[] { 666, 777, 888 }); //seen.Print(Console.Error); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(666,1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(666, 1), collection), new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(777,2), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(777, 1), collection), new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(888,3), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(888, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.InsertAll<int>(1, new int[] { }); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void InsertFirstLast() { collection.Add(4); collection.Add(56); collection.Add(18); listen(); collection.InsertFirst(45); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(45,0), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(45, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.InsertLast(88); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(88,4), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(88, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); } [Test] public void Remove() { collection.FIFO = false; collection.Add(4); collection.Add(56); collection.Add(18); listen(); collection.Remove(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(18, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.FIFO = true; collection.Remove(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(4, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); } [Test] public void RemoveFirst() { collection.Add(4); collection.Add(56); collection.Add(18); listen(); collection.RemoveFirst(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(4,0), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(4, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); } [Test] public void RemoveLast() { collection.Add(4); collection.Add(56); collection.Add(18); listen(); collection.RemoveLast(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(18,2), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(18, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); } [Test] public void Reverse() { collection.Add(4); collection.Add(56); collection.Add(8); listen(); collection.Reverse(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.View(1, 0).Reverse(); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void Sort() { collection.Add(4); collection.Add(56); collection.Add(8); listen(); collection.Sort(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.View(1, 0).Sort(); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void Shuffle() { collection.Add(4); collection.Add(56); collection.Add(8); listen(); collection.Shuffle(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.View(1, 0).Shuffle(); seen.Check(new CollectionEvent<int>[] { }); } [Test] public override void Clear() { collection.Add(4); collection.Add(56); collection.Add(18); listen(); collection.View(1, 1).Clear(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Cleared, new ClearedRangeEventArgs(false,1,1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.Clear(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Cleared, new ClearedRangeEventArgs(true,2,0), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.Clear(); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void ListDispose() { collection.Add(4); collection.Add(56); collection.Add(18); listen(); collection.View(1, 1).Dispose(); seen.Check(new CollectionEvent<int>[] { }); collection.Dispose(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Cleared, new ClearedRangeEventArgs(true,3,0), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); collection.Dispose(); seen.Check(new CollectionEvent<int>[] { }); } /* * / //[TearDown] //public void Dispose() { list = null; seen = null; } /* [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewChanged() { IList<int> w = collection.View(0, 0); w.CollectionChanged += new CollectionChangedHandler<int>(w_CollectionChanged); } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewCleared() { IList<int> w = collection.View(0, 0); w.CollectionCleared += new CollectionClearedHandler<int>(w_CollectionCleared); } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewAdded() { IList<int> w = collection.View(0, 0); w.ItemsAdded += new ItemsAddedHandler<int>(w_ItemAdded); } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewInserted() { IList<int> w = collection.View(0, 0); w.ItemInserted += new ItemInsertedHandler<int>(w_ItemInserted); } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewRemoved() { IList<int> w = collection.View(0, 0); w.ItemsRemoved += new ItemsRemovedHandler<int>(w_ItemRemoved); } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewRemovedAt() { IList<int> w = collection.View(0, 0); w.ItemRemovedAt += new ItemRemovedAtHandler<int>(w_ItemRemovedAt); } void w_CollectionChanged(object sender) { throw new NotImplementedException(); } void w_CollectionCleared(object sender, ClearedEventArgs eventArgs) { throw new NotImplementedException(); } void w_ItemAdded(object sender, ItemCountEventArgs<int> eventArgs) { throw new NotImplementedException(); } void w_ItemInserted(object sender, ItemAtEventArgs<int> eventArgs) { throw new NotImplementedException(); } void w_ItemRemoved(object sender, ItemCountEventArgs<int> eventArgs) { throw new NotImplementedException(); } void w_ItemRemovedAt(object sender, ItemAtEventArgs<int> eventArgs) { throw new NotImplementedException(); }*/ } public class StackTester<U> : CollectionValueTester<U> where U : IStack<int> { public override SCG.IEnumerable<EventTypeEnum> GetSpecs() { return SpecsBasic; } [Test] public void PushPop() { listen(); seen.Check(new CollectionEvent<int>[0]); collection.Push(23); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(23,0), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(23, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.Push(-12); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(-12,1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(-12, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.Pop(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(-12,1), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(-12, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.Pop(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(23,0), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(23, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); } } public class QueueTester<U> : CollectionValueTester<U> where U : IQueue<int> { public override SCG.IEnumerable<EventTypeEnum> GetSpecs() { return SpecsBasic; } [Test] public void EnqueueDequeue() { listen(); collection.Enqueue(67); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(67,0), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(67, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.Enqueue(2); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(2,1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(2, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.Dequeue(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(67,0), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(67, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.Dequeue(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(2,0), collection), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(2, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection)}); } } public class PriorityQueueTester<U> : ExtensibleTester<U> where U : IPriorityQueue<int> { public override System.Collections.Generic.IEnumerable<EventTypeEnum> GetSpecs() { return SpecsBasic; } [Test] public void Direct() { listen(); collection.Add(34); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(34, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.Add(56); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(56, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.AddAll<int>(new int[] { }); seen.Check(new CollectionEvent<int>[] { }); collection.Add(34); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(34, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.Add(12); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(12, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.DeleteMax(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.DeleteMin(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(12, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.AddAll<int>(new int[] { 4, 5, 6, 2 }); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(4, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(5, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(6, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(2, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection) }); } [Test] public void WithHandles() { listen(); IPriorityQueueHandle<int> handle = null, handle2; collection.Add(34); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(34, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.Add(56); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(56, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.Add(ref handle, 34); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(34, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.Add(12); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(12, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.DeleteMax(out handle2); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.DeleteMin(out handle2); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(12, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.Replace(handle, 117); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(34, 1), collection), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(117, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); collection.Delete(handle); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(117, 1), collection), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), collection), }); } } public class DictionaryTester<U> : CollectionValueTester<U, KeyValuePair<int, int>> where U : IDictionary<int, int> { public override SCG.IEnumerable<EventTypeEnum> GetSpecs() { return SpecsBasic; } [Test] public virtual void Listenable() { Assert.AreEqual(EventTypeEnum.Basic, collection.ListenableEvents); Assert.AreEqual(EventTypeEnum.None, collection.ActiveEvents); listen(); Assert.AreEqual(listenTo, collection.ActiveEvents); } [Test] public void AddAndREmove() { listen(); seen.Check(new CollectionEvent<KeyValuePair<int, int>>[0]); collection.Add(23, 45); seen.Check(new CollectionEvent<KeyValuePair<int,int>>[] { new CollectionEvent<KeyValuePair<int,int>>(EventTypeEnum.Added, new ItemCountEventArgs<KeyValuePair<int,int>>(new KeyValuePair<int,int>(23,45), 1), collection), new CollectionEvent<KeyValuePair<int,int>>(EventTypeEnum.Changed, new EventArgs(), collection)}); collection.Remove(25); seen.Check(new CollectionEvent<KeyValuePair<int, int>>[] { new CollectionEvent<KeyValuePair<int,int>>(EventTypeEnum.Removed, new ItemCountEventArgs<KeyValuePair<int,int>>(new KeyValuePair<int,int>(23,45), 1), collection), new CollectionEvent<KeyValuePair<int,int>>(EventTypeEnum.Changed, new EventArgs(), collection)}); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Linq; using NetGore; using NetGore.IO; namespace DemoGame { /// <summary> /// Represents a unique ID for an Item instance. /// </summary> [Serializable] [TypeConverter(typeof(ItemIDTypeConverter))] public struct ItemID : IComparable<ItemID>, IConvertible, IFormattable, IComparable<int>, IEquatable<int> { /// <summary> /// Represents the largest possible value of ItemID. This field is constant. /// </summary> public const int MaxValue = int.MaxValue; /// <summary> /// Represents the smallest possible value of ItemID. This field is constant. /// </summary> public const int MinValue = int.MinValue; /// <summary> /// The underlying value. This contains the actual value of the struct instance. /// </summary> readonly int _value; /// <summary> /// Initializes a new instance of the <see cref="ItemID"/> struct. /// </summary> /// <param name="value">Value to assign to the new ItemID.</param> /// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception> public ItemID(int value) { if (value < MinValue || value > MaxValue) throw new ArgumentOutOfRangeException("value"); _value = value; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="other">Another object to compare to.</param> /// <returns> /// True if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false. /// </returns> public bool Equals(ItemID other) { return other._value == _value; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">Another object to compare to.</param> /// <returns> /// True if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false. /// </returns> public override bool Equals(object obj) { return obj is ItemID && this == (ItemID)obj; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns> /// A 32-bit signed integer that is the hash code for this instance. /// </returns> public override int GetHashCode() { return _value.GetHashCode(); } /// <summary> /// Gets the raw internal value of this ItemID. /// </summary> /// <returns>The raw internal value.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public int GetRawValue() { return _value; } /// <summary> /// Reads an ItemID from an IValueReader. /// </summary> /// <param name="reader">IValueReader to read from.</param> /// <param name="name">Unique name of the value to read.</param> /// <returns>The ItemID read from the IValueReader.</returns> public static ItemID Read(IValueReader reader, string name) { var value = reader.ReadInt(name); return new ItemID(value); } /// <summary> /// Reads an ItemID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param> /// <param name="i">The index of the field to find.</param> /// <returns>The ItemID read from the <see cref="IDataRecord"/>.</returns> public static ItemID Read(IDataRecord reader, int i) { var value = reader.GetValue(i); if (value is int) return new ItemID((int)value); var convertedValue = Convert.ToInt32(value); return new ItemID(convertedValue); } /// <summary> /// Reads an ItemID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param> /// <param name="name">The name of the field to find.</param> /// <returns>The ItemID read from the <see cref="IDataRecord"/>.</returns> public static ItemID Read(IDataRecord reader, string name) { return Read(reader, reader.GetOrdinal(name)); } /// <summary> /// Reads an ItemID from an IValueReader. /// </summary> /// <param name="bitStream">BitStream to read from.</param> /// <returns>The ItemID read from the BitStream.</returns> public static ItemID Read(BitStream bitStream) { var value = bitStream.ReadInt(); return new ItemID(value); } /// <summary> /// Converts the numeric value of this instance to its equivalent string representation. /// </summary> /// <returns>The string representation of the value of this instance, consisting of a sequence /// of digits ranging from 0 to 9, without leading zeroes.</returns> public override string ToString() { return _value.ToString(); } /// <summary> /// Writes the ItemID to an IValueWriter. /// </summary> /// <param name="writer">IValueWriter to write to.</param> /// <param name="name">Unique name of the ItemID that will be used to distinguish it /// from other values when reading.</param> public void Write(IValueWriter writer, string name) { writer.Write(name, _value); } /// <summary> /// Writes the ItemID to an IValueWriter. /// </summary> /// <param name="bitStream">BitStream to write to.</param> public void Write(BitStream bitStream) { bitStream.Write(_value); } #region IComparable<int> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: /// Value /// Meaning /// Less than zero /// This object is less than the <paramref name="other"/> parameter. /// Zero /// This object is equal to <paramref name="other"/>. /// Greater than zero /// This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(int other) { return _value.CompareTo(other); } #endregion #region IComparable<ItemID> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. /// The return value has the following meanings: /// Value /// Meaning /// Less than zero /// This object is less than the <paramref name="other"/> parameter. /// Zero /// This object is equal to <paramref name="other"/>. /// Greater than zero /// This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(ItemID other) { return _value.CompareTo(other._value); } #endregion #region IConvertible Members /// <summary> /// Returns the <see cref="T:System.TypeCode"/> for this instance. /// </summary> /// <returns> /// The enumerated constant that is the <see cref="T:System.TypeCode"/> of the class or value type that implements this interface. /// </returns> public TypeCode GetTypeCode() { return _value.GetTypeCode(); } /// <summary> /// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation /// that supplies culture-specific formatting information.</param> /// <returns> /// A Boolean value equivalent to the value of this instance. /// </returns> bool IConvertible.ToBoolean(IFormatProvider provider) { return ((IConvertible)_value).ToBoolean(provider); } /// <summary> /// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 8-bit unsigned integer equivalent to the value of this instance. /// </returns> byte IConvertible.ToByte(IFormatProvider provider) { return ((IConvertible)_value).ToByte(provider); } /// <summary> /// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A Unicode character equivalent to the value of this instance. /// </returns> char IConvertible.ToChar(IFormatProvider provider) { return ((IConvertible)_value).ToChar(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.DateTime"/> using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A <see cref="T:System.DateTime"/> instance equivalent to the value of this instance. /// </returns> DateTime IConvertible.ToDateTime(IFormatProvider provider) { return ((IConvertible)_value).ToDateTime(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"/> number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information. </param> /// <returns> /// A <see cref="T:System.Decimal"/> number equivalent to the value of this instance. /// </returns> decimal IConvertible.ToDecimal(IFormatProvider provider) { return ((IConvertible)_value).ToDecimal(provider); } /// <summary> /// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A double-precision floating-point number equivalent to the value of this instance. /// </returns> double IConvertible.ToDouble(IFormatProvider provider) { return ((IConvertible)_value).ToDouble(provider); } /// <summary> /// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 16-bit signed integer equivalent to the value of this instance. /// </returns> short IConvertible.ToInt16(IFormatProvider provider) { return ((IConvertible)_value).ToInt16(provider); } /// <summary> /// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 32-bit signed integer equivalent to the value of this instance. /// </returns> int IConvertible.ToInt32(IFormatProvider provider) { return ((IConvertible)_value).ToInt32(provider); } /// <summary> /// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 64-bit signed integer equivalent to the value of this instance. /// </returns> long IConvertible.ToInt64(IFormatProvider provider) { return ((IConvertible)_value).ToInt64(provider); } /// <summary> /// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 8-bit signed integer equivalent to the value of this instance. /// </returns> sbyte IConvertible.ToSByte(IFormatProvider provider) { return ((IConvertible)_value).ToSByte(provider); } /// <summary> /// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information. </param> /// <returns> /// A single-precision floating-point number equivalent to the value of this instance. /// </returns> float IConvertible.ToSingle(IFormatProvider provider) { return ((IConvertible)_value).ToSingle(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.String"/> using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A <see cref="T:System.String"/> instance equivalent to the value of this instance. /// </returns> public string ToString(IFormatProvider provider) { return ((IConvertible)_value).ToString(provider); } /// <summary> /// Converts the value of this instance to an <see cref="T:System.Object"/> of the specified <see cref="T:System.Type"/> that has an equivalent value, using the specified culture-specific formatting information. /// </summary> /// <param name="conversionType">The <see cref="T:System.Type"/> to which the value of this instance is converted.</param> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An <see cref="T:System.Object"/> instance of type <paramref name="conversionType"/> whose value is equivalent to the value of this instance. /// </returns> object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return ((IConvertible)_value).ToType(conversionType, provider); } /// <summary> /// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 16-bit unsigned integer equivalent to the value of this instance. /// </returns> ushort IConvertible.ToUInt16(IFormatProvider provider) { return ((IConvertible)_value).ToUInt16(provider); } /// <summary> /// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 32-bit unsigned integer equivalent to the value of this instance. /// </returns> uint IConvertible.ToUInt32(IFormatProvider provider) { return ((IConvertible)_value).ToUInt32(provider); } /// <summary> /// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 64-bit unsigned integer equivalent to the value of this instance. /// </returns> ulong IConvertible.ToUInt64(IFormatProvider provider) { return ((IConvertible)_value).ToUInt64(provider); } #endregion #region IEquatable<int> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public bool Equals(int other) { return _value.Equals(other); } #endregion #region IFormattable Members /// <summary> /// Formats the value of the current instance using the specified format. /// </summary> /// <param name="format">The <see cref="T:System.String"/> specifying the format to use. /// -or- /// null to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation. /// </param> /// <param name="formatProvider">The <see cref="T:System.IFormatProvider"/> to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// </param> /// <returns> /// A <see cref="T:System.String"/> containing the value of the current instance in the specified format. /// </returns> public string ToString(string format, IFormatProvider formatProvider) { return _value.ToString(format, formatProvider); } #endregion /// <summary> /// Implements operator ++. /// </summary> /// <param name="l">The ItemID to increment.</param> /// <returns>The incremented ItemID.</returns> public static ItemID operator ++(ItemID l) { return new ItemID(l._value + 1); } /// <summary> /// Implements operator --. /// </summary> /// <param name="l">The ItemID to decrement.</param> /// <returns>The decremented ItemID.</returns> public static ItemID operator --(ItemID l) { return new ItemID(l._value - 1); } /// <summary> /// Implements operator +. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>Result of the left side plus the right side.</returns> public static ItemID operator +(ItemID left, ItemID right) { return new ItemID(left._value + right._value); } /// <summary> /// Implements operator -. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>Result of the left side minus the right side.</returns> public static ItemID operator -(ItemID left, ItemID right) { return new ItemID(left._value - right._value); } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(ItemID left, int right) { return left._value == right; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(ItemID left, int right) { return left._value != right; } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(int left, ItemID right) { return left == right._value; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(int left, ItemID right) { return left != right._value; } /// <summary> /// Casts a ItemID to an Int32. /// </summary> /// <param name="ItemID">ItemID to cast.</param> /// <returns>The Int32.</returns> public static explicit operator int(ItemID ItemID) { return ItemID._value; } /// <summary> /// Casts an Int32 to a ItemID. /// </summary> /// <param name="value">Int32 to cast.</param> /// <returns>The ItemID.</returns> public static explicit operator ItemID(int value) { return new ItemID(value); } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(int left, ItemID right) { return left > right._value; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(int left, ItemID right) { return left < right._value; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(ItemID left, ItemID right) { return left._value > right._value; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(ItemID left, ItemID right) { return left._value < right._value; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(ItemID left, int right) { return left._value > right; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(ItemID left, int right) { return left._value < right; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(int left, ItemID right) { return left >= right._value; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(int left, ItemID right) { return left <= right._value; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(ItemID left, int right) { return left._value >= right; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(ItemID left, int right) { return left._value <= right; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(ItemID left, ItemID right) { return left._value >= right._value; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(ItemID left, ItemID right) { return left._value <= right._value; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(ItemID left, ItemID right) { return left._value != right._value; } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(ItemID left, ItemID right) { return left._value == right._value; } } /// <summary> /// Adds extensions to some data I/O objects for performing Read and Write operations for the ItemID. /// All of the operations are implemented in the ItemID struct. These extensions are provided /// purely for the convenience of accessing all the I/O operations from the same place. /// </summary> public static class ItemIDReadWriteExtensions { /// <summary> /// Gets the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type ItemID. /// </summary> /// <typeparam name="T">The key Type.</typeparam> /// <param name="dict">The IDictionary.</param> /// <param name="key">The key for the value to get.</param> /// <returns>The value at the given <paramref name="key"/> parsed as a ItemID.</returns> public static ItemID AsItemID<T>(this IDictionary<T, string> dict, T key) { return Parser.Invariant.ParseItemID(dict[key]); } /// <summary> /// Tries to get the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type ItemID. /// </summary> /// <typeparam name="T">The key Type.</typeparam> /// <param name="dict">The IDictionary.</param> /// <param name="key">The key for the value to get.</param> /// <param name="defaultValue">The value to use if the value at the <paramref name="key"/> could not be parsed.</param> /// <returns>The value at the given <paramref name="key"/> parsed as an int, or the /// <paramref name="defaultValue"/> if the <paramref name="key"/> did not exist in the <paramref name="dict"/> /// or the value at the given <paramref name="key"/> could not be parsed.</returns> public static ItemID AsItemID<T>(this IDictionary<T, string> dict, T key, ItemID defaultValue) { string value; if (!dict.TryGetValue(key, out value)) return defaultValue; ItemID parsed; if (!Parser.Invariant.TryParse(value, out parsed)) return defaultValue; return parsed; } /// <summary> /// Reads the ItemID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="r"><see cref="IDataRecord"/> to read the ItemID from.</param> /// <param name="i">The field index to read.</param> /// <returns>The ItemID read from the <see cref="IDataRecord"/>.</returns> public static ItemID GetItemID(this IDataRecord r, int i) { return ItemID.Read(r, i); } /// <summary> /// Reads the ItemID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="r"><see cref="IDataRecord"/> to read the ItemID from.</param> /// <param name="name">The name of the field to read the value from.</param> /// <returns>The ItemID read from the <see cref="IDataRecord"/>.</returns> public static ItemID GetItemID(this IDataRecord r, string name) { return ItemID.Read(r, name); } /// <summary> /// Parses the ItemID from a string. /// </summary> /// <param name="parser">The Parser to use.</param> /// <param name="value">The string to parse.</param> /// <returns>The ItemID parsed from the string.</returns> public static ItemID ParseItemID(this Parser parser, string value) { return new ItemID(parser.ParseInt(value)); } /// <summary> /// Reads the ItemID from a BitStream. /// </summary> /// <param name="bitStream">BitStream to read the ItemID from.</param> /// <returns>The ItemID read from the BitStream.</returns> public static ItemID ReadItemID(this BitStream bitStream) { return ItemID.Read(bitStream); } /// <summary> /// Reads the ItemID from an IValueReader. /// </summary> /// <param name="valueReader">IValueReader to read the ItemID from.</param> /// <param name="name">The unique name of the value to read.</param> /// <returns>The ItemID read from the IValueReader.</returns> public static ItemID ReadItemID(this IValueReader valueReader, string name) { return ItemID.Read(valueReader, name); } /// <summary> /// Tries to parse the ItemID from a string. /// </summary> /// <param name="parser">The Parser to use.</param> /// <param name="value">The string to parse.</param> /// <param name="outValue">If this method returns true, contains the parsed ItemID.</param> /// <returns>True if the parsing was successfully; otherwise false.</returns> public static bool TryParse(this Parser parser, string value, out ItemID outValue) { int tmp; var ret = parser.TryParse(value, out tmp); outValue = new ItemID(tmp); return ret; } /// <summary> /// Writes a ItemID to a BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="value">ItemID to write.</param> public static void Write(this BitStream bitStream, ItemID value) { value.Write(bitStream); } /// <summary> /// Writes a ItemID to a IValueWriter. /// </summary> /// <param name="valueWriter">IValueWriter to write to.</param> /// <param name="name">Unique name of the ItemID that will be used to distinguish it /// from other values when reading.</param> /// <param name="value">ItemID to write.</param> public static void Write(this IValueWriter valueWriter, string name, ItemID value) { value.Write(valueWriter, name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { /// <remarks> /// Property Default Description /// PositiveSign '+' Character used to indicate positive values. /// NegativeSign '-' Character used to indicate negative values. /// NumberDecimalSeparator '.' The character used as the decimal separator. /// NumberGroupSeparator ',' The character used to separate groups of /// digits to the left of the decimal point. /// NumberDecimalDigits 2 The default number of decimal places. /// NumberGroupSizes 3 The number of digits in each group to the /// left of the decimal point. /// NaNSymbol "NaN" The string used to represent NaN values. /// PositiveInfinitySymbol"Infinity" The string used to represent positive /// infinities. /// NegativeInfinitySymbol"-Infinity" The string used to represent negative /// infinities. /// /// Property Default Description /// CurrencyDecimalSeparator '.' The character used as the decimal /// separator. /// CurrencyGroupSeparator ',' The character used to separate groups /// of digits to the left of the decimal /// point. /// CurrencyDecimalDigits 2 The default number of decimal places. /// CurrencyGroupSizes 3 The number of digits in each group to /// the left of the decimal point. /// CurrencyPositivePattern 0 The format of positive values. /// CurrencyNegativePattern 0 The format of negative values. /// CurrencySymbol "$" String used as local monetary symbol. /// </remarks> public sealed class NumberFormatInfo : IFormatProvider, ICloneable { private static volatile NumberFormatInfo? s_invariantInfo; internal int[] _numberGroupSizes = new int[] { 3 }; internal int[] _currencyGroupSizes = new int[] { 3 }; internal int[] _percentGroupSizes = new int[] { 3 }; internal string _positiveSign = "+"; internal string _negativeSign = "-"; internal string _numberDecimalSeparator = "."; internal string _numberGroupSeparator = ","; internal string _currencyGroupSeparator = ","; internal string _currencyDecimalSeparator = "."; internal string _currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund. internal string _nanSymbol = "NaN"; internal string _positiveInfinitySymbol = "Infinity"; internal string _negativeInfinitySymbol = "-Infinity"; internal string _percentDecimalSeparator = "."; internal string _percentGroupSeparator = ","; internal string _percentSymbol = "%"; internal string _perMilleSymbol = "\u2030"; internal string[] _nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; internal int _numberDecimalDigits = 2; internal int _currencyDecimalDigits = 2; internal int _currencyPositivePattern = 0; internal int _currencyNegativePattern = 0; internal int _numberNegativePattern = 1; internal int _percentPositivePattern = 0; internal int _percentNegativePattern = 0; internal int _percentDecimalDigits = 2; internal int _digitSubstitution = (int)DigitShapes.None; internal bool _isReadOnly = false; private bool _hasInvariantNumberSigns = true; public NumberFormatInfo() { } private static void VerifyDecimalSeparator(string decSep, string propertyName) { if (decSep == null) { throw new ArgumentNullException(propertyName); } if (decSep.Length == 0) { throw new ArgumentException(SR.Argument_EmptyDecString, propertyName); } } private static void VerifyGroupSeparator(string groupSep, string propertyName) { if (groupSep == null) { throw new ArgumentNullException(propertyName); } } private static void VerifyNativeDigits(string[] nativeDig, string propertyName) { if (nativeDig == null) { throw new ArgumentNullException(propertyName, SR.ArgumentNull_Array); } if (nativeDig.Length != 10) { throw new ArgumentException(SR.Argument_InvalidNativeDigitCount, propertyName); } for (int i = 0; i < nativeDig.Length; i++) { if (nativeDig[i] == null) { throw new ArgumentNullException(propertyName, SR.ArgumentNull_ArrayValue); } if (nativeDig[i].Length != 1) { if (nativeDig[i].Length != 2) { // Not 1 or 2 UTF-16 code points throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName); } else if (!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1])) { // 2 UTF-6 code points, but not a surrogate pair throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName); } } if (CharUnicodeInfo.GetDecimalDigitValue(nativeDig[i], 0) != i && CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse) { // Not the appropriate digit according to the Unicode data properties // (Digit 0 must be a 0, etc.). throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName); } } } private static void VerifyDigitSubstitution(DigitShapes digitSub, string propertyName) { switch (digitSub) { case DigitShapes.Context: case DigitShapes.None: case DigitShapes.NativeNational: // Success. break; default: throw new ArgumentException(SR.Argument_InvalidDigitSubstitution, propertyName); } } internal bool HasInvariantNumberSigns => _hasInvariantNumberSigns; private void UpdateHasInvariantNumberSigns() { _hasInvariantNumberSigns = _positiveSign == "+" && _negativeSign == "-"; } internal NumberFormatInfo(CultureData? cultureData) { if (cultureData != null) { // We directly use fields here since these data is coming from data table or Win32, so we // don't need to verify their values (except for invalid parsing situations). cultureData.GetNFIValues(this); UpdateHasInvariantNumberSigns(); } } private void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } /// <summary> /// Returns a default NumberFormatInfo that will be universally /// supported and constant irrespective of the current culture. /// Used by FromString methods. /// </summary> public static NumberFormatInfo InvariantInfo => s_invariantInfo ??= // Lazy create the invariant info. This cannot be done in a .cctor because exceptions can // be thrown out of a .cctor stack that will need this. new NumberFormatInfo { _isReadOnly = true }; public static NumberFormatInfo GetInstance(IFormatProvider? formatProvider) { return formatProvider == null ? CurrentInfo : // Fast path for a null provider GetProviderNonNull(formatProvider); static NumberFormatInfo GetProviderNonNull(IFormatProvider provider) { // Fast path for a regular CultureInfo if (provider is CultureInfo cultureProvider && !cultureProvider._isInherited) { return cultureProvider._numInfo ?? cultureProvider.NumberFormat; } return provider as NumberFormatInfo ?? // Fast path for an NFI provider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo ?? CurrentInfo; } } public object Clone() { NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone(); n._isReadOnly = false; return n; } public int CurrencyDecimalDigits { get => _currencyDecimalDigits; set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 99)); } VerifyWritable(); _currencyDecimalDigits = value; } } public string CurrencyDecimalSeparator { get => _currencyDecimalSeparator; set { VerifyWritable(); VerifyDecimalSeparator(value, nameof(value)); _currencyDecimalSeparator = value; } } public bool IsReadOnly => _isReadOnly; /// <summary> /// Check the values of the groupSize array. /// Every element in the groupSize array should be between 1 and 9 /// except the last element could be zero. /// </summary> internal static void CheckGroupSize(string propName, int[] groupSize) { for (int i = 0; i < groupSize.Length; i++) { if (groupSize[i] < 1) { if (i == groupSize.Length - 1 && groupSize[i] == 0) { return; } throw new ArgumentException(SR.Argument_InvalidGroupSize, propName); } else if (groupSize[i] > 9) { throw new ArgumentException(SR.Argument_InvalidGroupSize, propName); } } } public int[] CurrencyGroupSizes { get => (int[])_currencyGroupSizes.Clone(); set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); int[] inputSizes = (int[])value.Clone(); CheckGroupSize(nameof(value), inputSizes); _currencyGroupSizes = inputSizes; } } public int[] NumberGroupSizes { get => (int[])_numberGroupSizes.Clone(); set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); int[] inputSizes = (int[])value.Clone(); CheckGroupSize(nameof(value), inputSizes); _numberGroupSizes = inputSizes; } } public int[] PercentGroupSizes { get => (int[])_percentGroupSizes.Clone(); set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); int[] inputSizes = (int[])value.Clone(); CheckGroupSize(nameof(value), inputSizes); _percentGroupSizes = inputSizes; } } public string CurrencyGroupSeparator { get => _currencyGroupSeparator; set { VerifyWritable(); VerifyGroupSeparator(value, nameof(value)); _currencyGroupSeparator = value; } } public string CurrencySymbol { get => _currencySymbol; set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _currencySymbol = value; } } /// <summary> /// Returns the current culture's NumberFormatInfo. Used by Parse methods. /// </summary> public static NumberFormatInfo CurrentInfo { get { System.Globalization.CultureInfo culture = CultureInfo.CurrentCulture; if (!culture._isInherited) { NumberFormatInfo? info = culture._numInfo; if (info != null) { return info; } } // returns non-nullable when passed typeof(NumberFormatInfo) return (NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo))!; } } public string NaNSymbol { get => _nanSymbol; set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _nanSymbol = value; } } public int CurrencyNegativePattern { get => _currencyNegativePattern; set { if (value < 0 || value > 15) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 15)); } VerifyWritable(); _currencyNegativePattern = value; } } public int NumberNegativePattern { get => _numberNegativePattern; set { // NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp. if (value < 0 || value > 4) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 4)); } VerifyWritable(); _numberNegativePattern = value; } } public int PercentPositivePattern { get => _percentPositivePattern; set { // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 3)); } VerifyWritable(); _percentPositivePattern = value; } } public int PercentNegativePattern { get => _percentNegativePattern; set { // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. if (value < 0 || value > 11) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 11)); } VerifyWritable(); _percentNegativePattern = value; } } public string NegativeInfinitySymbol { get => _negativeInfinitySymbol; set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _negativeInfinitySymbol = value; } } public string NegativeSign { get => _negativeSign; set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _negativeSign = value; UpdateHasInvariantNumberSigns(); } } public int NumberDecimalDigits { get => _numberDecimalDigits; set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 99)); } VerifyWritable(); _numberDecimalDigits = value; } } public string NumberDecimalSeparator { get => _numberDecimalSeparator; set { VerifyWritable(); VerifyDecimalSeparator(value, nameof(value)); _numberDecimalSeparator = value; } } public string NumberGroupSeparator { get => _numberGroupSeparator; set { VerifyWritable(); VerifyGroupSeparator(value, nameof(value)); _numberGroupSeparator = value; } } public int CurrencyPositivePattern { get => _currencyPositivePattern; set { if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 3)); } VerifyWritable(); _currencyPositivePattern = value; } } public string PositiveInfinitySymbol { get => _positiveInfinitySymbol; set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _positiveInfinitySymbol = value; } } public string PositiveSign { get => _positiveSign; set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _positiveSign = value; UpdateHasInvariantNumberSigns(); } } public int PercentDecimalDigits { get => _percentDecimalDigits; set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 99)); } VerifyWritable(); _percentDecimalDigits = value; } } public string PercentDecimalSeparator { get => _percentDecimalSeparator; set { VerifyWritable(); VerifyDecimalSeparator(value, nameof(value)); _percentDecimalSeparator = value; } } public string PercentGroupSeparator { get => _percentGroupSeparator; set { VerifyWritable(); VerifyGroupSeparator(value, nameof(value)); _percentGroupSeparator = value; } } public string PercentSymbol { get => _percentSymbol; set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _percentSymbol = value; } } public string PerMilleSymbol { get => _perMilleSymbol; set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _perMilleSymbol = value; } } public string[] NativeDigits { get => (string[])_nativeDigits.Clone(); set { VerifyWritable(); VerifyNativeDigits(value, nameof(value)); _nativeDigits = value; } } public DigitShapes DigitSubstitution { get => (DigitShapes)_digitSubstitution; set { VerifyWritable(); VerifyDigitSubstitution(value, nameof(value)); _digitSubstitution = (int)value; } } public object? GetFormat(Type? formatType) { return formatType == typeof(NumberFormatInfo) ? this : null; } public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) { if (nfi == null) { throw new ArgumentNullException(nameof(nfi)); } if (nfi.IsReadOnly) { return nfi; } NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone()); info._isReadOnly = true; return info; } // private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00); private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); internal static void ValidateParseStyleInteger(NumberStyles style) { // Check for undefined flags or invalid hex number flags if ((style & (InvalidNumberStyles | NumberStyles.AllowHexSpecifier)) != 0 && (style & ~NumberStyles.HexNumber) != 0) { throwInvalid(style); void throwInvalid(NumberStyles value) { if ((value & InvalidNumberStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style)); } throw new ArgumentException(SR.Arg_InvalidHexStyle); } } } internal static void ValidateParseStyleFloatingPoint(NumberStyles style) { // Check for undefined flags or hex number if ((style & (InvalidNumberStyles | NumberStyles.AllowHexSpecifier)) != 0) { throwInvalid(style); void throwInvalid(NumberStyles value) { if ((value & InvalidNumberStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style)); } throw new ArgumentException(SR.Arg_HexStyleNotSupported); } } } } }
using System; using Eto.Forms; using Eto.Drawing; using Eto.Mac.Drawing; using Eto.Mac.Forms.Cells; #if XAMMAC2 using AppKit; using Foundation; using CoreGraphics; using ObjCRuntime; using CoreAnimation; #else using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.CoreGraphics; using MonoMac.ObjCRuntime; using MonoMac.CoreAnimation; #if Mac64 using CGSize = MonoMac.Foundation.NSSize; using CGRect = MonoMac.Foundation.NSRect; using CGPoint = MonoMac.Foundation.NSPoint; using nfloat = System.Double; using nint = System.Int64; using nuint = System.UInt64; #else using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using nfloat = System.Single; using nint = System.Int32; using nuint = System.UInt32; #endif #endif namespace Eto.Mac.Forms.Controls { public interface IDataViewHandler { bool ShowHeader { get; } NSTableView Table { get; } object GetItem(int row); int RowCount { get; } int RowHeight { get; } CGRect GetVisibleRect(); bool Loaded { get; } void OnCellFormatting(GridColumn column, object item, int row, NSCell cell); } public interface IDataColumnHandler { void Setup(int column); NSObject GetObjectValue(object dataItem); void SetObjectValue(object dataItem, NSObject val); GridColumn Widget { get; } IDataViewHandler DataViewHandler { get; } void Resize(bool force = false); void Loaded(IDataViewHandler handler, int column); void EnabledChanged(bool value); } public class GridColumnHandler : MacObject<NSTableColumn, GridColumn, GridColumn.ICallback>, GridColumn.IHandler, IDataColumnHandler { Cell dataCell; Font font; public IDataViewHandler DataViewHandler { get; private set; } public int Column { get; private set; } public GridColumnHandler() { Control = new NSTableColumn(); Control.ResizingMask = NSTableColumnResizing.None; Sortable = false; HeaderText = string.Empty; Editable = false; AutoSize = true; DataCell = new TextBoxCell(); } public void Loaded(IDataViewHandler handler, int column) { Column = column; DataViewHandler = handler; } public void Resize(bool force = false) { var handler = DataViewHandler; if (AutoSize && handler != null) { var width = Control.DataCell.CellSize.Width; var outlineView = handler.Table as NSOutlineView; if (handler.ShowHeader) width = (nfloat)Math.Max(Control.HeaderCell.CellSize.Width, width); if (dataCell != null) { /* Auto size based on visible cells only */ var rect = handler.GetVisibleRect(); var range = handler.Table.RowsInRect(rect); var cellSize = Control.DataCell.CellSize; cellSize.Height = (nfloat)Math.Max(cellSize.Height, handler.RowHeight); var dataCellHandler = ((ICellHandler)dataCell.Handler); for (var i = range.Location; i < range.Location + range.Length; i++) { var cellWidth = GetRowWidth(dataCellHandler, (int)i, cellSize) + 4; if (outlineView != null && Column == 0) { cellWidth += (float)((outlineView.LevelForRow((nint)i) + 1) * outlineView.IndentationPerLevel); } width = (nfloat)Math.Max(width, cellWidth); } } if (force || width > Control.Width) Control.Width = width; } } protected virtual nfloat GetRowWidth(ICellHandler cell, int row, CGSize cellSize) { var item = DataViewHandler.GetItem(row); var val = GetObjectValue(item); return cell.GetPreferredSize(val, cellSize, row, item); } public string HeaderText { get { return Control.HeaderCell.StringValue; } set { Control.HeaderCell.StringValue = value; } } public bool Resizable { get { return Control.ResizingMask.HasFlag(NSTableColumnResizing.UserResizingMask); } set { if (value) Control.ResizingMask |= NSTableColumnResizing.UserResizingMask; else Control.ResizingMask &= ~NSTableColumnResizing.UserResizingMask; } } public bool AutoSize { get; set; } public bool Sortable { get; set; } public bool Editable { get { return Control.Editable; } set { Control.Editable = value; if (dataCell != null) { var cellHandler = (ICellHandler)dataCell.Handler; cellHandler.Editable = value; } var table = Control.TableView; if (DataViewHandler != null && DataViewHandler.Loaded && table != null) { table.SetNeedsDisplay(); } } } public int Width { get { return (int)Control.Width; } set { Control.Width = value; } } public bool Visible { get { return !Control.Hidden; } set { Control.Hidden = !value; } } public Cell DataCell { get { return dataCell; } set { dataCell = value; if (dataCell != null) { var editable = Editable; var cellHandler = (ICellHandler)dataCell.Handler; Control.DataCell = cellHandler.Control; cellHandler.ColumnHandler = this; cellHandler.Editable = editable; } else Control.DataCell = null; } } public void Setup(int column) { Column = column; Control.Identifier = new NSString(column.ToString()); } public NSObject GetObjectValue(object dataItem) { return ((ICellHandler)dataCell.Handler).GetObjectValue(dataItem); } public void SetObjectValue(object dataItem, NSObject val) { ((ICellHandler)dataCell.Handler).SetObjectValue(dataItem, val); } GridColumn IDataColumnHandler.Widget { get { return Widget; } } public Font Font { get { if (font == null) font = new Font(new FontHandler(Control.DataCell.Font)); return font; } set { font = value; if (font != null) { var fontHandler = (FontHandler)font.Handler; Control.DataCell.Font = fontHandler.Control; } else Control.DataCell.Font = null; } } public void EnabledChanged(bool value) { if (dataCell != null) { var cellHandler = (ICellHandler)dataCell.Handler; cellHandler.EnabledChanged(value); } } } }
using GitTools; using GitVersion; using GitVersion.Helpers; using GitVersionCore.Tests; using NUnit.Framework; using Shouldly; using System; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using YamlDotNet.Serialization; [TestFixture] public class ConfigProviderTests : TestBase { private const string DefaultRepoPath = "c:\\MyGitRepo"; private const string DefaultWorkingPath = "c:\\MyGitRepo\\Working"; string repoPath; string workingPath; IFileSystem fileSystem; [SetUp] public void Setup() { fileSystem = new TestFileSystem(); repoPath = DefaultRepoPath; workingPath = DefaultWorkingPath; ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute<TestAttribute>(); } [Test] public void CanReadOldDocument() { const string text = @" assemblyVersioningScheme: MajorMinor develop-branch-tag: alpha release-branch-tag: rc branches: master: mode: ContinuousDeployment dev(elop)?(ment)?$: mode: ContinuousDeployment tag: dev release[/-]: mode: continuousDeployment tag: rc "; SetupConfigFileContent(text); var error = Should.Throw<OldConfigurationException>(() => ConfigurationProvider.Provide(repoPath, fileSystem)); error.Message.ShouldContainWithoutWhitespace(@"GitVersion configuration file contains old configuration, please fix the following errors: GitVersion branch configs no longer are keyed by regexes, update: dev(elop)?(ment)?$ -> develop release[/-] -> release assemblyVersioningScheme has been replaced by assembly-versioning-scheme develop-branch-tag has been replaced by branch specific configuration.See http://gitversion.readthedocs.org/en/latest/configuration/#branch-configuration release-branch-tag has been replaced by branch specific configuration.See http://gitversion.readthedocs.org/en/latest/configuration/#branch-configuration"); } [Test] public void OverwritesDefaultsWithProvidedConfig() { var defaultConfig = ConfigurationProvider.Provide(repoPath, fileSystem); const string text = @" next-version: 2.0.0 branches: develop: mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); config.NextVersion.ShouldBe("2.0.0"); config.Branches["develop"].Increment.ShouldBe(defaultConfig.Branches["develop"].Increment); config.Branches["develop"].VersioningMode.ShouldBe(defaultConfig.Branches["develop"].VersioningMode); config.Branches["develop"].Tag.ShouldBe("dev"); } [Test] public void AllBranchesModeWhenUsingMainline() { var defaultConfig = ConfigurationProvider.Provide(repoPath, fileSystem); const string text = @"mode: Mainline"; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); var branches = config.Branches.Select(x => x.Value); branches.All(branch => branch.VersioningMode == VersioningMode.Mainline).ShouldBe(true); } [Test] public void CanRemoveTag() { const string text = @" next-version: 2.0.0 branches: release: tag: """""; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); config.NextVersion.ShouldBe("2.0.0"); config.Branches["release"].Tag.ShouldBe(string.Empty); } [Test] public void RegexIsRequired() { const string text = @" next-version: 2.0.0 branches: bug: tag: bugfix"; SetupConfigFileContent(text); var ex = Should.Throw<GitVersionConfigurationException>(() => ConfigurationProvider.Provide(repoPath, fileSystem)); ex.Message.ShouldBe("Branch configuration 'bug' is missing required configuration 'regex'\n\n" + "See http://gitversion.readthedocs.io/en/latest/configuration/ for more info"); } [Test] public void SourceBranchIsRequired() { const string text = @" next-version: 2.0.0 branches: bug: regex: 'bug[/-]' tag: bugfix"; SetupConfigFileContent(text); var ex = Should.Throw<GitVersionConfigurationException>(() => ConfigurationProvider.Provide(repoPath, fileSystem)); ex.Message.ShouldBe("Branch configuration 'bug' is missing required configuration 'source-branches'\n\n" + "See http://gitversion.readthedocs.io/en/latest/configuration/ for more info"); } [Test] public void CanProvideConfigForNewBranch() { const string text = @" next-version: 2.0.0 branches: bug: regex: 'bug[/-]' tag: bugfix source-branches: []"; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); config.Branches["bug"].Regex.ShouldBe("bug[/-]"); config.Branches["bug"].Tag.ShouldBe("bugfix"); } [Test] public void NextVersionCanBeInteger() { const string text = "next-version: 2"; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); config.NextVersion.ShouldBe("2.0"); } [Test] public void NextVersionCanHaveEnormousMinorVersion() { const string text = "next-version: 2.118998723"; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); config.NextVersion.ShouldBe("2.118998723"); } [Test] public void NextVersionCanHavePatch() { const string text = "next-version: 2.12.654651698"; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); config.NextVersion.ShouldBe("2.12.654651698"); } [Test] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] [MethodImpl(MethodImplOptions.NoInlining)] public void CanWriteOutEffectiveConfiguration() { var config = ConfigurationProvider.GetEffectiveConfigAsString(repoPath, fileSystem); config.ShouldMatchApproved(); } [Test] public void CanUpdateAssemblyInformationalVersioningScheme() { const string text = @" assembly-versioning-scheme: MajorMinor assembly-file-versioning-scheme: MajorMinorPatch assembly-informational-format: '{NugetVersion}'"; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{NugetVersion}"); } [Test] public void CanUpdateAssemblyInformationalVersioningSchemeWithMultipleVariables() { const string text = @" assembly-versioning-scheme: MajorMinor assembly-file-versioning-scheme: MajorMinorPatch assembly-informational-format: '{Major}.{Minor}.{Patch}'"; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{Major}.{Minor}.{Patch}"); } [Test] public void CanUpdateAssemblyInformationalVersioningSchemeWithFullSemVer() { const string text = @"assembly-versioning-scheme: MajorMinorPatch assembly-file-versioning-scheme: MajorMinorPatch assembly-informational-format: '{FullSemVer}' mode: ContinuousDelivery next-version: 5.3.0 branches: {}"; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{FullSemVer}"); } [Test] public void CanReadDefaultDocument() { const string text = ""; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(repoPath, fileSystem); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe(null); config.Branches["develop"].Tag.ShouldBe("alpha"); config.Branches["release"].Tag.ShouldBe("beta"); config.TagPrefix.ShouldBe(ConfigurationProvider.DefaultTagPrefix); config.NextVersion.ShouldBe(null); } [Test] public void VerifyAliases() { var config = typeof(Config); var propertiesMissingAlias = config.GetProperties() .Where(p => p.GetCustomAttribute<ObsoleteAttribute>() == null) .Where(p => p.GetCustomAttribute(typeof(YamlMemberAttribute)) == null) .Select(p => p.Name); propertiesMissingAlias.ShouldBeEmpty(); } [TestCase(DefaultRepoPath)] [TestCase(DefaultWorkingPath)] public void WarnOnExistingGitVersionConfigYamlFile(string path) { SetupConfigFileContent(string.Empty, ConfigurationProvider.ObsoleteConfigFileName, path); var logOutput = string.Empty; Action<string> action = info => { logOutput = info; }; using (Logger.AddLoggersTemporarily(action, action, action, action)) { ConfigurationProvider.Verify(workingPath, repoPath, fileSystem); } var configFileDeprecatedWarning = string.Format("{0}' is deprecated, use '{1}' instead", ConfigurationProvider.ObsoleteConfigFileName, ConfigurationProvider.DefaultConfigFileName); logOutput.Contains(configFileDeprecatedWarning).ShouldBe(true); } [TestCase(DefaultRepoPath)] [TestCase(DefaultWorkingPath)] public void WarnOnAmbiguousConfigFilesAtTheSameProjectRootDirectory(string path) { SetupConfigFileContent(string.Empty, ConfigurationProvider.ObsoleteConfigFileName, path); SetupConfigFileContent(string.Empty, ConfigurationProvider.DefaultConfigFileName, path); var logOutput = string.Empty; Action<string> action = info => { logOutput = info; }; using (Logger.AddLoggersTemporarily(action, action, action, action)) { ConfigurationProvider.Verify(workingPath, repoPath, fileSystem); } var configFileDeprecatedWarning = string.Format("Ambiguous config files at '{0}'", path); logOutput.Contains(configFileDeprecatedWarning).ShouldBe(true); } [TestCase(ConfigurationProvider.DefaultConfigFileName, ConfigurationProvider.DefaultConfigFileName)] [TestCase(ConfigurationProvider.DefaultConfigFileName, ConfigurationProvider.ObsoleteConfigFileName)] [TestCase(ConfigurationProvider.ObsoleteConfigFileName, ConfigurationProvider.DefaultConfigFileName)] [TestCase(ConfigurationProvider.ObsoleteConfigFileName, ConfigurationProvider.ObsoleteConfigFileName)] public void ThrowsExceptionOnAmbiguousConfigFileLocation(string repoConfigFile, string workingConfigFile) { var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, repoConfigFile, repoPath); var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, workingConfigFile, workingPath); WarningException exception = Should.Throw<WarningException>(() => { ConfigurationProvider.Verify(workingPath, repoPath, fileSystem); }); var expecedMessage = string.Format("Ambiguous config file selection from '{0}' and '{1}'", workingDirectoryConfigFilePath, repositoryConfigFilePath); exception.Message.ShouldBe(expecedMessage); } [Test] public void NoWarnOnGitVersionYmlFile() { SetupConfigFileContent(string.Empty); var s = string.Empty; Action<string> action = info => { s = info; }; using (Logger.AddLoggersTemporarily(action, action, action, action)) { ConfigurationProvider.Provide(repoPath, fileSystem); } s.Length.ShouldBe(0); } string SetupConfigFileContent(string text, string fileName = ConfigurationProvider.DefaultConfigFileName) { return SetupConfigFileContent(text, fileName, repoPath); } string SetupConfigFileContent(string text, string fileName, string path) { var fullPath = Path.Combine(path, fileName); fileSystem.WriteAllText(fullPath, text); return fullPath; } [Test] public void WarnOnObsoleteIsDevelopBranchConfigurationSetting() { const string text = @" assembly-versioning-scheme: MajorMinorPatch branches: master: tag: beta is-develop: true"; OldConfigurationException exception = Should.Throw<OldConfigurationException>(() => { LegacyConfigNotifier.Notify(new StringReader(text)); }); const string expectedMessage = @"'is-develop' is deprecated, use 'tracks-release-branches' instead."; exception.Message.ShouldContain(expectedMessage); } }
#region License // // Copyright (c) 2018, Fluent Migrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Data; using FluentMigrator.Builders.Create.Column; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Infrastructure.Extensions; using FluentMigrator.Model; using FluentMigrator.Runner; using FluentMigrator.SqlServer; using Microsoft.Extensions.DependencyInjection; using Moq; namespace FluentMigrator.Tests.Unit.Generators { public static class GeneratorTestHelper { public static string TestTableName1 = "TestTable1"; public static string TestTableName2 = "TestTable2"; public static string TestColumnName1 = "TestColumn1"; public static string TestColumnName2 = "TestColumn2"; public static string TestColumnName3 = "TestColumn3"; public static string TestIndexName = "TestIndex"; public static string TestTableDescription = "TestDescription"; public static string TestColumn1Description = "TestColumn1Description"; public static string TestColumn2Description = "TestColumn2Description"; public static string TestColumnCollationName = "Latin1_General_CS_AS"; public static Guid TestGuid = Guid.NewGuid(); public static CreateTableExpression GetCreateTableExpression() { CreateTableExpression expression = new CreateTableExpression() { TableName = TestTableName1, }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, Type = DbType.String }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32 }); return expression; } public static CreateTableExpression GetCreateTableWithDefaultValue() { CreateTableExpression expression = new CreateTableExpression() { TableName = TestTableName1, }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, Type = DbType.String, DefaultValue = "Default", TableName = TestTableName1 }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32, DefaultValue = 0, TableName = TestTableName1 }); return expression; } public static CreateTableExpression GetCreateTableWithPrimaryKeyExpression() { var expression = new CreateTableExpression { TableName = TestTableName1 }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, IsPrimaryKey = true, Type = DbType.String }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32 }); return expression; } public static CreateTableExpression GetCreateTableWithNamedPrimaryKeyExpression() { var expression = new CreateTableExpression { TableName = TestTableName1 }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, IsPrimaryKey = true, PrimaryKeyName = "TestKey", Type = DbType.String }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32 }); return expression; } public static CreateTableExpression GetCreateTableWithNamedMultiColumnPrimaryKeyExpression() { var expression = new CreateTableExpression { TableName = TestTableName1 }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, IsPrimaryKey = true, PrimaryKeyName = "TestKey", Type = DbType.String }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32, IsPrimaryKey = true }); return expression; } public static CreateTableExpression GetCreateTableWithAutoIncrementExpression() { var expression = new CreateTableExpression { TableName = TestTableName1 }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, IsIdentity = true, Type = DbType.Int32 }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32 }); return expression; } public static CreateTableExpression GetCreateTableWithMultiColumnPrimaryKeyExpression() { var expression = new CreateTableExpression { TableName = TestTableName1 }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, IsPrimaryKey = true, Type = DbType.String }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, IsPrimaryKey = true, Type = DbType.Int32 }); return expression; } public static CreateTableExpression GetCreateTableWithNullableColumn() { var expression = new CreateTableExpression { TableName = TestTableName1 }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, IsNullable = true, Type = DbType.String }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32 }); return expression; } public static CreateTableExpression GetCreateTableWithTableDescription() { var expression = new CreateTableExpression { TableName = TestTableName1, TableDescription = TestTableDescription }; return expression; } public static CreateTableExpression GetCreateTableWithTableDescriptionAndColumnDescriptions() { var expression = new CreateTableExpression { TableName = TestTableName1, TableDescription = TestTableDescription }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, IsNullable = true, Type = DbType.String, ColumnDescription = TestColumn1Description }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32, ColumnDescription = TestColumn2Description }); return expression; } public static CreateTableExpression GetCreateTableWithForeignKey() { var expression = new CreateTableExpression { TableName = TestTableName1 }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, Type = DbType.String }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32, IsForeignKey = true, ForeignKey = new ForeignKeyDefinition() { PrimaryTable = TestTableName2, ForeignTable = TestTableName1, PrimaryColumns = new[] { TestColumnName2 }, ForeignColumns = new[] { TestColumnName1 } } }); return expression; } public static CreateTableExpression GetCreateTableWithMultiColumnForeignKey() { var expression = new CreateTableExpression { TableName = TestTableName1 }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, Type = DbType.String }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32, IsForeignKey = true, ForeignKey = new ForeignKeyDefinition() { PrimaryTable = TestTableName2, ForeignTable = TestTableName1, PrimaryColumns = new[] { TestColumnName2, "TestColumn4" }, ForeignColumns = new[] { TestColumnName1, "TestColumn3" } } }); return expression; } public static CreateTableExpression GetCreateTableWithNameForeignKey() { var expression = new CreateTableExpression { TableName = TestTableName1 }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, Type = DbType.String }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32, IsForeignKey = true, ForeignKey = new ForeignKeyDefinition() { Name = "FK_Test", PrimaryTable = TestTableName2, ForeignTable = TestTableName1, PrimaryColumns = new[] { TestColumnName2 }, ForeignColumns = new[] { TestColumnName1 } } }); return expression; } public static CreateTableExpression GetCreateTableWithNameMultiColumnForeignKey() { var expression = new CreateTableExpression { TableName = TestTableName1 }; expression.Columns.Add(new ColumnDefinition { Name = TestColumnName1, Type = DbType.String }); expression.Columns.Add(new ColumnDefinition { Name = TestColumnName2, Type = DbType.Int32, IsForeignKey = true, ForeignKey = new ForeignKeyDefinition() { Name = "FK_Test", PrimaryTable = TestTableName2, ForeignTable = TestTableName1, PrimaryColumns = new[] { TestColumnName2, "TestColumn4" }, ForeignColumns = new[] { TestColumnName1, "TestColumn3" } } }); return expression; } public static CreateIndexExpression GetCreateIndexExpression() { var expression = new CreateIndexExpression(); expression.Index.Name = TestIndexName; expression.Index.TableName = TestTableName1; expression.Index.IsUnique = false; expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Ascending, Name = TestColumnName1 }); return expression; } public static CreateSchemaExpression GetCreateSchemaExpression() { return new CreateSchemaExpression { SchemaName = "TestSchema" }; } public static CreateSequenceExpression GetCreateSequenceExpression() { return new CreateSequenceExpression { Sequence = { Cache = 10, Cycle = true, Increment = 2, MaxValue = 100, MinValue = 0, Name = "Sequence", StartWith = 2 } }; } public static CreateIndexExpression GetCreateMultiColumnCreateIndexExpression() { var expression = new CreateIndexExpression(); expression.Index.Name = TestIndexName; expression.Index.TableName = TestTableName1; expression.Index.IsUnique = false; expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Ascending, Name = TestColumnName1 }); expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Descending, Name = TestColumnName2 }); return expression; } public static CreateIndexExpression GetCreateUniqueIndexExpression() { var expression = new CreateIndexExpression(); expression.Index.Name = TestIndexName; expression.Index.TableName = TestTableName1; expression.Index.IsUnique = true; expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Ascending, Name = TestColumnName1 }); return expression; } public static CreateIndexExpression GetCreateUniqueMultiColumnIndexExpression() { var expression = new CreateIndexExpression(); expression.Index.Name = TestIndexName; expression.Index.TableName = TestTableName1; expression.Index.IsUnique = true; expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Ascending, Name = TestColumnName1 }); expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Descending, Name = TestColumnName2 }); return expression; } public static CreateIndexExpression GetCreateIncludeIndexExpression() { var expression = new CreateIndexExpression(); expression.Index.Name = TestIndexName; expression.Index.TableName = TestTableName1; expression.Index.IsUnique = false; expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Ascending, Name = TestColumnName1 }); var includes = expression.Index.GetAdditionalFeature(SqlServerExtensions.IncludesList, () => new List<IndexIncludeDefinition>()); includes.Add(new IndexIncludeDefinition { Name = TestColumnName2 }); return expression; } public static CreateIndexExpression GetCreateMultiIncludeIndexExpression() { var expression = new CreateIndexExpression(); expression.Index.Name = TestIndexName; expression.Index.TableName = TestTableName1; expression.Index.IsUnique = false; expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Ascending, Name = TestColumnName1 }); var includes = expression.Index.GetAdditionalFeature(SqlServerExtensions.IncludesList, () => new List<IndexIncludeDefinition>()); includes.Add(new IndexIncludeDefinition { Name = TestColumnName2 }); includes.Add(new IndexIncludeDefinition { Name = TestColumnName3 }); return expression; } public static InsertDataExpression GetInsertDataExpression() { var expression = new InsertDataExpression(); expression.TableName = TestTableName1; expression.Rows.Add(new InsertionDataDefinition { new KeyValuePair<string, object>("Id", 1), new KeyValuePair<string, object>("Name", "Just'in"), new KeyValuePair<string, object>("Website", "codethinked.com") }); expression.Rows.Add(new InsertionDataDefinition { new KeyValuePair<string, object>("Id", 2), new KeyValuePair<string, object>("Name", @"Na\te"), new KeyValuePair<string, object>("Website", "kohari.org") }); return expression; } public static UpdateDataExpression GetUpdateDataExpression() { var expression = new UpdateDataExpression(); expression.TableName = TestTableName1; expression.Set = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("Name", "Just'in"), new KeyValuePair<string, object>("Age", 25) }; expression.Where = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("Id", 9), new KeyValuePair<string, object>("Homepage", null) }; return expression; } public static UpdateDataExpression GetUpdateDataExpressionWithDbNullValue() { var expression = new UpdateDataExpression(); expression.TableName = TestTableName1; expression.Set = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("Name", "Just'in"), new KeyValuePair<string, object>("Age", 25) }; expression.Where = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("Id", 9), new KeyValuePair<string, object>("Homepage", DBNull.Value) }; return expression; } public static UpdateDataExpression GetUpdateDataExpressionWithAllRows() { var expression = new UpdateDataExpression(); expression.TableName = TestTableName1; expression.Set = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("Name", "Just'in"), new KeyValuePair<string, object>("Age", 25) }; expression.IsAllRows = true; return expression; } public static InsertDataExpression GetInsertGUIDExpression() { return GetInsertGUIDExpression(TestGuid); } public static InsertDataExpression GetInsertGUIDExpression(Guid guid) { var expression = new InsertDataExpression {TableName = TestTableName1}; expression.Rows.Add(new InsertionDataDefinition {new KeyValuePair<string, object>("guid", guid)}); return expression; } public static DeleteDataExpression GetDeleteDataExpression() { var expression = new DeleteDataExpression(); expression.TableName = TestTableName1; expression.Rows.Add(new DeletionDataDefinition { new KeyValuePair<string, object>("Name", "Just'in"), new KeyValuePair<string, object>("Website", null) }); return expression; } public static DeleteDataExpression GetDeleteDataExpressionWithDbNullValue() { var expression = new DeleteDataExpression(); expression.TableName = TestTableName1; expression.Rows.Add(new DeletionDataDefinition { new KeyValuePair<string, object>("Name", "Just'in"), new KeyValuePair<string, object>("Website", DBNull.Value) }); return expression; } public static DeleteDataExpression GetDeleteDataMultipleRowsExpression() { var expression = new DeleteDataExpression(); expression.TableName = TestTableName1; expression.Rows.Add(new DeletionDataDefinition { new KeyValuePair<string, object>("Name", "Just'in"), new KeyValuePair<string, object>("Website", null) }); expression.Rows.Add(new DeletionDataDefinition { new KeyValuePair<string, object>("Website", "github.com") }); return expression; } public static DeleteDataExpression GetDeleteDataAllRowsExpression() { var expression = new DeleteDataExpression(); expression.TableName = TestTableName1; expression.IsAllRows = true; return expression; } public static RenameColumnExpression GetRenameColumnExpression() { return new RenameColumnExpression { OldName = TestColumnName1, NewName = TestColumnName2, TableName = TestTableName1 }; } public static CreateColumnExpression GetCreateDecimalColumnExpression() { ColumnDefinition column = new ColumnDefinition { Name = TestColumnName1, Type = DbType.Decimal, Size = 19, Precision = 2 }; return new CreateColumnExpression { TableName = TestTableName1, Column = column }; } public static CreateColumnExpression GetCreateCurrencyColumnExpression() { ColumnDefinition column = new ColumnDefinition { Name = TestColumnName1, Type = DbType.Currency }; return new CreateColumnExpression { TableName = TestTableName1, Column = column }; } public static CreateColumnExpression GetCreateColumnExpression() { ColumnDefinition column = new ColumnDefinition { Name = TestColumnName1, Type = DbType.String, Size = 5 }; return new CreateColumnExpression { TableName = TestTableName1, Column = column }; } public static ICollection<IMigrationExpression> GetCreateColumnWithSystemMethodExpression(string schemaName = null) { var serviceProvider = new ServiceCollection().BuildServiceProvider(); var querySchema = new Mock<IQuerySchema>(); var context = new MigrationContext(querySchema.Object, serviceProvider, null, null); var expr = new CreateColumnExpression { TableName = TestTableName1, SchemaName = schemaName, Column = new ColumnDefinition { Name = TestColumnName1, Type = DbType.DateTime } }; context.Expressions.Add(expr); var builder = new CreateColumnExpressionBuilder(expr, context); builder.SetExistingRowsTo(SystemMethods.CurrentDateTime); return context.Expressions; } public static CreateColumnExpression GetCreateColumnExpressionWithDescription() { CreateColumnExpression columnExpression = GetCreateColumnExpression(); columnExpression.Column.ColumnDescription = TestColumn1Description; return columnExpression; } public static CreateColumnExpression GetCreateColumnExpressionWithCollation() { CreateColumnExpression columnExpression = GetCreateColumnExpression(); columnExpression.Column.CollationName = TestColumnCollationName; return columnExpression; } public static CreateColumnExpression GetAlterTableAutoIncrementColumnExpression() { ColumnDefinition column = new ColumnDefinition { Name = TestColumnName1, IsIdentity = true, Type = DbType.Int32 }; return new CreateColumnExpression { TableName = TestTableName1, Column = column }; } public static AlterTableExpression GetAlterTableWithDescriptionExpression() { return new AlterTableExpression() { TableName = TestTableName1, TableDescription = TestTableDescription }; } public static AlterTableExpression GetAlterTable() { return new AlterTableExpression() {TableName = TestTableName1 }; } public static RenameTableExpression GetRenameTableExpression() { var expression = new RenameTableExpression(); expression.OldName = TestTableName1; expression.NewName = TestTableName2; return expression; } public static AlterColumnExpression GetAlterColumnAddAutoIncrementExpression() { ColumnDefinition column = new ColumnDefinition { Name = TestColumnName1, IsIdentity = true, IsPrimaryKey = true, Type = DbType.Int32, ModificationType = ColumnModificationType.Alter }; return new AlterColumnExpression { TableName = TestTableName1, Column = column }; } public static AlterColumnExpression GetAlterColumnExpression() { var expression = new AlterColumnExpression(); expression.TableName = TestTableName1; expression.Column = new ColumnDefinition(); expression.Column.Name = TestColumnName1; expression.Column.Type = DbType.String; expression.Column.Size = 20; expression.Column.IsNullable = false; expression.Column.ModificationType = ColumnModificationType.Alter; return expression; } public static CreateColumnExpression GetCreateColumnExpressionWithDateTimeOffsetType() { var expression = new CreateColumnExpression(); expression.TableName = TestTableName1; expression.Column = new ColumnDefinition(); expression.Column.Name = TestColumnName1; expression.Column.IsNullable = true; expression.Column.Type = DbType.DateTimeOffset; expression.Column.ModificationType = ColumnModificationType.Create; return expression; } public static CreateColumnExpression GetCreateColumnExpressionWithNullableCustomType() { var expression = new CreateColumnExpression(); expression.TableName = TestTableName1; expression.Column = new ColumnDefinition(); expression.Column.Name = TestColumnName1; expression.Column.IsNullable = true; expression.Column.CustomType = "MyDomainType"; expression.Column.ModificationType = ColumnModificationType.Create; return expression; } public static AlterColumnExpression GetAlterColumnExpressionWithDescription() { var columnExpression = GetAlterColumnExpression(); columnExpression.Column.ColumnDescription = TestColumn1Description; return columnExpression; } public static AlterColumnExpression GetAlterColumnExpressionWithCollation() { var columnExpression = GetAlterColumnExpression(); columnExpression.Column.CollationName = TestColumnCollationName; return columnExpression; } public static AlterSchemaExpression GetAlterSchemaExpression() { return new AlterSchemaExpression { DestinationSchemaName = "TestSchema2", SourceSchemaName = "TestSchema1", TableName = "TestTable" }; } public static CreateForeignKeyExpression GetCreateForeignKeyExpression() { var expression = new CreateForeignKeyExpression { ForeignKey = { PrimaryTable = TestTableName2, ForeignTable = TestTableName1, PrimaryColumns = new[] {TestColumnName2}, ForeignColumns = new[] {TestColumnName1} } }; var processed = expression.Apply(ConventionSets.NoSchemaName); return processed; } public static CreateForeignKeyExpression GetCreateMultiColumnForeignKeyExpression() { var expression = new CreateForeignKeyExpression { ForeignKey = { PrimaryTable = TestTableName2, ForeignTable = TestTableName1, PrimaryColumns = new[] {TestColumnName2, "TestColumn4"}, ForeignColumns = new[] {TestColumnName1, "TestColumn3"} } }; var processed = expression.Apply(ConventionSets.NoSchemaName); return processed; } public static CreateForeignKeyExpression GetCreateNamedForeignKeyExpression() { var expression = new CreateForeignKeyExpression(); expression.ForeignKey.Name = "FK_Test"; expression.ForeignKey.PrimaryTable = TestTableName2; expression.ForeignKey.ForeignTable = TestTableName1; expression.ForeignKey.PrimaryColumns = new[] { TestColumnName2 }; expression.ForeignKey.ForeignColumns = new[] { TestColumnName1 }; return expression; } public static CreateForeignKeyExpression GetCreateNamedMultiColumnForeignKeyExpression() { var expression = new CreateForeignKeyExpression(); expression.ForeignKey.Name = "FK_Test"; expression.ForeignKey.PrimaryTable = TestTableName2; expression.ForeignKey.ForeignTable = TestTableName1; expression.ForeignKey.PrimaryColumns = new[] { TestColumnName2, "TestColumn4" }; expression.ForeignKey.ForeignColumns = new[] { TestColumnName1, "TestColumn3" }; return expression; } public static DeleteTableExpression GetDeleteTableExpression() { return new DeleteTableExpression { TableName = TestTableName1 }; } public static DeleteColumnExpression GetDeleteColumnExpression() { return GetDeleteColumnExpression(new[] { TestColumnName1 }); } public static DeleteColumnExpression GetDeleteColumnExpression(string[] columns) { return new DeleteColumnExpression { TableName = TestTableName1, ColumnNames = columns }; } public static DeleteIndexExpression GetDeleteIndexExpression() { IndexDefinition indexDefinition = new IndexDefinition { Name = TestIndexName, TableName = TestTableName1 }; return new DeleteIndexExpression { Index = indexDefinition }; } public static DeleteForeignKeyExpression GetDeleteForeignKeyExpression() { var expression = new DeleteForeignKeyExpression(); expression.ForeignKey.Name = "FK_Test"; expression.ForeignKey.ForeignTable = TestTableName1; return expression; } public static DeleteConstraintExpression GetDeletePrimaryKeyExpression() { var expression = new DeleteConstraintExpression(ConstraintType.PrimaryKey); expression.Constraint.TableName = TestTableName1; expression.Constraint.ConstraintName = "TESTPRIMARYKEY"; return expression; } public static DeleteSchemaExpression GetDeleteSchemaExpression() { return new DeleteSchemaExpression { SchemaName = "TestSchema" }; } public static DeleteSequenceExpression GetDeleteSequenceExpression() { return new DeleteSequenceExpression { SequenceName = "Sequence" }; } public static DeleteConstraintExpression GetDeleteUniqueConstraintExpression() { var expression = new DeleteConstraintExpression(ConstraintType.Unique); expression.Constraint.TableName = TestTableName1; expression.Constraint.ConstraintName = "TESTUNIQUECONSTRAINT"; return expression; } public static CreateConstraintExpression GetCreatePrimaryKeyExpression() { var expression = new CreateConstraintExpression(ConstraintType.PrimaryKey); expression.Constraint.TableName = TestTableName1; expression.Constraint.Columns.Add(TestColumnName1); var processed = expression.Apply(ConventionSets.NoSchemaName); return processed; } public static CreateConstraintExpression GetCreateNamedPrimaryKeyExpression() { var expression = new CreateConstraintExpression(ConstraintType.PrimaryKey); expression.Constraint.TableName = TestTableName1; expression.Constraint.Columns.Add(TestColumnName1); expression.Constraint.ConstraintName = "TESTPRIMARYKEY"; return expression; } public static CreateConstraintExpression GetCreateMultiColumnPrimaryKeyExpression() { var expression = new CreateConstraintExpression(ConstraintType.PrimaryKey); expression.Constraint.TableName = TestTableName1; expression.Constraint.Columns.Add(TestColumnName1); expression.Constraint.Columns.Add(TestColumnName2); var processed = expression.Apply(ConventionSets.NoSchemaName); return processed; } public static CreateConstraintExpression GetCreateNamedMultiColumnPrimaryKeyExpression() { var expression = new CreateConstraintExpression(ConstraintType.PrimaryKey); expression.Constraint.TableName = TestTableName1; expression.Constraint.Columns.Add(TestColumnName1); expression.Constraint.Columns.Add(TestColumnName2); expression.Constraint.ConstraintName = "TESTPRIMARYKEY"; return expression; } public static CreateConstraintExpression GetCreateUniqueConstraintExpression() { var expression = new CreateConstraintExpression(ConstraintType.Unique); expression.Constraint.TableName = TestTableName1; expression.Constraint.Columns.Add(TestColumnName1); var processed = expression.Apply(ConventionSets.NoSchemaName); return processed; } public static CreateConstraintExpression GetCreateNamedUniqueConstraintExpression() { var expression = new CreateConstraintExpression(ConstraintType.Unique); expression.Constraint.TableName = TestTableName1; expression.Constraint.Columns.Add(TestColumnName1); expression.Constraint.ConstraintName = "TESTUNIQUECONSTRAINT"; return expression; } public static CreateConstraintExpression GetCreateMultiColumnUniqueConstraintExpression() { var expression = new CreateConstraintExpression(ConstraintType.Unique); expression.Constraint.TableName = TestTableName1; expression.Constraint.Columns.Add(TestColumnName1); expression.Constraint.Columns.Add(TestColumnName2); var processed = expression.Apply(ConventionSets.NoSchemaName); return processed; } public static CreateConstraintExpression GetCreateNamedMultiColumnUniqueConstraintExpression() { var expression = new CreateConstraintExpression(ConstraintType.Unique); expression.Constraint.TableName = TestTableName1; expression.Constraint.Columns.Add(TestColumnName1); expression.Constraint.Columns.Add(TestColumnName2); expression.Constraint.ConstraintName = "TESTUNIQUECONSTRAINT"; return expression; } public static AlterDefaultConstraintExpression GetAlterDefaultConstraintExpression() { var expression = new AlterDefaultConstraintExpression { ColumnName = TestColumnName1, DefaultValue = 1, TableName = TestTableName1 }; return expression; } public static DeleteDefaultConstraintExpression GetDeleteDefaultConstraintExpression() { var expression = new DeleteDefaultConstraintExpression { ColumnName = TestColumnName1, TableName = TestTableName1 }; return expression; } } }
#if UNITY_IOS // Copyright (C) 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 // // 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.Runtime.InteropServices; using UnityEngine; using GoogleMobileAds.Api; using GoogleMobileAds.Common; namespace GoogleMobileAds.iOS { public class AppOpenAdClient : IAppOpenAdClient, IDisposable { private IntPtr appOpenAdPtr; private IntPtr appOpenAdClientPtr; #region app open callback types internal delegate void GADUAppOpenAdLoadedCallback( IntPtr appOpenAdClient); internal delegate void GADUAppOpenAdFailToLoadCallback( IntPtr appOpenAdClient, IntPtr error); internal delegate void GADUAppOpenAdPaidEventCallback( IntPtr appOpenAdClient, int precision, long value, string currencyCode); #endregion #region full screen content callback types internal delegate void GADUAppOpenAdFailedToPresentFullScreenContentCallback( IntPtr appOpenAdClient, IntPtr error); internal delegate void GADUAppOpenAdWillPresentFullScreenContentCallback(IntPtr appOpenAdClient); internal delegate void GADUAppOpenAdDidDismissFullScreenContentCallback(IntPtr appOpenAdClient); internal delegate void GADUAppOpenAdDidRecordImpressionCallback(IntPtr appOpenAdClient); #endregion public event EventHandler<EventArgs> OnAdLoaded; public event EventHandler<LoadAdErrorClientEventArgs> OnAdFailedToLoad; public event EventHandler<AdValueEventArgs> OnPaidEvent; public event EventHandler<AdErrorClientEventArgs> OnAdFailedToPresentFullScreenContent; public event EventHandler<EventArgs> OnAdDidPresentFullScreenContent; public event EventHandler<EventArgs> OnAdDidRecordImpression; public event EventHandler<EventArgs> OnAdDidDismissFullScreenContent; // This property should be used when setting the appOpenAdPtr. private IntPtr AppOpenAdPtr { get { return this.appOpenAdPtr; } set { Externs.GADURelease(this.appOpenAdPtr); this.appOpenAdPtr = value; } } #region IAppOpenAdClient implementation public void CreateAppOpenAd() { this.appOpenAdClientPtr = (IntPtr)GCHandle.Alloc(this); this.AppOpenAdPtr = Externs.GADUCreateAppOpenAd(this.appOpenAdClientPtr); Externs.GADUSetAppOpenAdCallbacks( this.AppOpenAdPtr, AppOpenAdLoadedCallback, AppOpenAdFailedToLoadCallback, AppOpenAdPaidEventCallback, AdFailedToPresentFullScreenContentCallback, AdWillPresentFullScreenContentCallback, AdDidDismissFullScreenContentCallback, AdDidRecordImpressionCallback); } // Load an ad. public void LoadAd(string adUnitID, AdRequest request, ScreenOrientation orientation) { IntPtr requestPtr = Utils.BuildAdRequest(request); Externs.GADULoadAppOpenAd(this.AppOpenAdPtr, adUnitID, (int) orientation, requestPtr); Externs.GADURelease(requestPtr); } // Show the app open ad on the screen. public void Show() { Externs.GADUShowAppOpenAd(this.AppOpenAdPtr); } public IResponseInfoClient GetResponseInfoClient() { return new ResponseInfoClient(ResponseInfoClientType.AdLoaded, this.AppOpenAdPtr); } // Destroys the app open ad. public void DestroyAppOpenAd() { this.AppOpenAdPtr = IntPtr.Zero; } public void Dispose() { this.DestroyAppOpenAd(); ((GCHandle)this.appOpenAdClientPtr).Free(); } ~AppOpenAdClient() { this.Dispose(); } #endregion #region App open ad callback methods [MonoPInvokeCallback(typeof(GADUAppOpenAdLoadedCallback))] private static void AppOpenAdLoadedCallback(IntPtr appOpenAdClient) { AppOpenAdClient client = IntPtrToAppOpenAdClient(appOpenAdClient); if (client.OnAdLoaded != null) { client.OnAdLoaded(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUAppOpenAdFailToLoadCallback))] private static void AppOpenAdFailedToLoadCallback( IntPtr appOpenAdClient, IntPtr error) { AppOpenAdClient client = IntPtrToAppOpenAdClient(appOpenAdClient); if (client.OnAdFailedToLoad != null) { LoadAdErrorClientEventArgs args = new LoadAdErrorClientEventArgs() { LoadAdErrorClient = new LoadAdErrorClient(error), }; client.OnAdFailedToLoad(client, args); } } [MonoPInvokeCallback(typeof(GADUAppOpenAdPaidEventCallback))] private static void AppOpenAdPaidEventCallback( IntPtr appOpenAdClient, int precision, long value, string currencyCode) { AppOpenAdClient client = IntPtrToAppOpenAdClient(appOpenAdClient); if (client.OnPaidEvent != null) { AdValue adValue = new AdValue() { Precision = (AdValue.PrecisionType) precision, Value = value, CurrencyCode = currencyCode }; AdValueEventArgs args = new AdValueEventArgs() { AdValue = adValue }; client.OnPaidEvent(client, args); } } [MonoPInvokeCallback(typeof(GADUAppOpenAdFailedToPresentFullScreenContentCallback))] private static void AdFailedToPresentFullScreenContentCallback( IntPtr appOpenAdClient, IntPtr error) { AppOpenAdClient client = IntPtrToAppOpenAdClient(appOpenAdClient); if (client.OnAdFailedToPresentFullScreenContent != null) { AdErrorClientEventArgs args = new AdErrorClientEventArgs() { AdErrorClient = new AdErrorClient(error), }; client.OnAdFailedToPresentFullScreenContent(client, args); } } [MonoPInvokeCallback(typeof(GADUAppOpenAdWillPresentFullScreenContentCallback))] private static void AdWillPresentFullScreenContentCallback(IntPtr appOpenAdClient) { AppOpenAdClient client = IntPtrToAppOpenAdClient(appOpenAdClient); if (client.OnAdDidPresentFullScreenContent != null) { client.OnAdDidPresentFullScreenContent(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUAppOpenAdDidDismissFullScreenContentCallback))] private static void AdDidDismissFullScreenContentCallback(IntPtr appOpenAdClient) { AppOpenAdClient client = IntPtrToAppOpenAdClient(appOpenAdClient); if (client.OnAdDidDismissFullScreenContent != null) { client.OnAdDidDismissFullScreenContent(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUAppOpenAdDidRecordImpressionCallback))] private static void AdDidRecordImpressionCallback(IntPtr appOpenAdClient) { AppOpenAdClient client = IntPtrToAppOpenAdClient(appOpenAdClient); if (client.OnAdDidRecordImpression != null) { client.OnAdDidRecordImpression(client, EventArgs.Empty); } } private static AppOpenAdClient IntPtrToAppOpenAdClient(IntPtr appOpenAdClient) { GCHandle handle = (GCHandle)appOpenAdClient; return handle.Target as AppOpenAdClient; } #endregion } } #endif
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cache.Affinity; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Resource; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// This class defines a factory for the main Ignite API. /// <p/> /// Use <see cref="Start()"/> method to start Ignite with default configuration. /// <para/> /// All members are thread-safe and may be used concurrently from multiple threads. /// </summary> public static class Ignition { /** */ internal const string EnvIgniteSpringConfigUrlPrefix = "IGNITE_SPRING_CONFIG_URL_PREFIX"; /** */ private static readonly object SyncRoot = new object(); /** GC warning flag. */ private static int _gcWarn; /** */ private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>(); /** Current DLL name. */ private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); /** Startup info. */ [ThreadStatic] private static Startup _startup; /** Client mode flag. */ [ThreadStatic] private static bool _clientMode; /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static Ignition() { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } /// <summary> /// Gets or sets a value indicating whether Ignite should be started in client mode. /// Client nodes cannot hold data in caches. /// </summary> public static bool ClientMode { get { return _clientMode; } set { _clientMode = value; } } /// <summary> /// Starts Ignite with default configuration. By default this method will /// use Ignite configuration defined in <c>{IGNITE_HOME}/config/default-config.xml</c> /// configuration file. If such file is not found, then all system defaults will be used. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite Start() { return Start(new IgniteConfiguration()); } /// <summary> /// Starts all grids specified within given Spring XML configuration file. If Ignite with given name /// is already started, then exception is thrown. In this case all instances that may /// have been started so far will be stopped too. /// </summary> /// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be /// absolute or relative to IGNITE_HOME.</param> /// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st /// found instance is returned.</returns> public static IIgnite Start(string springCfgPath) { return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath}); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from first <see cref="IgniteConfigurationSection"/> in the /// application configuration and starts Ignite. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration() { var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var section = cfg.Sections.OfType<IgniteConfigurationSection>().FirstOrDefault(); if (section == null) throw new ConfigurationErrorsException( string.Format("Could not find {0} in current application configuration", typeof(IgniteConfigurationSection).Name)); return Start(section.IgniteConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection; if (section == null) throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'", typeof(IgniteConfigurationSection).Name, sectionName)); return Start(section.IgniteConfiguration); } /// <summary> /// Starts Ignite with given configuration. /// </summary> /// <returns>Started Ignite.</returns> public unsafe static IIgnite Start(IgniteConfiguration cfg) { IgniteArgumentCheck.NotNull(cfg, "cfg"); lock (SyncRoot) { // 1. Check GC settings. CheckServerGc(cfg); // 2. Create context. IgniteUtils.LoadDlls(cfg.JvmDllPath); var cbs = new UnmanagedCallbacks(); IgniteManager.CreateJvmContext(cfg, cbs); var gridName = cfg.GridName; var cfgPath = cfg.SpringConfigUrl == null ? null : Environment.GetEnvironmentVariable(EnvIgniteSpringConfigUrlPrefix) + cfg.SpringConfigUrl; // 3. Create startup object which will guide us through the rest of the process. _startup = new Startup(cfg, cbs); IUnmanagedTarget interopProc = null; try { // 4. Initiate Ignite start. UU.IgnitionStart(cbs.Context, cfgPath, gridName, ClientMode); // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data. var node = _startup.Ignite; interopProc = node.InteropProcessor; // 6. On-start callback (notify lifecycle components). node.OnStart(); Nodes[new NodeKey(_startup.Name)] = node; return node; } catch (Exception) { // 1. Perform keys cleanup. string name = _startup.Name; if (name != null) { NodeKey key = new NodeKey(name); if (Nodes.ContainsKey(key)) Nodes.Remove(key); } // 2. Stop Ignite node if it was started. if (interopProc != null) UU.IgnitionStop(interopProc.Context, gridName, true); // 3. Throw error further (use startup error if exists because it is more precise). if (_startup.Error != null) throw _startup.Error; throw; } finally { _startup = null; if (interopProc != null) UU.ProcessorReleaseStart(interopProc); } } } /// <summary> /// Check whether GC is set to server mode. /// </summary> /// <param name="cfg">Configuration.</param> private static void CheckServerGc(IgniteConfiguration cfg) { if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0) Logger.LogWarning("GC server mode is not enabled, this could lead to less " + "than optimal performance on multi-core machines (to enable see " + "http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx)."); } /// <summary> /// Prepare callback invoked from Java. /// </summary> /// <param name="inStream">Input stream with data.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream, HandleRegistry handleRegistry) { try { BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(inStream); PrepareConfiguration(reader, outStream); PrepareLifecycleBeans(reader, outStream, handleRegistry); PrepareAffinityFunctions(reader, outStream); outStream.SynchronizeOutput(); } catch (Exception e) { _startup.Error = e; throw; } } /// <summary> /// Prepare configuration. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Response stream.</param> private static void PrepareConfiguration(BinaryReader reader, PlatformMemoryStream outStream) { // 1. Load assemblies. IgniteConfiguration cfg = _startup.Configuration; LoadAssemblies(cfg.Assemblies); ICollection<string> cfgAssembllies; BinaryConfiguration binaryCfg; BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg); LoadAssemblies(cfgAssembllies); // 2. Create marshaller only after assemblies are loaded. if (cfg.BinaryConfiguration == null) cfg.BinaryConfiguration = binaryCfg; _startup.Marshaller = new Marshaller(cfg.BinaryConfiguration); // 3. Send configuration details to Java cfg.Write(_startup.Marshaller.StartMarshal(outStream)); } /// <summary> /// Prepare lifecycle beans. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> private static void PrepareLifecycleBeans(IBinaryRawReader reader, IBinaryStream outStream, HandleRegistry handleRegistry) { IList<LifecycleBeanHolder> beans = new List<LifecycleBeanHolder> { new LifecycleBeanHolder(new InternalLifecycleBean()) // add internal bean for events }; // 1. Read beans defined in Java. int cnt = reader.ReadInt(); for (int i = 0; i < cnt; i++) beans.Add(new LifecycleBeanHolder(CreateObject<ILifecycleBean>(reader))); // 2. Append beans defined in local configuration. ICollection<ILifecycleBean> nativeBeans = _startup.Configuration.LifecycleBeans; if (nativeBeans != null) { foreach (ILifecycleBean nativeBean in nativeBeans) beans.Add(new LifecycleBeanHolder(nativeBean)); } // 3. Write bean pointers to Java stream. outStream.WriteInt(beans.Count); foreach (LifecycleBeanHolder bean in beans) outStream.WriteLong(handleRegistry.AllocateCritical(bean)); // 4. Set beans to STARTUP object. _startup.LifecycleBeans = beans; } /// <summary> /// Prepares the affinity functions. /// </summary> private static void PrepareAffinityFunctions(BinaryReader reader, PlatformMemoryStream outStream) { var cnt = reader.ReadInt(); var writer = reader.Marshaller.StartMarshal(outStream); for (var i = 0; i < cnt; i++) { var objHolder = new ObjectInfoHolder(reader); AffinityFunctionSerializer.Write(writer, objHolder.CreateInstance<IAffinityFunction>(), objHolder); } } /// <summary> /// Creates an object and sets the properties. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Resulting object.</returns> private static T CreateObject<T>(IBinaryRawReader reader) { return IgniteUtils.CreateInstance<T>(reader.ReadString(), reader.ReadDictionaryAsGeneric<string, object>()); } /// <summary> /// Kernal start callback. /// </summary> /// <param name="interopProc">Interop processor.</param> /// <param name="stream">Stream.</param> internal static void OnStart(IUnmanagedTarget interopProc, IBinaryStream stream) { try { // 1. Read data and leave critical state ASAP. BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(stream); // ReSharper disable once PossibleInvalidOperationException var name = reader.ReadString(); // 2. Set ID and name so that Start() method can use them later. _startup.Name = name; if (Nodes.ContainsKey(new NodeKey(name))) throw new IgniteException("Ignite with the same name already started: " + name); _startup.Ignite = new Ignite(_startup.Configuration, _startup.Name, interopProc, _startup.Marshaller, _startup.LifecycleBeans, _startup.Callbacks); } catch (Exception e) { // 5. Preserve exception to throw it later in the "Start" method and throw it further // to abort startup in Java. _startup.Error = e; throw; } } /// <summary> /// Load assemblies. /// </summary> /// <param name="assemblies">Assemblies.</param> private static void LoadAssemblies(IEnumerable<string> assemblies) { if (assemblies != null) { foreach (string s in assemblies) { // 1. Try loading as directory. if (Directory.Exists(s)) { string[] files = Directory.GetFiles(s, "*.dll"); #pragma warning disable 0168 foreach (string dllPath in files) { if (!SelfAssembly(dllPath)) { try { Assembly.LoadFile(dllPath); } catch (BadImageFormatException) { // No-op. } } } #pragma warning restore 0168 continue; } // 2. Try loading using full-name. try { Assembly assembly = Assembly.Load(s); if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 3. Try loading using file path. try { Assembly assembly = Assembly.LoadFrom(s); if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 4. Not found, exception. throw new IgniteException("Failed to load assembly: " + s); } } } /// <summary> /// Whether assembly points to Ignite binary. /// </summary> /// <param name="assembly">Assembly to check..</param> /// <returns><c>True</c> if this is one of GG assemblies.</returns> private static bool SelfAssembly(string assembly) { return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Gets a named Ignite instance. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p /> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned.</param> /// <returns> /// An instance of named grid. /// </returns> /// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception> public static IIgnite GetIgnite(string name) { var ignite = TryGetIgnite(name); if (ignite == null) throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name); return ignite; } /// <summary> /// Gets an instance of default no-name grid. Note that /// caller of this method should not assume that it will return the same /// instance every time. /// </summary> /// <returns>An instance of default no-name grid.</returns> /// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception> public static IIgnite GetIgnite() { return GetIgnite(null); } /// <summary> /// Gets a named Ignite instance, or <c>null</c> if none found. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p/> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned. /// </param> /// <returns>An instance of named grid, or null.</returns> public static IIgnite TryGetIgnite(string name) { lock (SyncRoot) { Ignite result; return !Nodes.TryGetValue(new NodeKey(name), out result) ? null : result; } } /// <summary> /// Gets an instance of default no-name grid, or <c>null</c> if none found. Note that /// caller of this method should not assume that it will return the same /// instance every time. /// </summary> /// <returns>An instance of default no-name grid, or null.</returns> public static IIgnite TryGetIgnite() { return TryGetIgnite(null); } /// <summary> /// Stops named grid. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. If /// grid name is <c>null</c>, then default no-name Ignite will be stopped. /// </summary> /// <param name="name">Grid name. If <c>null</c>, then default no-name Ignite will be stopped.</param> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.cancel</c>method.</param> /// <returns><c>true</c> if named Ignite instance was indeed found and stopped, <c>false</c> /// othwerwise (the instance with given <c>name</c> was not found).</returns> public static bool Stop(string name, bool cancel) { lock (SyncRoot) { NodeKey key = new NodeKey(name); Ignite node; if (!Nodes.TryGetValue(key, out node)) return false; node.Stop(cancel); Nodes.Remove(key); GC.Collect(); return true; } } /// <summary> /// Stops <b>all</b> started grids. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. /// </summary> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.Cancel()</c> method.</param> public static void StopAll(bool cancel) { lock (SyncRoot) { while (Nodes.Count > 0) { var entry = Nodes.First(); entry.Value.Stop(cancel); Nodes.Remove(entry.Key); } } GC.Collect(); } /// <summary> /// Handles the AssemblyResolve event of the CurrentDomain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">The <see cref="ResolveEventArgs"/> instance containing the event data.</param> /// <returns>Manually resolved assembly, or null.</returns> private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { return LoadedAssembliesResolver.Instance.GetAssembly(args.Name); } /// <summary> /// Grid key. /// </summary> private class NodeKey { /** */ private readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="NodeKey"/> class. /// </summary> /// <param name="name">The name.</param> internal NodeKey(string name) { _name = name; } /** <inheritdoc /> */ public override bool Equals(object obj) { var other = obj as NodeKey; return other != null && Equals(_name, other._name); } /** <inheritdoc /> */ public override int GetHashCode() { return _name == null ? 0 : _name.GetHashCode(); } } /// <summary> /// Value object to pass data between .Net methods during startup bypassing Java. /// </summary> private class Startup { /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="cbs"></param> internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { Configuration = cfg; Callbacks = cbs; } /// <summary> /// Configuration. /// </summary> internal IgniteConfiguration Configuration { get; private set; } /// <summary> /// Gets unmanaged callbacks. /// </summary> internal UnmanagedCallbacks Callbacks { get; private set; } /// <summary> /// Lifecycle beans. /// </summary> internal IList<LifecycleBeanHolder> LifecycleBeans { get; set; } /// <summary> /// Node name. /// </summary> internal string Name { get; set; } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get; set; } /// <summary> /// Start error. /// </summary> internal Exception Error { get; set; } /// <summary> /// Gets or sets the ignite. /// </summary> internal Ignite Ignite { get; set; } } /// <summary> /// Internal bean for event notification. /// </summary> private class InternalLifecycleBean : ILifecycleBean { /** */ #pragma warning disable 649 // unused field [InstanceResource] private readonly IIgnite _ignite; /** <inheritdoc /> */ public void OnLifecycleEvent(LifecycleEventType evt) { if (evt == LifecycleEventType.BeforeNodeStop && _ignite != null) ((IgniteProxy) _ignite).Target.BeforeNodeStop(); } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <[email protected]> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Xml; using System.Reflection; using RdlEngine.Resources; using fyiReporting.RDL; namespace fyiReporting.RDL { /// <summary> /// <p>Language parser. Recursive descent parser. Precedence of operators /// is handled by starting with lowest precedence and calling down recursively /// to the highest.</p> /// AND/OR /// NOT /// relational operators, eq, ne, lt, lte, gt, gte /// +, - /// *, /, % /// ^ (exponentiation) /// unary +, - /// parenthesis (...) /// <p> /// In BNF the language grammar is:</p> /// <code> /// Expr: Term ExprRhs /// ExprRhs: PlusMinusOperator Term ExprRhs /// Term: Factor TermRhs /// TermRhs: MultDivOperator Factor TermRhs /// Factor: ( Expr ) | BaseType | - BaseType | - ( Expr ) /// BaseType: FuncIdent | NUMBER | QUOTE /// FuncIDent: IDENTIFIER ( [Expr] [, Expr]*) | IDENTIFIER /// PlusMinusOperator: + | - /// MultDivOperator: * | / /// </code> /// /// </summary> internal class Parser { static internal long Counter; // counter used for unique expression count private TokenList tokens; private Stack operandStack = new Stack(); private Stack operatorStack = new Stack(); private Token curToken=null; private NameLookup idLookup=null; private List<ICacheData> _DataCache; private bool _InAggregate; private List<FunctionField> _FieldResolve; private bool _NoAggregate=false; /// <summary> /// Parse an expression. /// </summary> internal Parser(List<ICacheData> c) { _DataCache = c; } /// <summary> /// Returns a parsed Expression /// </summary> /// <param name="lu">The NameLookUp class used to resolve names.</param> /// <param name="expr">The expression to be parsed.</param> /// <returns>An expression that can be run after validation and binding.</returns> internal IExpr Parse(NameLookup lu, string expr) { _InAggregate = false; if (expr.Substring(0,1) != "=") // if 1st char not '=' return new Constant(expr); // this is a constant value idLookup = lu; IExpr e = this.ParseExpr(new StringReader(expr)); if (e == null) // Didn't get an expression? e = new Constant(expr); // then provide a constant return e; } internal bool NoAggregateFunctions { // marked true when in an aggregate function get {return _NoAggregate;} set {_NoAggregate = value;} } private static string GetLocationInfo(Token token) { return string.Format(Strings.Parser_ErrorP_AtColumn, token.StartCol); } private static string GetLocationInfoWithValue(Token token) { return string.Format(Strings.Parser_ErrorP_FoundValue, token.Value) + GetLocationInfo(token); } /// <summary> /// Returns a parsed DPL instance. /// </summary> /// <param name="reader">The TextReader value to be parsed.</param> /// <returns>A parsed Program instance.</returns> private IExpr ParseExpr(TextReader reader) { IExpr result=null; Lexer lexer = new Lexer(reader); tokens = lexer.Lex(); if (tokens.Peek().Type == TokenTypes.EQUAL) { tokens.Extract(); // skip over the equal curToken = tokens.Extract(); // set up the first token MatchExprAndOr(out result); // start with lowest precedence and work up } if (curToken.Type != TokenTypes.EOF) throw new ParserException(Strings.Parser_ErrorP_EndExpressionExpected + GetLocationInfo(curToken)); return result; } // ExprAndOr: private void MatchExprAndOr(out IExpr result) { TokenTypes t; // remember the type IExpr lhs; MatchExprNot(out lhs); result = lhs; // in case we get no matches while ((t = curToken.Type) == TokenTypes.AND || t == TokenTypes.OR) { curToken = tokens.Extract(); IExpr rhs; MatchExprNot(out rhs); bool bBool = (rhs.GetTypeCode() == TypeCode.Boolean && lhs.GetTypeCode() == TypeCode.Boolean); if (!bBool) throw new ParserException(Strings.Parser_ErrorP_AND_OR_RequiresBoolean + GetLocationInfo(curToken)); switch(t) { case TokenTypes.AND: result = new FunctionAnd(lhs, rhs); break; case TokenTypes.OR: result = new FunctionOr(lhs, rhs); break; } lhs = result; // in case we have more AND/OR s } } private void MatchExprNot(out IExpr result) { TokenTypes t; // remember the type t = curToken.Type; if (t == TokenTypes.NOT) { curToken = tokens.Extract(); } MatchExprRelop(out result); if (t == TokenTypes.NOT) { if (result.GetTypeCode() != TypeCode.Boolean) throw new ParserException(Strings.Parser_ErrorP_NOTRequiresBoolean + GetLocationInfo(curToken)); result = new FunctionNot(result); } } // ExprRelop: private void MatchExprRelop(out IExpr result) { TokenTypes t; // remember the type IExpr lhs; MatchExprAddSub(out lhs); result = lhs; // in case we get no matches while ((t = curToken.Type) == TokenTypes.EQUAL || t == TokenTypes.NOTEQUAL || t == TokenTypes.GREATERTHAN || t == TokenTypes.GREATERTHANOREQUAL || t == TokenTypes.LESSTHAN || t == TokenTypes.LESSTHANOREQUAL) { curToken = tokens.Extract(); IExpr rhs; MatchExprAddSub(out rhs); switch(t) { case TokenTypes.EQUAL: result = new FunctionRelopEQ(lhs, rhs); break; case TokenTypes.NOTEQUAL: result = new FunctionRelopNE(lhs, rhs); break; case TokenTypes.GREATERTHAN: result = new FunctionRelopGT(lhs, rhs); break; case TokenTypes.GREATERTHANOREQUAL: result = new FunctionRelopGTE(lhs, rhs); break; case TokenTypes.LESSTHAN: result = new FunctionRelopLT(lhs, rhs); break; case TokenTypes.LESSTHANOREQUAL: result = new FunctionRelopLTE(lhs, rhs); break; } lhs = result; // in case we continue the loop } } // ExprAddSub: PlusMinusOperator Term ExprRhs private void MatchExprAddSub(out IExpr result) { TokenTypes t; // remember the type IExpr lhs; MatchExprMultDiv(out lhs); result = lhs; // in case we get no matches while ((t = curToken.Type) == TokenTypes.PLUS || t == TokenTypes.PLUSSTRING || t == TokenTypes.MINUS) { curToken = tokens.Extract(); IExpr rhs; MatchExprMultDiv(out rhs); TypeCode lt = lhs.GetTypeCode(); TypeCode rt = rhs.GetTypeCode(); bool bDecimal = (rt == TypeCode.Decimal && lt == TypeCode.Decimal); bool bInt32 = (rt == TypeCode.Int32 && lt == TypeCode.Int32); bool bString = (rt == TypeCode.String || lt == TypeCode.String); switch(t) { case TokenTypes.PLUSSTRING: result = new FunctionPlusString(lhs, rhs); break; case TokenTypes.PLUS: if (bDecimal) result = new FunctionPlusDecimal(lhs, rhs); else if (bString) result = new FunctionPlusString(lhs, rhs); else if (bInt32) result = new FunctionPlusInt32(lhs, rhs); else result = new FunctionPlus(lhs, rhs); break; case TokenTypes.MINUS: if (bDecimal) result = new FunctionMinusDecimal(lhs, rhs); else if (bString) throw new ParserException(Strings.Parser_ErrorP_MinusNeedNumbers + GetLocationInfo(curToken)); else if (bInt32) result = new FunctionMinusInt32(lhs, rhs); else result = new FunctionMinus(lhs, rhs); break; } lhs = result; // in case continue in the loop } } // TermRhs: MultDivOperator Factor TermRhs private void MatchExprMultDiv(out IExpr result) { TokenTypes t; // remember the type IExpr lhs; MatchExprExp(out lhs); result = lhs; // in case we get no matches while ((t = curToken.Type) == TokenTypes.FORWARDSLASH || t == TokenTypes.STAR || t == TokenTypes.MODULUS) { curToken = tokens.Extract(); IExpr rhs; MatchExprExp(out rhs); bool bDecimal = (rhs.GetTypeCode() == TypeCode.Decimal && lhs.GetTypeCode() == TypeCode.Decimal); switch (t) { case TokenTypes.FORWARDSLASH: if (bDecimal) result = new FunctionDivDecimal(lhs, rhs); else result = new FunctionDiv(lhs, rhs); break; case TokenTypes.STAR: if (bDecimal) result = new FunctionMultDecimal(lhs, rhs); else result = new FunctionMult(lhs, rhs); break; case TokenTypes.MODULUS: result = new FunctionModulus(lhs, rhs); break; } lhs = result; // in case continue in the loop } } // TermRhs: ExpOperator Factor TermRhs private void MatchExprExp(out IExpr result) { IExpr lhs; MatchExprUnary(out lhs); if (curToken.Type == TokenTypes.EXP) { curToken = tokens.Extract(); IExpr rhs; MatchExprUnary(out rhs); result = new FunctionExp(lhs, rhs); } else result = lhs; } private void MatchExprUnary(out IExpr result) { TokenTypes t; // remember the type t = curToken.Type; if (t == TokenTypes.PLUS || t == TokenTypes.MINUS) { curToken = tokens.Extract(); } MatchExprParen(out result); if (t == TokenTypes.MINUS) { if (result.GetTypeCode() == TypeCode.Decimal) result = new FunctionUnaryMinusDecimal(result); else if (result.GetTypeCode() == TypeCode.Int32) result = new FunctionUnaryMinusInteger(result); else result = new FunctionUnaryMinus(result); } } // Factor: ( Expr ) | BaseType | - BaseType | - ( Expr ) private void MatchExprParen(out IExpr result) { // Match- ( Expr ) if (curToken.Type == TokenTypes.LPAREN) { // trying to match ( Expr ) curToken = tokens.Extract(); MatchExprAndOr(out result); if (curToken.Type != TokenTypes.RPAREN) throw new ParserException(Strings.Parser_ErrorP_BracketExpected + GetLocationInfoWithValue(curToken)); curToken = tokens.Extract(); } else MatchBaseType(out result); } // BaseType: FuncIdent | NUMBER | QUOTE - note certain types are restricted in expressions private void MatchBaseType(out IExpr result) { if (MatchFuncIDent(out result)) return; switch (curToken.Type) { case TokenTypes.NUMBER: result = new ConstantDecimal(curToken.Value); break; case TokenTypes.DATETIME: result = new ConstantDateTime(curToken.Value); break; case TokenTypes.DOUBLE: result = new ConstantDouble(curToken.Value); break; case TokenTypes.INTEGER: result = new ConstantInteger(curToken.Value); break; case TokenTypes.QUOTE: result = new ConstantString(curToken.Value); break; default: throw new ParserException(Strings.Parser_ErrorP_IdentifierExpected + GetLocationInfoWithValue(curToken)); } curToken = tokens.Extract(); return; } // FuncIDent: IDENTIFIER ( [Expr] [, Expr]*) | IDENTIFIER private bool MatchFuncIDent(out IExpr result) { IExpr e; string fullname; // will hold the full name string method; // will hold method name or second part of name string firstPart; // will hold the collection name string thirdPart; // will hold third part of name bool bOnePart; // simple name: no ! or . in name result = null; if (curToken.Type != TokenTypes.IDENTIFIER) return false; // Disentangle method calls from collection references method = fullname = curToken.Value; curToken = tokens.Extract(); // Break the name into parts char[] breakChars = new char[] {'!', '.'}; int posBreak = method.IndexOfAny(breakChars); if (posBreak > 0) { bOnePart = false; firstPart = method.Substring(0, posBreak); method = method.Substring(posBreak+1); // rest of expression } else { bOnePart = true; firstPart = method; } posBreak = method.IndexOf('.'); if (posBreak > 0) { thirdPart = method.Substring(posBreak + 1); // rest of expression method = method.Substring(0, posBreak); } else { thirdPart = null; } if (curToken.Type != TokenTypes.LPAREN) switch (firstPart) { case "Fields": Field f = idLookup.LookupField(method); if (f == null && !this._InAggregate) { throw new ParserException(string.Format(Strings.Parser_ErrorP_FieldNotFound, method)); } if (thirdPart == null || thirdPart == "Value") { if (f == null) { FunctionField ff; result = ff = new FunctionField(method); this._FieldResolve.Add(ff); } else result = new FunctionField(f); } else if (thirdPart == "IsMissing") { if (f == null) { FunctionField ff; result = ff = new FunctionFieldIsMissing(method); this._FieldResolve.Add(ff); } else result = new FunctionFieldIsMissing(f); } else throw new ParserException(string.Format(Strings.Parser_ErrorP_FieldSupportsValueAndIsMissing, method)); return true; case "Parameters": // see ResolveParametersMethod for resolution of MultiValue parameter function reference ReportParameter p = idLookup.LookupParameter(method); if (p == null) throw new ParserException(string.Format(Strings.Parser_ErrorP_ParameterNotFound, method)); int ci = thirdPart == null? -1: thirdPart.IndexOf(".Count"); if (ci > 0) thirdPart = thirdPart.Substring(0, ci); FunctionReportParameter r; if (thirdPart == null || thirdPart == "Value") r = new FunctionReportParameter(p); else if (thirdPart == "Label") r = new FunctionReportParameterLabel(p); else throw new ParserException(string.Format(Strings.Parser_ErrorP_ParameterSupportsValueAndLabel, method)); if (ci > 0) r.SetParameterMethod("Count", null); result = r; return true; case "ReportItems": Textbox t = idLookup.LookupReportItem(method); if (t == null) throw new ParserException(string.Format(Strings.Parser_ErrorP_ItemNotFound, method)); if (thirdPart != null && thirdPart != "Value") throw new ParserException(string.Format(Strings.Parser_ErrorP_ItemSupportsValue, method)); result = new FunctionTextbox(t, idLookup.ExpressionName); return true; case "Globals": e = idLookup.LookupGlobal(method); if (e == null) throw new ParserException(string.Format(Strings.Parser_ErrorP_GlobalsNotFound, method)); result = e; return true; case "User": e = idLookup.LookupUser(method); if (e == null) throw new ParserException(string.Format(Strings.Parser_ErrorP_UserVarNotFound, method)); result = e; return true; case "Recursive": // Only valid for some aggregate functions result = new IdentifierKey(IdentifierKeyEnum.Recursive); return true; case "Simple": // Only valid for some aggregate functions result = new IdentifierKey(IdentifierKeyEnum.Simple); return true; default: if (!bOnePart) throw new ParserException(string.Format(Strings.Parser_ErrorP_UnknownIdentifer, fullname)); switch (method.ToLower()) // lexer should probably mark these { case "true": case "false": result = new ConstantBoolean(method.ToLower()); break; default: // usually this is enum that will be used in an aggregate result = new Identifier(method); break; } return true; } // We've got an function reference curToken = tokens.Extract(); // get rid of '(' // Got a function now obtain the arguments int argCount=0; bool isAggregate = IsAggregate(method, bOnePart); if (_NoAggregate && isAggregate) throw new ParserException(string.Format(Strings.Parser_ErrorP_AggregateCannotUsedWithinGrouping, method)); if (_InAggregate && isAggregate) throw new ParserException(string.Format(Strings.Parser_ErrorP_AggregateCannotNestedInAnotherAggregate, method)); _InAggregate = isAggregate; if (_InAggregate) _FieldResolve = new List<FunctionField>(); List<IExpr> largs = new List<IExpr>(); while(true) { if (curToken.Type == TokenTypes.RPAREN) { // We've got our function curToken = tokens.Extract(); break; } if (argCount == 0) { // don't need to do anything } else if (curToken.Type == TokenTypes.COMMA) { curToken = tokens.Extract(); } else throw new ParserException(Strings.Parser_ErrorP_Invalid_function_arguments + GetLocationInfoWithValue(curToken)); MatchExprAndOr(out e); if (e == null) throw new ParserException(Strings.Parser_ErrorP_ExpectingComma + GetLocationInfoWithValue(curToken)); largs.Add(e); argCount++; } if (_InAggregate) { ResolveFields(method, this._FieldResolve, largs); _FieldResolve = null; _InAggregate = false; } IExpr[] args = largs.ToArray(); object scope; bool bSimple; if (!bOnePart) { result = (firstPart == "Parameters")? ResolveParametersMethod(method, thirdPart, args): ResolveMethodCall(fullname, args); // throw exception when fails } else switch(method.ToLower()) { case "iif": if (args.Length != 3) throw new ParserException(Strings.Parser_ErrorP_iff_function_requires_3_arguments + GetLocationInfo(curToken)); // We allow any type for the first argument; it will get converted to boolean at runtime // if (args[0].GetTypeCode() != TypeCode.Boolean) // throw new ParserException("First argument to iif function must be boolean." + GetLocationInfo(curToken)); result = new FunctionIif(args[0], args[1], args[2]); break; case "choose": if (args.Length <= 2) throw new ParserException(Strings.Parser_ErrorP_ChooseRequires2Arguments + GetLocationInfo(curToken)); switch (args[0].GetTypeCode()) { case TypeCode.Double: case TypeCode.Single: case TypeCode.Int32: case TypeCode.Decimal: case TypeCode.Int16: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: break; default: throw new ParserException(Strings.Parser_ErrorP_ChooseFirstArgumentMustNumeric + GetLocationInfo(curToken)); } result = new FunctionChoose(args); break; case "switch": if (args.Length <= 2) throw new ParserException(Strings.Parser_ErrorP_SwitchRequires2Arguments + GetLocationInfo(curToken)); if (args.Length % 2 != 0) throw new ParserException(Strings.Parser_ErrorP_SwitchMustEvenArguments + GetLocationInfo(curToken)); for (int i=0; i < args.Length; i = i+2) { if (args[i].GetTypeCode() != TypeCode.Boolean) throw new ParserException(Strings.Parser_ErrorP_SwitchMustBoolean + GetLocationInfo(curToken)); } result = new FunctionSwitch(args); break; case "format": if (args.Length > 2 || args.Length < 1) throw new ParserException(Strings.Parser_ErrorP_FormatRequires2Arguments + GetLocationInfo(curToken)); if (args.Length == 1) { result = new FunctionFormat(args[0], new ConstantString("")); } else { if (args[1].GetTypeCode() != TypeCode.String) throw new ParserException(Strings.Parser_ErrorP_SecondMustString + GetLocationInfo(curToken)); result = new FunctionFormat(args[0], args[1]); } break; case "fields": if (args.Length != 1) throw new ParserException(Strings.Parser_ErrorP_FieldsRequires1Argument + GetLocationInfo(curToken)); result = new FunctionFieldCollection(idLookup.Fields, args[0]); if (curToken.Type == TokenTypes.DOT) { // user placed "." TODO: generalize this code curToken = tokens.Extract(); // skip past dot operator if (curToken.Type == TokenTypes.IDENTIFIER && curToken.Value.ToLowerInvariant() == "value") curToken = tokens.Extract(); // only support "value" property for now else throw new ParserException(string.Format(Strings.Parser_ErrorP_UnknownProperty, curToken.Value, "Fields") + GetLocationInfo(curToken)); } break; case "parameters": if (args.Length != 1) throw new ParserException(Strings.Parser_ErrorP_ParametersRequires1Argument + GetLocationInfo(curToken)); result = new FunctionParameterCollection(idLookup.Parameters, args[0]); if (curToken.Type == TokenTypes.DOT) { // user placed "." curToken = tokens.Extract(); // skip past dot operator if (curToken.Type == TokenTypes.IDENTIFIER && curToken.Value.ToLowerInvariant() == "value") curToken = tokens.Extract(); // only support "value" property for now else throw new ParserException((string.Format(Strings.Parser_ErrorP_UnknownProperty, curToken.Value, "Parameters") + GetLocationInfo(curToken))); } break; case "reportitems": if (args.Length != 1) throw new ParserException(Strings.Parser_ErrorP_ReportItemsRequires1Argument + GetLocationInfo(curToken)); result = new FunctionReportItemCollection(idLookup.ReportItems, args[0]); if (curToken.Type == TokenTypes.DOT) { // user placed "." curToken = tokens.Extract(); // skip past dot operator if (curToken.Type == TokenTypes.IDENTIFIER && curToken.Value.ToLowerInvariant() == "value") curToken = tokens.Extract(); // only support "value" property for now else throw new ParserException((string.Format(Strings.Parser_ErrorP_UnknownProperty, curToken.Value, "ReportItems") + GetLocationInfo(curToken))); } break; case "globals": if (args.Length != 1) throw new ParserException(Strings.Parser_ErrorP_GlobalsRequires1Argument + GetLocationInfo(curToken)); result = new FunctionGlobalCollection(idLookup.Globals, args[0]); break; case "user": if (args.Length != 1) throw new ParserException(Strings.Parser_ErrorP_UserRequires1Argument + GetLocationInfo(curToken)); result = new FunctionUserCollection(idLookup.User, args[0]); break; case "sum": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrSum aggrFS = new FunctionAggrSum(_DataCache, args[0], scope); aggrFS.LevelCheck = bSimple; result = aggrFS; break; case "avg": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrAvg aggrFA = new FunctionAggrAvg(_DataCache, args[0], scope); aggrFA.LevelCheck = bSimple; result = aggrFA; break; case "min": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrMin aggrFMin = new FunctionAggrMin(_DataCache, args[0], scope); aggrFMin.LevelCheck = bSimple; result = aggrFMin; break; case "max": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrMax aggrFMax = new FunctionAggrMax(_DataCache, args[0], scope); aggrFMax.LevelCheck = bSimple; result = aggrFMax; break; case "first": scope = ResolveAggrScope(args, 2, out bSimple); result = new FunctionAggrFirst(_DataCache, args[0], scope); break; case "last": scope = ResolveAggrScope(args, 2, out bSimple); result = new FunctionAggrLast(_DataCache, args[0], scope); break; case "next": scope = ResolveAggrScope(args, 2, out bSimple); result = new FunctionAggrNext(_DataCache, args[0], scope); break; case "previous": scope = ResolveAggrScope(args, 2, out bSimple); result = new FunctionAggrPrevious(_DataCache, args[0], scope); break; case "level": scope = ResolveAggrScope(args, 1, out bSimple); result = new FunctionAggrLevel(scope); break; case "aggregate": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrArray aggr = new FunctionAggrArray(_DataCache, args[0], scope); aggr.LevelCheck = bSimple; result = aggr; break; case "count": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrCount aggrFC = new FunctionAggrCount(_DataCache, args[0], scope); aggrFC.LevelCheck = bSimple; result = aggrFC; break; case "countrows": scope = ResolveAggrScope(args, 1, out bSimple); FunctionAggrCountRows aggrFCR = new FunctionAggrCountRows(scope); aggrFCR.LevelCheck = bSimple; result = aggrFCR; break; case "countdistinct": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrCountDistinct aggrFCD = new FunctionAggrCountDistinct(_DataCache, args[0], scope); aggrFCD.LevelCheck = bSimple; result = aggrFCD; break; case "rownumber": scope = ResolveAggrScope(args, 1, out bSimple); IExpr texpr = new ConstantDouble("0"); result = new FunctionAggrRvCount(_DataCache, texpr, scope); break; case "runningvalue": if (args.Length < 2 || args.Length > 3) throw new ParserException(Strings.Parser_ErrorP_RunningValue_takes_2_or_3_arguments + GetLocationInfo(curToken)); string aggrFunc = args[1].EvaluateString(null, null); if (aggrFunc == null) throw new ParserException(Strings.Parser_ErrorP_RunningValueArgumentInvalid + GetLocationInfo(curToken)); scope = ResolveAggrScope(args, 3, out bSimple); switch(aggrFunc.ToLower()) { case "sum": result = new FunctionAggrRvSum(_DataCache, args[0], scope); break; case "avg": result = new FunctionAggrRvAvg(_DataCache, args[0], scope); break; case "count": result = new FunctionAggrRvCount(_DataCache, args[0], scope); break; case "max": result = new FunctionAggrRvMax(_DataCache, args[0], scope); break; case "min": result = new FunctionAggrRvMin(_DataCache, args[0], scope); break; case "stdev": result = new FunctionAggrRvStdev(_DataCache, args[0], scope); break; case "stdevp": result = new FunctionAggrRvStdevp(_DataCache, args[0], scope); break; case "var": result = new FunctionAggrRvVar(_DataCache, args[0], scope); break; case "varp": result = new FunctionAggrRvVarp(_DataCache, args[0], scope); break; default: throw new ParserException(string.Format(Strings.Parser_ErrorP_RunningValueNotSupported, aggrFunc) + GetLocationInfo(curToken)); } break; case "stdev": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrStdev aggrSDev = new FunctionAggrStdev(_DataCache, args[0], scope); aggrSDev.LevelCheck = bSimple; result = aggrSDev; break; case "stdevp": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrStdevp aggrSDevP = new FunctionAggrStdevp(_DataCache, args[0], scope); aggrSDevP.LevelCheck = bSimple; result = aggrSDevP; break; case "var": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrVar aggrVar = new FunctionAggrVar(_DataCache, args[0], scope); aggrVar.LevelCheck = bSimple; result = aggrVar; break; case "varp": scope = ResolveAggrScope(args, 2, out bSimple); FunctionAggrVarp aggrVarP = new FunctionAggrVarp(_DataCache, args[0], scope); aggrVarP.LevelCheck = bSimple; result = aggrVarP; break; default: result = ResolveMethodCall(fullname, args); // through exception when fails break; } return true; } private bool IsAggregate(string method, bool onePart) { if (!onePart) return false; bool rc; switch(method.ToLower()) { // this needs to include all aggregate functions case "sum": case "avg": case "min": case "max": case "first": case "last": case "next": case "previous": case "aggregate": case "count": case "countrows": case "countdistinct": case "stdev": case "stdevp": case "var": case "varp": case "rownumber": case "runningvalue": rc = true; break; default: rc = false; break; } return rc; } private void ResolveFields(string aggr, List<FunctionField> fargs, List<IExpr> args) { if (fargs == null || fargs.Count == 0) return; // get the scope argument offset int argOffset = aggr.ToLower() == "countrows"? 1: 2; DataSetDefn ds; if (args.Count == argOffset) { string dsname=null; IExpr e = args[argOffset-1]; if (e is ConstantString) dsname = e.EvaluateString(null, null); if (dsname == null) throw new ParserException(string.Format(Strings.Parser_ErrorP_ScopeMustConstant, aggr)); ds = this.idLookup.ScopeDataSet(dsname); if (ds == null) throw new ParserException(string.Format(Strings.Parser_ErrorP_ScopeNotKnownDataSet, dsname)); } else { ds = this.idLookup.ScopeDataSet(null); if (ds == null) throw new ParserException(string.Format(Strings.Parser_ErrorP_NoScope4Aggregate, aggr)); } foreach (FunctionField f in fargs) { if (f.Fld != null) continue; Field dsf = ds.Fields == null? null: ds.Fields[f.Name]; if (dsf == null) throw new ParserException(string.Format(Strings.Parser_ErrorP_FieldNotInDataSet, f.Name, ds.Name.Nm)); f.Fld = dsf; } return; } private object ResolveAggrScope(IExpr[] args, int indexOfScope, out bool bSimple) { object scope; bSimple = true; if (args.Length == 0 && indexOfScope > 1) throw new ParserException(Strings.Parser_ErrorP_AggregateMust1Argument); if (args.Length >= indexOfScope) { string n = args[indexOfScope-1].EvaluateString(null, null); if (idLookup.IsPageScope) throw new ParserException(string.Format(Strings.Parser_ErrorP_ScopeNotSpecifiedInHeaderOrFooter,n)); scope = idLookup.LookupScope(n); if (scope == null) { Identifier ie = args[indexOfScope-1] as Identifier; if (ie == null || ie.IsNothing == false) // check for "nothing" identifier throw new ParserException(string.Format(Strings.Parser_ErrorP_ScopeNotKnownGrouping,n)); } if (args.Length > indexOfScope) // has recursive/simple been specified { IdentifierKey k = args[indexOfScope] as IdentifierKey; if (k == null) throw new ParserException(Strings.Parser_ErrorP_ScopeIdentifer + GetLocationInfo(curToken)); if (k.Value == IdentifierKeyEnum.Recursive) bSimple = false; } } else if (idLookup.IsPageScope) { scope = "pghf"; // indicates page header or footer } else { scope = idLookup.LookupGrouping(); if (scope == null) { scope = idLookup.LookupMatrix(); if (scope == null) scope = idLookup.ScopeDataSet(null); } } return scope; } private IExpr ResolveParametersMethod(string pname, string vf, IExpr[] args) { FunctionReportParameter result; ReportParameter p = idLookup.LookupParameter(pname); if (p == null) throw new ParserException(string.Format(Strings.Parser_ErrorP_ParameterNotFound, pname)); string arrayMethod; int posBreak = vf.IndexOf('.'); if (posBreak > 0) { arrayMethod = vf.Substring(posBreak + 1); // rest of expression vf = vf.Substring(0, posBreak); } else arrayMethod = null; if (vf == null || vf == "Value") result = new FunctionReportParameter(p); else if (vf == "Label") result = new FunctionReportParameterLabel(p); else throw new ParserException(string.Format(Strings.Parser_ErrorP_ParameterSupportsValueAndLabel, pname)); result.SetParameterMethod(arrayMethod, args); return result; } private IExpr ResolveMethodCall(string fullname, IExpr[] args) { string cls, method; int idx = fullname.LastIndexOf('.'); if (idx > 0) { cls = fullname.Substring(0, idx); method = fullname.Substring(idx+1); } else { cls = ""; method = fullname; } // Fill out the argument types Type[] argTypes = new Type[args.Length]; for (int i=0; i < args.Length; i++) { argTypes[i] = XmlUtil.GetTypeFromTypeCode(args[i].GetTypeCode()); } // See if this is a function within the Code element Type cType=null; bool bCodeFunction = false; if (cls == "" || cls.ToLower() == "code") { cType = idLookup.CodeClassType; // get the code class type if (cType != null) { if (XmlUtil.GetMethod(cType, method, argTypes) == null) cType = null; // try for the method in the instance else bCodeFunction = true; } if (cls != "" && !bCodeFunction) throw new ParserException(string.Format(Strings.Parser_ErrorP_NotCodeMethod, method)); } // See if this is a function within the instance classes ReportClass rc=null; if (cType == null) { rc = idLookup.LookupInstance(cls); // is this an instance variable name? if (rc == null) { cType=idLookup.LookupType(cls); // no, must be a static class reference } else { cType= idLookup.LookupType(rc.ClassName); // yes, use the classname of the ReportClass } } string syscls=null; if (cType == null) { // ok try for some of the system functions switch(cls) { case "Math": syscls = "System.Math"; break; case "String": syscls = "System.String"; break; case "Convert": syscls = "System.Convert"; break; case "Financial": syscls = "fyiReporting.RDL.Financial"; break; default: syscls = "fyiReporting.RDL.VBFunctions"; break; } if (syscls != null) { cType = Type.GetType(syscls, false, true); } } if (cType == null) { string err; if (cls == null || cls.Length == 0) err = String.Format(Strings.Parser_ErrorP_FunctionUnknown, method); else err = String.Format(Strings.Parser_ErrorP_ClassUnknown, cls); throw new ParserException(err); } IExpr result=null; MethodInfo mInfo = XmlUtil.GetMethod(cType, method, argTypes); if (mInfo == null) { string err; if (cls == null || cls.Length == 0) err = String.Format(Strings.Parser_ErrorP_FunctionUnknown, method); else err = String.Format(Strings.Parser_ErrorP_FunctionOfClassUnknown, method, cls); throw new ParserException(err); } // when nullable object (e.g. DateTime?, int?,...) // we need to get the underlying type Type t = mInfo.ReturnType; if (Type.GetTypeCode(t) == TypeCode.Object) { try { t = Nullable.GetUnderlyingType(t); } catch { } // ok if it fails; must not be nullable object } // obtain the TypeCode TypeCode tc = Type.GetTypeCode(t); if (bCodeFunction) result = new FunctionCode(method, args, tc); else if (syscls != null) result = new FunctionSystem(syscls, method, args, tc); else if (rc == null) result = new FunctionCustomStatic(idLookup.CMS, cls, method, args, tc); else result = new FunctionCustomInstance(rc, method, args, tc); return result; } } }
// DateRangeSlider.cs // using System; using System.Collections; using System.Collections.Generic; using System.Html; using System.Runtime.CompilerServices; using AngularApi; using Custom; using jQueryApi; namespace Custom { public class DateRangeSlider : DateRangeSliderOptions { public static void Init(AngularStatic angular, AngularModule module) { module.directive("dateHigh", (Func<object>)delegate() { return new Dictionary( "restrict", "A", //"require", "ngModel", "link", (Action<DateRangeScope, jQueryObject, object, DateRangeSliderOptions>)delegate(DateRangeScope scope, jQueryObject element, object attr, DateRangeSliderOptions ngModel) { element.On("change", (jQueryEventHandler)delegate(jQueryEvent ev) { scope.Apply((System.Action)delegate() { string value = element.GetValue(); int offset = Date.Parse(value).GetTime(); scope.slider.offset.high = offset; }); }); }); }); module.directive("dateLow", (Func<object>)delegate() { return new Dictionary( "restrict", "A", //"require", "ngModel", "link", (Action<DateRangeScope, jQueryObject, object, DateRangeSliderOptions>)delegate(DateRangeScope scope, jQueryObject element, object attr, DateRangeSliderOptions ngModel) { element.On("change", (jQueryEventHandler)delegate(jQueryEvent ev) { scope.Apply((System.Action)delegate() { string value = element.GetValue(); int offset = Date.Parse(value).GetTime(); scope.slider.offset.low = offset; }); }); }); }); module.directive("dateRange", (Func<object>)delegate() { return new Dictionary( "restrict", "A", "link", (Action<DateRangeScope, jQueryObject, object, DateRangeSliderOptions>)delegate(DateRangeScope scope, jQueryObject element, object attr, DateRangeSliderOptions ngModel) { // catch the element scope.slider.el = element; element.Data("Custom.DateRangeSlider", scope.slider); }); }); module.directive("rangeTrack", (Func<object>)delegate() { return new Dictionary( "restrict", "A", "link", (Action<DateRangeScope, jQueryObject, object, DateRangeSliderOptions>)delegate(DateRangeScope scope, jQueryObject element, object attr, DateRangeSliderOptions ngModel) { // catch the element scope.slider.trackEl = element; }); }); module.directive("rangeThumb", (Func<object>)delegate() { return new Dictionary( "restrict", "A", "link", (Action<DateRangeScope, jQueryObject, object, DateRangeSliderOptions>)delegate(DateRangeScope scope, jQueryObject element, object attr, DateRangeSliderOptions ngModel) { // catch the element scope.slider.thumbEl = element; }); }); module.directive("rangeHigh", (Func<object>)delegate() { return new Dictionary( "restrict", "A", //"require", "ngModel", "link", (Action<DateRangeScope, jQueryObject, object, DateRangeSliderOptions>)delegate(DateRangeScope scope, jQueryObject element, object attr, DateRangeSliderOptions ngModel) { // catch the element scope.slider.highEl = element; element.On("create", (jQueryEventHandler)delegate(jQueryEvent ev) { int a = 0; }); element.On("slidestart", (jQueryEventHandler)delegate(jQueryEvent ev) { scope.Apply((System.Action)delegate() { int a = 0; }); }); element.On("change", (jQueryEventHandler)delegate(jQueryEvent ev) { scope.Apply((System.Action)delegate() { string value = element.GetValue(); int offset = int.Parse(value); scope.slider.date.high = DateHelper.Date(offset); // update max of the low slider if ((bool)(object)scope.slider.lowEl) { scope.slider.lowEl.Attribute("max", (string)(object)offset); } }); }); element.On("slidestop", (jQueryEventHandler)delegate(jQueryEvent ev) { scope.Apply((System.Action)delegate() { // update max of the low slider if ((bool)(object)scope.slider.lowEl) { //scope.slider.lowEl.Attribute("max", (string)(object)scope.slider.offset.high); // scope.slider.lowEl.Plugin<SliderObject>().Slider(new SliderOptions( "max", scope.slider.offset.high )); scope.slider.lowEl.Plugin<SliderObject>().Slider("refresh"); } }); }); }); }); module.directive("rangeLow", (Func<object>)delegate() { return new Dictionary( "restrict", "A", //"require", "ngModel", "link", (Action<DateRangeScope, jQueryObject, object, DateRangeSliderOptions>)delegate(DateRangeScope scope, jQueryObject element, object attr, DateRangeSliderOptions ngModel) { // catch the element scope.slider.lowEl = element; element.On("slidestart", (jQueryEventHandler)delegate(jQueryEvent ev) { scope.Apply((System.Action)delegate() { int a = 0; }); }); element.On("change", (jQueryEventHandler)delegate(jQueryEvent ev) { scope.Apply((System.Action)delegate() { string value = element.GetValue(); int offset = int.Parse(value); scope.slider.date.low = DateHelper.Date(offset); // update min of the high slider if ((bool)(object)scope.slider.highEl) { scope.slider.highEl.Attribute("min", (string)(object)offset); } }); }); element.On("slidestop", (jQueryEventHandler)delegate(jQueryEvent ev) { scope.Apply((System.Action)delegate() { // update min of the high slider if ((bool)(object)scope.slider.highEl) { // scope.slider.highEl.Attribute("min", (string)(object)scope.slider.offset.low); scope.slider.highEl.Plugin<SliderObject>().Slider(new SliderOptions( "min", scope.slider.offset.low )); scope.slider.highEl.Plugin<SliderObject>().Slider("refresh"); } }); }); }); }); } /// <summary> /// Date range control div element /// </summary> public jQueryObject el; /// <summary> /// Date range track div element /// </summary> public jQueryObject trackEl; /// <summary> /// Date range thumb div element /// </summary> public jQueryObject thumbEl; /// <summary> /// Date range high slider input element /// </summary> public jQueryObject highEl; /// <summary> /// Date range low slider input element /// </summary> /// public jQueryObject lowEl; public DateRangeSlider(DateRangeSliderOptions options) { this.date = jQuery.ExtendObject(new DateRange(), options.date); this.offset = jQuery.ExtendObject(new OffsetRange(), options.offset); } public void setHeight(Number value) { } public void setWidth(Number value) { } } [Imported, IgnoreNamespace, ScriptName("Object")] public class DateRangeSliderOptions : ScriptObject { public DateRange date; /// <summary> /// The values are given by the number of milliseconds between midnight of January 1, 1970 and the specified date. /// See Date.getTime and Date.setTime. /// </summary> public OffsetRange offset; public DateRangeSliderOptions() { } public DateRangeSliderOptions(params object[] nameValuePairs) { } } } [Mixin("$.fn")] public static class DateRangeSliderPlugin { public static jQueryObject DateRangeSlider(DateRangeSliderOptions customOptions) { DateRangeSliderOptions defaultOptions = new DateRangeSliderOptions("myOption", 0 /* name/value pairs corresponding to default options */); DateRangeSliderOptions options = jQuery.ExtendObject<DateRangeSliderOptions>(new DateRangeSliderOptions(), defaultOptions, customOptions); return jQuery.Current.Each(delegate(int i, Element element) { // TODO: Consume the matched elements }); } } #region Script# Support [Imported] public sealed class DateRangeSliderObject : jQueryObject { public jQueryObject DateRangeSlider() { return null; } public jQueryObject DateRangeSlider(DateRangeSliderOptions options) { return null; } } #endregion