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.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Sql; using Microsoft.WindowsAzure.Management.Sql.Models; namespace Microsoft.WindowsAzure.Management.Sql { /// <summary> /// Includes operations for importing and exporting Azure SQL Databases /// into and out of Azure blob storage. /// </summary> internal partial class DacOperations : IServiceOperations<SqlManagementClient>, Microsoft.WindowsAzure.Management.Sql.IDacOperations { /// <summary> /// Initializes a new instance of the DacOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DacOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Exports an Azure SQL Database into a DACPAC file in Azure Blob /// Storage. /// </summary> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server in which the /// database to export resides. /// </param> /// <param name='parameters'> /// Optional. The parameters needed to initiate the export request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response that the service returns once an import or /// export operation has been initiated. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DacImportExportResponse> ExportAsync(string serverName, DacExportParameters parameters, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } if (parameters != null) { if (parameters.BlobCredentials != null) { if (parameters.BlobCredentials.StorageAccessKey == null) { throw new ArgumentNullException("parameters.BlobCredentials.StorageAccessKey"); } if (parameters.BlobCredentials.Uri == null) { throw new ArgumentNullException("parameters.BlobCredentials.Uri"); } } if (parameters.ConnectionInfo != null) { if (parameters.ConnectionInfo.DatabaseName == null) { throw new ArgumentNullException("parameters.ConnectionInfo.DatabaseName"); } if (parameters.ConnectionInfo.Password == null) { throw new ArgumentNullException("parameters.ConnectionInfo.Password"); } if (parameters.ConnectionInfo.ServerName == null) { throw new ArgumentNullException("parameters.ConnectionInfo.ServerName"); } if (parameters.ConnectionInfo.UserName == null) { throw new ArgumentNullException("parameters.ConnectionInfo.UserName"); } } } // 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("serverName", serverName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "ExportAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/DacOperations/Export"; 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2012-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); if (parameters != null) { XElement exportInputElement = new XElement(XName.Get("ExportInput", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); requestDoc.Add(exportInputElement); if (parameters.BlobCredentials != null) { XElement blobCredentialsElement = new XElement(XName.Get("BlobCredentials", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); exportInputElement.Add(blobCredentialsElement); XAttribute typeAttribute = new XAttribute(XName.Get("type", "http://www.w3.org/2001/XMLSchema-instance"), ""); typeAttribute.Value = "BlobStorageAccessKeyCredentials"; blobCredentialsElement.Add(typeAttribute); XElement uriElement = new XElement(XName.Get("Uri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); uriElement.Value = parameters.BlobCredentials.Uri.AbsoluteUri; blobCredentialsElement.Add(uriElement); XElement storageAccessKeyElement = new XElement(XName.Get("StorageAccessKey", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); storageAccessKeyElement.Value = parameters.BlobCredentials.StorageAccessKey; blobCredentialsElement.Add(storageAccessKeyElement); } if (parameters.ConnectionInfo != null) { XElement connectionInfoElement = new XElement(XName.Get("ConnectionInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); exportInputElement.Add(connectionInfoElement); XElement databaseNameElement = new XElement(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); databaseNameElement.Value = parameters.ConnectionInfo.DatabaseName; connectionInfoElement.Add(databaseNameElement); XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); passwordElement.Value = parameters.ConnectionInfo.Password; connectionInfoElement.Add(passwordElement); XElement serverNameElement = new XElement(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); serverNameElement.Value = parameters.ConnectionInfo.ServerName; connectionInfoElement.Add(serverNameElement); XElement userNameElement = new XElement(XName.Get("UserName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); userNameElement.Value = parameters.ConnectionInfo.UserName; connectionInfoElement.Add(userNameElement); } } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // 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 DacImportExportResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DacImportExportResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement guidElement = responseDoc.Element(XName.Get("guid", "http://schemas.microsoft.com/2003/10/Serialization/")); if (guidElement != null) { result.Guid = guidElement.Value; } 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 the status of the import or export operation in the specified /// server with the corresponding request ID. The request ID is /// provided in the responses of the import or export operation. /// </summary> /// <param name='serverName'> /// Required. The name of the server in which the import or export /// operation is taking place. /// </param> /// <param name='fullyQualifiedServerName'> /// Required. The fully qualified domain name of the Azure SQL Database /// Server where the operation is taking place. Example: /// a9s7f7s9d3.database.windows.net /// </param> /// <param name='username'> /// Required. The administrator username for the Azure SQL Database /// Server. /// </param> /// <param name='password'> /// Required. The administrator password for the Azure SQL Database /// Server. /// </param> /// <param name='requestId'> /// Required. The request ID of the operation being queried. The /// request ID is obtained from the responses of the import and export /// operations. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents a list of import or export status values returned from /// GetStatus. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DacGetStatusResponse> GetStatusAsync(string serverName, string fullyQualifiedServerName, string username, string password, string requestId, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } if (fullyQualifiedServerName == null) { throw new ArgumentNullException("fullyQualifiedServerName"); } if (username == null) { throw new ArgumentNullException("username"); } if (password == null) { throw new ArgumentNullException("password"); } 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("serverName", serverName); tracingParameters.Add("fullyQualifiedServerName", fullyQualifiedServerName); tracingParameters.Add("username", username); tracingParameters.Add("password", password); tracingParameters.Add("requestId", requestId); Tracing.Enter(invocationId, this, "GetStatusAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/DacOperations/Status?"; url = url + "servername=" + Uri.EscapeDataString(fullyQualifiedServerName.Trim()); url = url + "&username=" + Uri.EscapeDataString(username.Trim()); url = url + "&password=" + Uri.EscapeDataString(password.Trim()); url = url + "&reqId=" + Uri.EscapeDataString(requestId.Trim()); 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 httpRequest.Headers.Add("x-ms-version", "2012-03-01"); // 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 DacGetStatusResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DacGetStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement arrayOfStatusInfoElement = responseDoc.Element(XName.Get("ArrayOfStatusInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (arrayOfStatusInfoElement != null) { if (arrayOfStatusInfoElement != null) { foreach (XElement statusInfoElement in arrayOfStatusInfoElement.Elements(XName.Get("StatusInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"))) { StatusInfo statusInfoInstance = new StatusInfo(); result.StatusInfoList.Add(statusInfoInstance); XElement blobUriElement = statusInfoElement.Element(XName.Get("BlobUri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (blobUriElement != null) { Uri blobUriInstance = TypeConversion.TryParseUri(blobUriElement.Value); statusInfoInstance.BlobUri = blobUriInstance; } XElement databaseNameElement = statusInfoElement.Element(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (databaseNameElement != null) { string databaseNameInstance = databaseNameElement.Value; statusInfoInstance.DatabaseName = databaseNameInstance; } XElement errorMessageElement = statusInfoElement.Element(XName.Get("ErrorMessage", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (errorMessageElement != null) { bool isNil = false; XAttribute nilAttribute = errorMessageElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance")); if (nilAttribute != null) { isNil = nilAttribute.Value == "true"; } if (isNil == false) { string errorMessageInstance = errorMessageElement.Value; statusInfoInstance.ErrorMessage = errorMessageInstance; } } XElement lastModifiedTimeElement = statusInfoElement.Element(XName.Get("LastModifiedTime", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (lastModifiedTimeElement != null) { DateTime lastModifiedTimeInstance = DateTime.Parse(lastModifiedTimeElement.Value, CultureInfo.InvariantCulture); statusInfoInstance.LastModifiedTime = lastModifiedTimeInstance; } XElement queuedTimeElement = statusInfoElement.Element(XName.Get("QueuedTime", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (queuedTimeElement != null) { DateTime queuedTimeInstance = DateTime.Parse(queuedTimeElement.Value, CultureInfo.InvariantCulture); statusInfoInstance.QueuedTime = queuedTimeInstance; } XElement requestIdElement = statusInfoElement.Element(XName.Get("RequestId", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (requestIdElement != null) { string requestIdInstance = requestIdElement.Value; statusInfoInstance.RequestId = requestIdInstance; } XElement requestTypeElement = statusInfoElement.Element(XName.Get("RequestType", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (requestTypeElement != null) { string requestTypeInstance = requestTypeElement.Value; statusInfoInstance.RequestType = requestTypeInstance; } XElement serverNameElement = statusInfoElement.Element(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (serverNameElement != null) { string serverNameInstance = serverNameElement.Value; statusInfoInstance.ServerName = serverNameInstance; } XElement statusElement = statusInfoElement.Element(XName.Get("Status", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (statusElement != null) { string statusInstance = statusElement.Value; statusInfoInstance.Status = statusInstance; } } } } 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 the status of the import or export operation in the specified /// server with the corresponding request ID. The request ID is /// provided in the responses of the import or export operation. /// </summary> /// <param name='serverName'> /// Required. The name of the server in which the import or export /// operation is taking place. /// </param> /// <param name='parameters'> /// Required. The parameters needed to get the status of an import or /// export operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents a list of import or export status values returned from /// GetStatus. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DacGetStatusResponse> GetStatusPostAsync(string serverName, DacGetStatusParameters parameters, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Password == null) { throw new ArgumentNullException("parameters.Password"); } if (parameters.RequestId == null) { throw new ArgumentNullException("parameters.RequestId"); } if (parameters.ServerName == null) { throw new ArgumentNullException("parameters.ServerName"); } if (parameters.UserName == null) { throw new ArgumentNullException("parameters.UserName"); } // 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("serverName", serverName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "GetStatusPostAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/DacOperations/Status"; 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2012-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement statusInputElement = new XElement(XName.Get("StatusInput", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); requestDoc.Add(statusInputElement); XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); passwordElement.Value = parameters.Password; statusInputElement.Add(passwordElement); XElement requestIdElement = new XElement(XName.Get("RequestId", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); requestIdElement.Value = parameters.RequestId; statusInputElement.Add(requestIdElement); XElement serverNameElement = new XElement(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); serverNameElement.Value = parameters.ServerName; statusInputElement.Add(serverNameElement); XElement userNameElement = new XElement(XName.Get("UserName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); userNameElement.Value = parameters.UserName; statusInputElement.Add(userNameElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // 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 DacGetStatusResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DacGetStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement arrayOfStatusInfoElement = responseDoc.Element(XName.Get("ArrayOfStatusInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (arrayOfStatusInfoElement != null) { if (arrayOfStatusInfoElement != null) { foreach (XElement statusInfoElement in arrayOfStatusInfoElement.Elements(XName.Get("StatusInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"))) { StatusInfo statusInfoInstance = new StatusInfo(); result.StatusInfoList.Add(statusInfoInstance); XElement blobUriElement = statusInfoElement.Element(XName.Get("BlobUri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (blobUriElement != null) { Uri blobUriInstance = TypeConversion.TryParseUri(blobUriElement.Value); statusInfoInstance.BlobUri = blobUriInstance; } XElement databaseNameElement = statusInfoElement.Element(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (databaseNameElement != null) { string databaseNameInstance = databaseNameElement.Value; statusInfoInstance.DatabaseName = databaseNameInstance; } XElement errorMessageElement = statusInfoElement.Element(XName.Get("ErrorMessage", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (errorMessageElement != null) { bool isNil = false; XAttribute nilAttribute = errorMessageElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance")); if (nilAttribute != null) { isNil = nilAttribute.Value == "true"; } if (isNil == false) { string errorMessageInstance = errorMessageElement.Value; statusInfoInstance.ErrorMessage = errorMessageInstance; } } XElement lastModifiedTimeElement = statusInfoElement.Element(XName.Get("LastModifiedTime", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (lastModifiedTimeElement != null) { DateTime lastModifiedTimeInstance = DateTime.Parse(lastModifiedTimeElement.Value, CultureInfo.InvariantCulture); statusInfoInstance.LastModifiedTime = lastModifiedTimeInstance; } XElement queuedTimeElement = statusInfoElement.Element(XName.Get("QueuedTime", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (queuedTimeElement != null) { DateTime queuedTimeInstance = DateTime.Parse(queuedTimeElement.Value, CultureInfo.InvariantCulture); statusInfoInstance.QueuedTime = queuedTimeInstance; } XElement requestIdElement2 = statusInfoElement.Element(XName.Get("RequestId", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (requestIdElement2 != null) { string requestIdInstance = requestIdElement2.Value; statusInfoInstance.RequestId = requestIdInstance; } XElement requestTypeElement = statusInfoElement.Element(XName.Get("RequestType", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (requestTypeElement != null) { string requestTypeInstance = requestTypeElement.Value; statusInfoInstance.RequestType = requestTypeInstance; } XElement serverNameElement2 = statusInfoElement.Element(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (serverNameElement2 != null) { string serverNameInstance = serverNameElement2.Value; statusInfoInstance.ServerName = serverNameInstance; } XElement statusElement = statusInfoElement.Element(XName.Get("Status", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); if (statusElement != null) { string statusInstance = statusElement.Value; statusInfoInstance.Status = statusInstance; } } } } 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> /// Initiates an Import of a DACPAC file from Azure Blob Storage into a /// Azure SQL Database. /// </summary> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server into which the /// database is being imported. /// </param> /// <param name='parameters'> /// Optional. The parameters needed to initiated the Import request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response that the service returns once an import or /// export operation has been initiated. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DacImportExportResponse> ImportAsync(string serverName, DacImportParameters parameters, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } if (parameters != null) { if (parameters.BlobCredentials != null) { if (parameters.BlobCredentials.StorageAccessKey == null) { throw new ArgumentNullException("parameters.BlobCredentials.StorageAccessKey"); } if (parameters.BlobCredentials.Uri == null) { throw new ArgumentNullException("parameters.BlobCredentials.Uri"); } } if (parameters.ConnectionInfo != null) { if (parameters.ConnectionInfo.DatabaseName == null) { throw new ArgumentNullException("parameters.ConnectionInfo.DatabaseName"); } if (parameters.ConnectionInfo.Password == null) { throw new ArgumentNullException("parameters.ConnectionInfo.Password"); } if (parameters.ConnectionInfo.ServerName == null) { throw new ArgumentNullException("parameters.ConnectionInfo.ServerName"); } if (parameters.ConnectionInfo.UserName == null) { throw new ArgumentNullException("parameters.ConnectionInfo.UserName"); } } } // 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("serverName", serverName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "ImportAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/DacOperations/Import"; 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2012-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); if (parameters != null) { XElement importInputElement = new XElement(XName.Get("ImportInput", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); requestDoc.Add(importInputElement); if (parameters.AzureEdition != null) { XElement azureEditionElement = new XElement(XName.Get("AzureEdition", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); azureEditionElement.Value = parameters.AzureEdition; importInputElement.Add(azureEditionElement); } if (parameters.BlobCredentials != null) { XElement blobCredentialsElement = new XElement(XName.Get("BlobCredentials", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); importInputElement.Add(blobCredentialsElement); XAttribute typeAttribute = new XAttribute(XName.Get("type", "http://www.w3.org/2001/XMLSchema-instance"), ""); typeAttribute.Value = "BlobStorageAccessKeyCredentials"; blobCredentialsElement.Add(typeAttribute); XElement uriElement = new XElement(XName.Get("Uri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); uriElement.Value = parameters.BlobCredentials.Uri.AbsoluteUri; blobCredentialsElement.Add(uriElement); XElement storageAccessKeyElement = new XElement(XName.Get("StorageAccessKey", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); storageAccessKeyElement.Value = parameters.BlobCredentials.StorageAccessKey; blobCredentialsElement.Add(storageAccessKeyElement); } if (parameters.ConnectionInfo != null) { XElement connectionInfoElement = new XElement(XName.Get("ConnectionInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); importInputElement.Add(connectionInfoElement); XElement databaseNameElement = new XElement(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); databaseNameElement.Value = parameters.ConnectionInfo.DatabaseName; connectionInfoElement.Add(databaseNameElement); XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); passwordElement.Value = parameters.ConnectionInfo.Password; connectionInfoElement.Add(passwordElement); XElement serverNameElement = new XElement(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); serverNameElement.Value = parameters.ConnectionInfo.ServerName; connectionInfoElement.Add(serverNameElement); XElement userNameElement = new XElement(XName.Get("UserName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); userNameElement.Value = parameters.ConnectionInfo.UserName; connectionInfoElement.Add(userNameElement); } XElement databaseSizeInGBElement = new XElement(XName.Get("DatabaseSizeInGB", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")); databaseSizeInGBElement.Value = parameters.DatabaseSizeInGB.ToString(); importInputElement.Add(databaseSizeInGBElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // 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 DacImportExportResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DacImportExportResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement guidElement = responseDoc.Element(XName.Get("guid", "http://schemas.microsoft.com/2003/10/Serialization/")); if (guidElement != null) { result.Guid = guidElement.Value; } 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(); } } } } }
using System; using System.Collections.Generic; using MicroMapper.Mappers; using Should; using Xunit; using System.Reflection; using System.Linq; namespace MicroMapper.UnitTests { namespace MemberResolution { public class When_mapping_derived_classes_in_arrays : AutoMapperSpecBase { private DtoObject[] _result; public class ModelObject { public string BaseString { get; set; } } public class ModelSubObject : ModelObject { public string SubString { get; set; } } public class DtoObject { public string BaseString { get; set; } } public class DtoSubObject : DtoObject { public string SubString { get; set; } } protected override void Establish_context() { Mapper.Reset(); var model = new[] { new ModelObject {BaseString = "Base1"}, new ModelSubObject {BaseString = "Base2", SubString = "Sub2"} }; Mapper.Initialize(cfg => { cfg.CreateMap<ModelObject, DtoObject>() .Include<ModelSubObject, DtoSubObject>(); cfg.CreateMap<ModelSubObject, DtoSubObject>(); }); _result = (DtoObject[]) Mapper.Map(model, typeof (ModelObject[]), typeof (DtoObject[])); } [Fact] public void Should_map_both_the_base_and_sub_objects() { _result.Length.ShouldEqual(2); _result[0].BaseString.ShouldEqual("Base1"); _result[1].BaseString.ShouldEqual("Base2"); } [Fact] public void Should_map_to_the_correct_respective_dto_types() { _result[0].ShouldBeType(typeof (DtoObject)); _result[1].ShouldBeType(typeof (DtoSubObject)); } } public class When_mapping_derived_classes : AutoMapperSpecBase { private DtoObject _result; public class ModelObject { public string BaseString { get; set; } } public class ModelSubObject : ModelObject { public string SubString { get; set; } } public class DtoObject { public string BaseString { get; set; } } public class DtoSubObject : DtoObject { public string SubString { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<ModelObject, DtoObject>() .Include<ModelSubObject, DtoSubObject>(); cfg.CreateMap<ModelSubObject, DtoSubObject>(); }); } protected override void Because_of() { var model = new ModelSubObject { BaseString = "Base2", SubString = "Sub2" }; _result = Mapper.Map<ModelObject, DtoObject>(model); } [Fact] public void Should_map_to_the_correct_dto_types() { _result.ShouldBeType(typeof(DtoSubObject)); } } public class When_mapping_derived_classes_from_intefaces_to_abstract : AutoMapperSpecBase { private DtoObject[] _result; public interface IModelObject { string BaseString { get; set; } } public class ModelSubObject : IModelObject { public string SubString { get; set; } public string BaseString { get; set; } } public abstract class DtoObject { public virtual string BaseString { get; set; } } public class DtoSubObject : DtoObject { public string SubString { get; set; } } protected override void Establish_context() { Mapper.Reset(); var model = new IModelObject[] { new ModelSubObject {BaseString = "Base2", SubString = "Sub2"} }; Mapper.Initialize(cfg => { cfg.CreateMap<IModelObject, DtoObject>() .Include<ModelSubObject, DtoSubObject>(); cfg.CreateMap<ModelSubObject, DtoSubObject>(); }); _result = (DtoObject[]) Mapper.Map(model, typeof (IModelObject[]), typeof (DtoObject[])); } [Fact] public void Should_map_both_the_base_and_sub_objects() { _result.Length.ShouldEqual(1); _result[0].BaseString.ShouldEqual("Base2"); } [Fact] public void Should_map_to_the_correct_respective_dto_types() { _result[0].ShouldBeType(typeof (DtoSubObject)); ((DtoSubObject) _result[0]).SubString.ShouldEqual("Sub2"); } } public class When_mapping_derived_classes_as_property_of_top_object : AutoMapperSpecBase { private DtoModel _result; public class Model { public IModelObject Object { get; set; } } public interface IModelObject { string BaseString { get; set; } } public class ModelSubObject : IModelObject { public string SubString { get; set; } public string BaseString { get; set; } } public class DtoModel { public DtoObject Object { get; set; } } public abstract class DtoObject { public virtual string BaseString { get; set; } } public class DtoSubObject : DtoObject { public string SubString { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Model, DtoModel>(); cfg.CreateMap<IModelObject, DtoObject>() .Include<ModelSubObject, DtoSubObject>(); cfg.CreateMap<ModelSubObject, DtoSubObject>(); }); } [Fact] public void Should_map_object_to_sub_object() { var model = new Model { Object = new ModelSubObject {BaseString = "Base2", SubString = "Sub2"} }; _result = Mapper.Map<Model, DtoModel>(model); _result.Object.ShouldNotBeNull(); _result.Object.ShouldBeType<DtoSubObject>(); _result.Object.ShouldBeType<DtoSubObject>(); _result.Object.BaseString.ShouldEqual("Base2"); ((DtoSubObject) _result.Object).SubString.ShouldEqual("Sub2"); } } public class When_mapping_dto_with_only_properties : AutoMapperSpecBase { private ModelDto _result; public class ModelObject { public DateTime BaseDate { get; set; } public ModelSubObject Sub { get; set; } public ModelSubObject Sub2 { get; set; } public ModelSubObject SubWithExtraName { get; set; } public ModelSubObject SubMissing { get; set; } } public class ModelSubObject { public string ProperName { get; set; } public ModelSubSubObject SubSub { get; set; } } public class ModelSubSubObject { public string IAmACoolProperty { get; set; } } public class ModelDto { public DateTime BaseDate { get; set; } public string SubProperName { get; set; } public string Sub2ProperName { get; set; } public string SubWithExtraNameProperName { get; set; } public string SubSubSubIAmACoolProperty { get; set; } public string SubMissingSubSubIAmACoolProperty { get; set; } } protected override void Establish_context() { Mapper.Reset(); var model = new ModelObject { BaseDate = new DateTime(2007, 4, 5), Sub = new ModelSubObject { ProperName = "Some name", SubSub = new ModelSubSubObject { IAmACoolProperty = "Cool daddy-o" } }, Sub2 = new ModelSubObject { ProperName = "Sub 2 name" }, SubWithExtraName = new ModelSubObject { ProperName = "Some other name" }, SubMissing = new ModelSubObject { ProperName = "I have a missing sub sub object" } }; Mapper.CreateMap<ModelObject, ModelDto>(); _result = Mapper.Map<ModelObject, ModelDto>(model); } [Fact] public void Should_map_item_in_first_level_of_hierarchy() { _result.BaseDate.ShouldEqual(new DateTime(2007, 4, 5)); } [Fact] public void Should_map_a_member_with_a_number() { _result.Sub2ProperName.ShouldEqual("Sub 2 name"); } [Fact] public void Should_map_item_in_second_level_of_hierarchy() { _result.SubProperName.ShouldEqual("Some name"); } [Fact] public void Should_map_item_with_more_items_in_property_name() { _result.SubWithExtraNameProperName.ShouldEqual("Some other name"); } [Fact] public void Should_map_item_in_any_level_of_depth_in_the_hierarchy() { _result.SubSubSubIAmACoolProperty.ShouldEqual("Cool daddy-o"); } } public class When_mapping_dto_with_only_fields : AutoMapperSpecBase { private ModelDto _result; public class ModelObject { public DateTime BaseDate; public ModelSubObject Sub; public ModelSubObject Sub2; public ModelSubObject SubWithExtraName; public ModelSubObject SubMissing; } public class ModelSubObject { public string ProperName; public ModelSubSubObject SubSub; } public class ModelSubSubObject { public string IAmACoolProperty; } public class ModelDto { public DateTime BaseDate; public string SubProperName; public string Sub2ProperName; public string SubWithExtraNameProperName; public string SubSubSubIAmACoolProperty; public string SubMissingSubSubIAmACoolProperty; } protected override void Establish_context() { Mapper.Reset(); var model = new ModelObject { BaseDate = new DateTime(2007, 4, 5), Sub = new ModelSubObject { ProperName = "Some name", SubSub = new ModelSubSubObject { IAmACoolProperty = "Cool daddy-o" } }, Sub2 = new ModelSubObject { ProperName = "Sub 2 name" }, SubWithExtraName = new ModelSubObject { ProperName = "Some other name" }, SubMissing = new ModelSubObject { ProperName = "I have a missing sub sub object" } }; Mapper.CreateMap<ModelObject, ModelDto>(); _result = Mapper.Map<ModelObject, ModelDto>(model); } [Fact] public void Should_map_item_in_first_level_of_hierarchy() { _result.BaseDate.ShouldEqual(new DateTime(2007, 4, 5)); } [Fact] public void Should_map_a_member_with_a_number() { _result.Sub2ProperName.ShouldEqual("Sub 2 name"); } [Fact] public void Should_map_item_in_second_level_of_hierarchy() { _result.SubProperName.ShouldEqual("Some name"); } [Fact] public void Should_map_item_with_more_items_in_property_name() { _result.SubWithExtraNameProperName.ShouldEqual("Some other name"); } [Fact] public void Should_map_item_in_any_level_of_depth_in_the_hierarchy() { _result.SubSubSubIAmACoolProperty.ShouldEqual("Cool daddy-o"); } } public class When_mapping_dto_with_fields_and_properties : AutoMapperSpecBase { private ModelDto _result; public class ModelObject { public DateTime BaseDate { get; set;} public ModelSubObject Sub; public ModelSubObject Sub2 { get; set;} public ModelSubObject SubWithExtraName; public ModelSubObject SubMissing { get; set; } } public class ModelSubObject { public string ProperName { get; set;} public ModelSubSubObject SubSub; } public class ModelSubSubObject { public string IAmACoolProperty { get; set;} } public class ModelDto { public DateTime BaseDate; public string SubProperName; public string Sub2ProperName { get; set;} public string SubWithExtraNameProperName; public string SubSubSubIAmACoolProperty; public string SubMissingSubSubIAmACoolProperty { get; set;} } protected override void Establish_context() { Mapper.Reset(); var model = new ModelObject { BaseDate = new DateTime(2007, 4, 5), Sub = new ModelSubObject { ProperName = "Some name", SubSub = new ModelSubSubObject { IAmACoolProperty = "Cool daddy-o" } }, Sub2 = new ModelSubObject { ProperName = "Sub 2 name" }, SubWithExtraName = new ModelSubObject { ProperName = "Some other name" }, SubMissing = new ModelSubObject { ProperName = "I have a missing sub sub object" } }; Mapper.CreateMap<ModelObject, ModelDto>(); _result = Mapper.Map<ModelObject, ModelDto>(model); } [Fact] public void Should_map_item_in_first_level_of_hierarchy() { _result.BaseDate.ShouldEqual(new DateTime(2007, 4, 5)); } [Fact] public void Should_map_a_member_with_a_number() { _result.Sub2ProperName.ShouldEqual("Sub 2 name"); } [Fact] public void Should_map_item_in_second_level_of_hierarchy() { _result.SubProperName.ShouldEqual("Some name"); } [Fact] public void Should_map_item_with_more_items_in_property_name() { _result.SubWithExtraNameProperName.ShouldEqual("Some other name"); } [Fact] public void Should_map_item_in_any_level_of_depth_in_the_hierarchy() { _result.SubSubSubIAmACoolProperty.ShouldEqual("Cool daddy-o"); } } public class When_ignoring_a_dto_property_during_configuration : AutoMapperSpecBase { private TypeMap[] _allTypeMaps; private Source _source; public class Source { public string Value { get; set; } } public class Destination { public bool Ignored { get { return true; } } public string Value { get; set; } } [Fact] public void Should_not_report_it_as_unmapped() { _allTypeMaps.AsEnumerable().ForEach(t => t.GetUnmappedPropertyNames().ShouldBeOfLength(0)); } [Fact] public void Should_map_successfully() { var destination = Mapper.Map<Source, Destination>(_source); destination.Value.ShouldEqual("foo"); destination.Ignored.ShouldBeTrue(); } [Fact] public void Should_succeed_configration_check() { Mapper.AssertConfigurationIsValid(); } protected override void Establish_context() { _source = new Source {Value = "foo"}; Mapper.CreateMap<Source, Destination>() .ForMember(x => x.Ignored, opt => opt.Ignore()); _allTypeMaps = Mapper.GetAllTypeMaps(); } } public class When_mapping_dto_with_get_methods : AutoMapperSpecBase { private ModelDto _result; public class ModelObject { public string GetSomeCoolValue() { return "Cool value"; } public ModelSubObject Sub { get; set; } } public class ModelSubObject { public string GetSomeOtherCoolValue() { return "Even cooler"; } } public class ModelDto { public string SomeCoolValue { get; set; } public string SubSomeOtherCoolValue { get; set; } } protected override void Establish_context() { var model = new ModelObject { Sub = new ModelSubObject() }; Mapper.CreateMap<ModelObject, ModelDto>(); _result = Mapper.Map<ModelObject, ModelDto>(model); } [Fact] public void Should_map_base_method_value() { _result.SomeCoolValue.ShouldEqual("Cool value"); } [Fact] public void Should_map_second_level_method_value_off_of_property() { _result.SubSomeOtherCoolValue.ShouldEqual("Even cooler"); } } public class When_mapping_a_dto_with_names_matching_properties : AutoMapperSpecBase { private ModelDto _result; public class ModelObject { public string SomeCoolValue() { return "Cool value"; } public ModelSubObject Sub { get; set; } } public class ModelSubObject { public string SomeOtherCoolValue() { return "Even cooler"; } } public class ModelDto { public string SomeCoolValue { get; set; } public string SubSomeOtherCoolValue { get; set; } } protected override void Establish_context() { var model = new ModelObject { Sub = new ModelSubObject() }; Mapper.CreateMap<ModelObject, ModelDto>(); _result = Mapper.Map<ModelObject, ModelDto>(model); } [Fact] public void Should_map_base_method_value() { _result.SomeCoolValue.ShouldEqual("Cool value"); } [Fact] public void Should_map_second_level_method_value_off_of_property() { _result.SubSomeOtherCoolValue.ShouldEqual("Even cooler"); } } public class When_mapping_with_a_dto_subtype : AutoMapperSpecBase { private ModelDto _result; public class ModelObject { public ModelSubObject Sub { get; set; } } public class ModelSubObject { public string SomeValue { get; set; } } public class ModelDto { public ModelSubDto Sub { get; set; } } public class ModelSubDto { public string SomeValue { get; set; } } protected override void Establish_context() { Mapper.CreateMap<ModelObject, ModelDto>(); Mapper.CreateMap<ModelSubObject, ModelSubDto>(); var model = new ModelObject { Sub = new ModelSubObject { SomeValue = "Some value" } }; _result = Mapper.Map<ModelObject, ModelDto>(model); } [Fact] public void Should_map_the_model_sub_type_to_the_dto_sub_type() { _result.Sub.ShouldNotBeNull(); _result.Sub.SomeValue.ShouldEqual("Some value"); } } public class When_mapping_a_dto_with_a_set_only_property_and_a_get_method : AutoMapperSpecBase { private ModelDto _result; public class ModelDto { public int SomeValue { get; set; } } public class ModelObject { private int _someValue; public int SomeValue { set { _someValue = value; } } public int GetSomeValue() { return _someValue; } } protected override void Establish_context() { Mapper.CreateMap<ModelObject, ModelDto>(); var model = new ModelObject(); model.SomeValue = 46; _result = Mapper.Map<ModelObject, ModelDto>(model); } [Fact] public void Should_map_the_get_method_to_the_dto() { _result.SomeValue.ShouldEqual(46); } } public class When_mapping_using_a_custom_member_mappings : AutoMapperSpecBase { private ModelDto _result; public class ModelObject { public int Blarg { get; set; } public string MoreBlarg { get; set; } public int SomeMethodToGetMoreBlarg() { return 45; } public string SomeValue { get; set; } public ModelSubObject SomeWeirdSubObject { get; set; } public string IAmSomeMethod() { return "I am some method"; } } public class ModelSubObject { public int Narf { get; set; } public ModelSubSubObject SubSub { get; set; } public string SomeSubValue() { return "I am some sub value"; } } public class ModelSubSubObject { public int Norf { get; set; } public string SomeSubSubValue() { return "I am some sub sub value"; } } public class ModelDto { public int Splorg { get; set; } public string SomeValue { get; set; } public string SomeMethod { get; set; } public int SubNarf { get; set; } public string SubValue { get; set; } public int GrandChildInt { get; set; } public string GrandChildString { get; set; } public int BlargPlus3 { get; set; } public int BlargMinus2 { get; set; } public int MoreBlarg { get; set; } } protected override void Establish_context() { var model = new ModelObject { Blarg = 10, SomeValue = "Some value", SomeWeirdSubObject = new ModelSubObject { Narf = 5, SubSub = new ModelSubSubObject { Norf = 15 } }, MoreBlarg = "adsfdsaf" }; Mapper .CreateMap<ModelObject, ModelDto>() .ForMember(dto => dto.Splorg, opt => opt.MapFrom(m => m.Blarg)) .ForMember(dto => dto.SomeMethod, opt => opt.MapFrom(m => m.IAmSomeMethod())) .ForMember(dto => dto.SubNarf, opt => opt.MapFrom(m => m.SomeWeirdSubObject.Narf)) .ForMember(dto => dto.SubValue, opt => opt.MapFrom(m => m.SomeWeirdSubObject.SomeSubValue())) .ForMember(dto => dto.GrandChildInt, opt => opt.MapFrom(m => m.SomeWeirdSubObject.SubSub.Norf)) .ForMember(dto => dto.GrandChildString, opt => opt.MapFrom(m => m.SomeWeirdSubObject.SubSub.SomeSubSubValue())) .ForMember(dto => dto.MoreBlarg, opt => opt.MapFrom(m => m.SomeMethodToGetMoreBlarg())) .ForMember(dto => dto.BlargPlus3, opt => opt.MapFrom(m => m.Blarg.Plus(3))) .ForMember(dto => dto.BlargMinus2, opt => opt.MapFrom(m => m.Blarg - 2)); _result = Mapper.Map<ModelObject, ModelDto>(model); } [Fact] public void Should_preserve_the_existing_mapping() { _result.SomeValue.ShouldEqual("Some value"); } [Fact] public void Should_map_top_level_properties() { _result.Splorg.ShouldEqual(10); } [Fact] public void Should_map_methods_results() { _result.SomeMethod.ShouldEqual("I am some method"); } [Fact] public void Should_map_children_properties() { _result.SubNarf.ShouldEqual(5); } [Fact] public void Should_map_children_methods() { _result.SubValue.ShouldEqual("I am some sub value"); } [Fact] public void Should_map_grandchildren_properties() { _result.GrandChildInt.ShouldEqual(15); } [Fact] public void Should_map_grandchildren_methods() { _result.GrandChildString.ShouldEqual("I am some sub sub value"); } [Fact] public void Should_map_blarg_plus_three_using_extension_method() { _result.BlargPlus3.ShouldEqual(13); } [Fact] public void Should_map_blarg_minus_2_using_lambda() { _result.BlargMinus2.ShouldEqual(8); } [Fact] public void Should_override_existing_matches_for_new_mappings() { _result.MoreBlarg.ShouldEqual(45); } } public class When_mapping_using_custom_member_mappings_without_generics : AutoMapperSpecBase { private OrderDTO _result; public class Order { public int Id { get; set; } public string Status { get; set; } public string Customer { get; set; } public string ShippingCode { get; set; } public string Zip { get; set; } } public class OrderDTO { public int Id { get; set; } public string CurrentState { get; set; } public string Contact { get; set; } public string Tracking { get; set; } public string Postal { get; set; } } public class StringCAPS : ValueResolver<string, string> { protected override string ResolveCore(string source) { return source.ToUpper(); } } public class StringLower : ValueResolver<string, string> { protected override string ResolveCore(string source) { return source.ToLower(); } } public class StringPadder : ValueResolver<string, string> { private readonly int _desiredLength; public StringPadder(int desiredLength) { _desiredLength = desiredLength; } protected override string ResolveCore(string source) { return source.PadLeft(_desiredLength); } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap(typeof (Order), typeof (OrderDTO)) .ForMember("CurrentState", map => map.MapFrom("Status")) .ForMember("Contact", map => map.ResolveUsing(new StringCAPS()).FromMember("Customer")) .ForMember("Tracking", map => map.ResolveUsing(typeof(StringLower)).FromMember("ShippingCode")) .ForMember("Postal", map => map.ResolveUsing<StringPadder>().ConstructedBy(() => new StringPadder(6)).FromMember("Zip")); }); var order = new Order { Id = 7, Status = "Pending", Customer = "Buster", ShippingCode = "AbcxY23", Zip = "XYZ" }; _result = Mapper.Map<Order, OrderDTO>(order); } [Fact] public void Should_preserve_existing_mapping() { _result.Id.ShouldEqual(7); } [Fact] public void Should_support_custom_source_member() { _result.CurrentState.ShouldEqual("Pending"); } [Fact] public void Should_support_custom_resolver_on_custom_source_member() { _result.Contact.ShouldEqual("BUSTER"); } [Fact] public void Should_support_custom_resolver_by_type_on_custom_source_member() { _result.Tracking.ShouldEqual("abcxy23"); } [Fact] public void Should_support_custom_resolver_by_generic_type_with_constructor_on_custom_source_member() { _result.Postal.ShouldEqual(" XYZ"); } } public class When_mapping_to_a_top_level_camelCased_destination_member : AutoMapperSpecBase { private Destination _result; public class Source { public int SomeValueWithPascalName { get; set; } } public class Destination { public int someValueWithPascalName { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>(); } protected override void Because_of() { var source = new Source {SomeValueWithPascalName = 5}; _result = Mapper.Map<Source, Destination>(source); } [Fact] public void Should_match_to_PascalCased_source_member() { _result.someValueWithPascalName.ShouldEqual(5); } [Fact] public void Should_pass_configuration_check() { Mapper.AssertConfigurationIsValid(); } } public class When_mapping_to_a_self_referential_object : AutoMapperSpecBase { private CategoryDto _result; public class Category { public string Name { get; set; } public IList<Category> Children { get; set; } } public class CategoryDto { public string Name { get; set; } public CategoryDto[] Children { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Category, CategoryDto>(); } protected override void Because_of() { var category = new Category { Name = "Grandparent", Children = new List<Category>() { new Category { Name = "Parent 1", Children = new List<Category>() { new Category { Name = "Child 1"}, new Category { Name = "Child 2"}, new Category { Name = "Child 3"}, }}, new Category { Name = "Parent 2", Children = new List<Category>() { new Category { Name = "Child 4"}, new Category { Name = "Child 5"}, new Category { Name = "Child 6"}, new Category { Name = "Child 7"}, }}, } }; _result = Mapper.Map<Category, CategoryDto>(category); } [Fact] public void Should_pass_configuration_check() { Mapper.AssertConfigurationIsValid(); } [Fact] public void Should_resolve_any_level_of_hierarchies() { _result.Name.ShouldEqual("Grandparent"); _result.Children.Length.ShouldEqual(2); _result.Children[0].Children.Length.ShouldEqual(3); _result.Children[1].Children.Length.ShouldEqual(4); } } public class When_mapping_to_types_in_a_non_generic_manner : AutoMapperSpecBase { private Destination _result; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap(typeof (Source), typeof (Destination)); } protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source {Value = 5}); } [Fact] public void Should_allow_for_basic_mapping() { _result.Value.ShouldEqual(5); } } public class When_matching_source_and_destination_members_with_underscored_members : AutoMapperSpecBase { private Destination _destination; public class Source { public SubSource some_source { get; set; } } public class SubSource { public int value { get; set; } } public class Destination { public int some_source_value { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention(); cfg.DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention(); cfg.CreateMap<Source, Destination>(); }); } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source {some_source = new SubSource {value = 8}}); } [Fact] public void Should_use_underscores_as_tokenizers_to_flatten() { _destination.some_source_value.ShouldEqual(8); } } public class When_source_members_contain_prefixes : AutoMapperSpecBase { private Destination _destination; public class Source { public int FooValue { get; set; } public int GetOtherValue() { return 10; } } public class Destination { public int Value { get; set; } public int OtherValue { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.RecognizePrefixes("Foo"); cfg.CreateMap<Source, Destination>(); }); } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source {FooValue = 5}); } [Fact] public void Registered_prefixes_ignored() { _destination.Value.ShouldEqual(5); } [Fact] public void Default_prefix_included() { _destination.OtherValue.ShouldEqual(10); } } public class When_source_members_contain_postfixes_and_prefixes : AutoMapperSpecBase { private Destination _destination; public class Source { public int FooValueBar { get; set; } public int GetOtherValue() { return 10; } } public class Destination { public int Value { get; set; } public int OtherValue { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.RecognizePrefixes("Foo"); cfg.RecognizePostfixes("Bar"); cfg.CreateMap<Source, Destination>(); }); } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { FooValueBar = 5 }); } [Fact] public void Registered_prefixes_ignored() { _destination.Value.ShouldEqual(5); } [Fact] public void Default_prefix_included() { _destination.OtherValue.ShouldEqual(10); } } public class When_source_member_names_match_with_underscores : AutoMapperSpecBase { private Destination _destination; public class Source { public int I_amaCraAZZEE____Name { get; set; } } public class Destination { public int I_amaCraAZZEE____Name { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>(); _destination = Mapper.Map<Source, Destination>(new Source {I_amaCraAZZEE____Name = 5}); } [Fact] public void Should_match_based_on_name() { _destination.I_amaCraAZZEE____Name.ShouldEqual(5); } } public class When_recognizing_explicit_member_aliases : AutoMapperSpecBase { private Destination _destination; public class Source { public int Foo { get; set; } } public class Destination { public int Bar { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.RecognizeAlias("Foo", "Bar"); cfg.CreateMap<Source, Destination>(); }); } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source {Foo = 5}); } [Fact] public void Members_that_match_alias_should_be_matched() { _destination.Bar.ShouldEqual(5); } } public class When_destination_members_contain_prefixes : AutoMapperSpecBase { private Destination _destination; public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int FooValue { get; set; } public int BarValue2 { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.RecognizeDestinationPrefixes("Foo","Bar"); cfg.CreateMap<Source, Destination>(); }); } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Value = 5, Value2 = 10 }); } [Fact] public void Registered_prefixes_ignored() { _destination.FooValue.ShouldEqual(5); _destination.BarValue2.ShouldEqual(10); } } } #if !SILVERLIGHT public class When_destination_type_has_private_members : AutoMapperSpecBase { private IDestination _destination; public class Source { public int Value { get; set; } } public interface IDestination { int Value { get; } } public class Destination : IDestination { public Destination(int value) { Value = value; } private Destination() { } public int Value { get; private set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>(); } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source {Value = 5}); } [Fact] public void Should_use_private_accessors_and_constructors() { _destination.Value.ShouldEqual(5); } } #endif public static class MapFromExtensions { public static int Plus(this int left, int right) { return left + right; } } }
/* M2Mqtt Project - MQTT Client Library for .Net and GnatMQ MQTT Broker for .NET Copyright (c) 2014, Paolo Patierno, All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. 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. */ using System; using System.Text; using uPLibrary.Networking.M2Mqtt.Exceptions; namespace uPLibrary.Networking.M2Mqtt.Messages { /// <summary> /// Class for PUBLISH message from client to broker /// </summary> public class MqttMsgPublish : MqttMsgBase { #region Properties... /// <summary> /// Message topic /// </summary> public string Topic { get { return this.topic; } set { this.topic = value; } } /// <summary> /// Message data /// </summary> public byte[] Message { get { return this.message; } set { this.message = value; } } /// <summary> /// Message identifier /// </summary> public ushort MessageId { get { return this.messageId; } set { this.messageId = value; } } #endregion // message topic private string topic; // message data private byte[] message; // message identifier ushort messageId; /// <summary> /// Constructor /// </summary> public MqttMsgPublish() { this.type = MQTT_MSG_PUBLISH_TYPE; } /// <summary> /// Constructor /// </summary> /// <param name="topic">Message topic</param> /// <param name="message">Message data</param> public MqttMsgPublish(string topic, byte[] message) : this(topic, message, false, QOS_LEVEL_AT_MOST_ONCE, false) { } /// <summary> /// Constructor /// </summary> /// <param name="topic">Message topic</param> /// <param name="message">Message data</param> /// <param name="dupFlag">Duplicate flag</param> /// <param name="qosLevel">Quality of Service level</param> /// <param name="retain">Retain flag</param> public MqttMsgPublish(string topic, byte[] message, bool dupFlag, byte qosLevel, bool retain) : base() { this.type = MQTT_MSG_PUBLISH_TYPE; this.topic = topic; this.message = message; this.dupFlag = dupFlag; this.qosLevel = qosLevel; this.retain = retain; this.messageId = 0; } public override byte[] GetBytes() { int fixedHeaderSize = 0; int varHeaderSize = 0; int payloadSize = 0; int remainingLength = 0; byte[] buffer; int index = 0; // topic can't contain wildcards if ((this.topic.IndexOf('#') != -1) || (this.topic.IndexOf('+') != -1)) throw new MqttClientException(MqttClientErrorCode.TopicWildcard); // check topic length if ((this.topic.Length < MIN_TOPIC_LENGTH) || (this.topic.Length > MAX_TOPIC_LENGTH)) throw new MqttClientException(MqttClientErrorCode.TopicLength); byte[] topicUtf8 = Encoding.UTF8.GetBytes(this.topic); // topic name varHeaderSize += topicUtf8.Length + 2; // message id is valid only with QOS level 1 or QOS level 2 if ((this.qosLevel == QOS_LEVEL_AT_LEAST_ONCE) || (this.qosLevel == QOS_LEVEL_EXACTLY_ONCE)) { varHeaderSize += MESSAGE_ID_SIZE; } // check on message with zero length if (this.message != null) // message data payloadSize += this.message.Length; remainingLength += (varHeaderSize + payloadSize); // first byte of fixed header fixedHeaderSize = 1; int temp = remainingLength; // increase fixed header size based on remaining length // (each remaining length byte can encode until 128) do { fixedHeaderSize++; temp = temp / 128; } while (temp > 0); // allocate buffer for message buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; // first fixed header byte buffer[index] = (byte)((MQTT_MSG_PUBLISH_TYPE << MSG_TYPE_OFFSET) | (this.qosLevel << QOS_LEVEL_OFFSET)); buffer[index] |= this.dupFlag ? (byte)(1 << DUP_FLAG_OFFSET) : (byte)0x00; buffer[index] |= this.retain ? (byte)(1 << RETAIN_FLAG_OFFSET) : (byte)0x00; index++; // encode remaining length index = this.encodeRemainingLength(remainingLength, buffer, index); // topic name buffer[index++] = (byte)((topicUtf8.Length >> 8) & 0x00FF); // MSB buffer[index++] = (byte)(topicUtf8.Length & 0x00FF); // LSB Array.Copy(topicUtf8, 0, buffer, index, topicUtf8.Length); index += topicUtf8.Length; // message id is valid only with QOS level 1 or QOS level 2 if ((this.qosLevel == QOS_LEVEL_AT_LEAST_ONCE) || (this.qosLevel == QOS_LEVEL_EXACTLY_ONCE)) { // check message identifier assigned if (this.messageId == 0) throw new MqttClientException(MqttClientErrorCode.WrongMessageId); buffer[index++] = (byte)((this.messageId >> 8) & 0x00FF); // MSB buffer[index++] = (byte)(this.messageId & 0x00FF); // LSB } // check on message with zero length if (this.message != null) { // message data Array.Copy(this.message, 0, buffer, index, this.message.Length); index += this.message.Length; } return buffer; } /// <summary> /// Parse bytes for a PUBLISH message /// </summary> /// <param name="fixedHeaderFirstByte">First fixed header byte</param> /// <param name="channel">Channel connected to the broker</param> /// <returns>PUBLISH message instance</returns> public static MqttMsgPublish Parse(byte fixedHeaderFirstByte, IMqttNetworkChannel channel) { byte[] buffer; int index = 0; byte[] topicUtf8; int topicUtf8Length; MqttMsgPublish msg = new MqttMsgPublish(); // get remaining length and allocate buffer int remainingLength = MqttMsgBase.decodeRemainingLength(channel); buffer = new byte[remainingLength]; // read bytes from socket... int received = channel.Receive(buffer); // topic name topicUtf8Length = ((buffer[index++] << 8) & 0xFF00); topicUtf8Length |= buffer[index++]; topicUtf8 = new byte[topicUtf8Length]; Array.Copy(buffer, index, topicUtf8, 0, topicUtf8Length); index += topicUtf8Length; msg.topic = new String(Encoding.UTF8.GetChars(topicUtf8)); // read QoS level from fixed header msg.qosLevel = (byte)((fixedHeaderFirstByte & QOS_LEVEL_MASK) >> QOS_LEVEL_OFFSET); // read DUP flag from fixed header msg.dupFlag = (((fixedHeaderFirstByte & DUP_FLAG_MASK) >> DUP_FLAG_OFFSET) == 0x01); // read retain flag from fixed header msg.retain = (((fixedHeaderFirstByte & RETAIN_FLAG_MASK) >> RETAIN_FLAG_OFFSET) == 0x01); // message id is valid only with QOS level 1 or QOS level 2 if ((msg.qosLevel == QOS_LEVEL_AT_LEAST_ONCE) || (msg.qosLevel == QOS_LEVEL_EXACTLY_ONCE)) { // message id msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); msg.messageId |= (buffer[index++]); } // get payload with message data int messageSize = remainingLength - index; int remaining = messageSize; int messageOffset = 0; msg.message = new byte[messageSize]; // BUG FIX 26/07/2013 : receiving large payload // copy first part of payload data received Array.Copy(buffer, index, msg.message, messageOffset, received - index); remaining -= (received - index); messageOffset += (received - index); // if payload isn't finished while (remaining > 0) { // receive other payload data received = channel.Receive(buffer); Array.Copy(buffer, 0, msg.message, messageOffset, received); remaining -= received; messageOffset += received; } return msg; } public override string ToString() { #if DEBUG return this.GetDebugString( "PUBLISH", new object[] { "messageId", "topic", "message" }, new object[] { this.messageId, this.topic, this.message }); #else return base.ToString(); #endif } } }
/* The MIT License (MIT) Copyright (c) 2007 - 2020 Microting A/S Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microting.eForm.Infrastructure.Constants; using Microting.eForm.Infrastructure.Data.Entities; using NUnit.Framework; namespace eFormSDK.Base.Tests { [TestFixture] public class SiteTagsUTest : DbTestFixture { [Test] public async Task SiteTags_Create_DoesCreate() { // Arrange Random rnd = new Random(); Site site = new Site { Name = Guid.NewGuid().ToString(), MicrotingUid = rnd.Next(1, 255) }; await site.Create(DbContext).ConfigureAwait(false); Tag tag = new Tag { Name = Guid.NewGuid().ToString(), TaggingsCount = rnd.Next(1, 255) }; await tag.Create(DbContext).ConfigureAwait(false); SiteTag siteTag = new SiteTag { SiteId = site.Id, TagId = tag.Id }; // Act await siteTag.Create(DbContext).ConfigureAwait(false); List<SiteTag> siteTags = DbContext.SiteTags.AsNoTracking().ToList(); List<SiteTagVersion> siteTagVersions = DbContext.SiteTagVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(siteTags); Assert.NotNull(siteTagVersions); Assert.AreEqual(siteTag.SiteId, siteTags[0].SiteId); Assert.AreEqual(siteTag.TagId, siteTags[0].TagId); Assert.AreEqual(siteTag.SiteId, siteTagVersions[0].SiteId); Assert.AreEqual(siteTag.TagId, siteTagVersions[0].TagId); } [Test] public async Task SiteTags_Update_DoesUpdate() { // Arrange Random rnd = new Random(); Site site = new Site { Name = Guid.NewGuid().ToString(), MicrotingUid = rnd.Next(1, 255) }; await site.Create(DbContext).ConfigureAwait(false); Site site2 = new Site { Name = Guid.NewGuid().ToString(), MicrotingUid = rnd.Next(1, 255) }; await site2.Create(DbContext).ConfigureAwait(false); Tag tag = new Tag { Name = Guid.NewGuid().ToString(), TaggingsCount = rnd.Next(1, 255) }; await tag.Create(DbContext).ConfigureAwait(false); Tag tag2 = new Tag { Name = Guid.NewGuid().ToString(), TaggingsCount = rnd.Next(1, 255) }; await tag2.Create(DbContext).ConfigureAwait(false); SiteTag siteTag = new SiteTag { SiteId = site.Id, TagId = tag.Id }; await siteTag.Create(DbContext).ConfigureAwait(false); int? oldSiteId = siteTag.SiteId; int? oldTagId = siteTag.TagId; siteTag.SiteId = site2.Id; siteTag.TagId = tag2.Id; // Act await siteTag.Update(DbContext).ConfigureAwait(false); List<SiteTag> siteTags = DbContext.SiteTags.AsNoTracking().ToList(); List<SiteTagVersion> siteTagVersions = DbContext.SiteTagVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(siteTags); Assert.NotNull(siteTagVersions); Assert.AreEqual(siteTag.SiteId, siteTags[0].SiteId); Assert.AreEqual(siteTag.TagId, siteTags[0].TagId); Assert.AreEqual(oldSiteId, siteTagVersions[0].SiteId); Assert.AreEqual(oldTagId, siteTagVersions[0].TagId); Assert.AreEqual(siteTag.SiteId, siteTagVersions[1].SiteId); Assert.AreEqual(siteTag.TagId, siteTagVersions[1].TagId); } [Test] public async Task SiteTags_Delete_DoesDelete() { // Arrange Random rnd = new Random(); Site site = new Site { Name = Guid.NewGuid().ToString(), MicrotingUid = rnd.Next(1, 255) }; await site.Create(DbContext).ConfigureAwait(false); Tag tag = new Tag { Name = Guid.NewGuid().ToString(), TaggingsCount = rnd.Next(1, 255) }; await tag.Create(DbContext).ConfigureAwait(false); SiteTag siteTag = new SiteTag { SiteId = site.Id, TagId = tag.Id }; await siteTag.Create(DbContext).ConfigureAwait(false); // Act await siteTag.Delete(DbContext).ConfigureAwait(false); List<SiteTag> siteTags = DbContext.SiteTags.AsNoTracking().ToList(); List<SiteTagVersion> siteTagVersions = DbContext.SiteTagVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(siteTags); Assert.NotNull(siteTagVersions); Assert.AreEqual(siteTag.SiteId, siteTags[0].SiteId); Assert.AreEqual(siteTag.TagId, siteTags[0].TagId); Assert.AreEqual(siteTag.WorkflowState, Constants.WorkflowStates.Removed); Assert.AreEqual(siteTag.SiteId, siteTagVersions[0].SiteId); Assert.AreEqual(siteTag.TagId, siteTagVersions[0].TagId); Assert.AreEqual(siteTagVersions[0].WorkflowState, Constants.WorkflowStates.Created); Assert.AreEqual(siteTag.SiteId, siteTagVersions[1].SiteId); Assert.AreEqual(siteTag.TagId, siteTagVersions[1].TagId); Assert.AreEqual(siteTagVersions[1].WorkflowState, Constants.WorkflowStates.Removed); } [Test] public async Task SiteTags_MultipleCreateAndDelete() { Random rnd = new Random(); Site site = new Site { Name = Guid.NewGuid().ToString(), MicrotingUid = rnd.Next(1, 255) }; await site.Create(DbContext).ConfigureAwait(false); Tag tag = new Tag { Name = Guid.NewGuid().ToString(), TaggingsCount = rnd.Next(1, 255) }; await tag.Create(DbContext).ConfigureAwait(false); SiteTag siteTag = new SiteTag { SiteId = site.Id, TagId = tag.Id }; // Act await siteTag.Create(DbContext).ConfigureAwait(false); await siteTag.Delete(DbContext).ConfigureAwait(false); siteTag.WorkflowState = Constants.WorkflowStates.Created; await siteTag.Update(DbContext).ConfigureAwait(false); await siteTag.Delete(DbContext).ConfigureAwait(false); List<SiteTag> siteTags = DbContext.SiteTags.AsNoTracking().ToList(); List<SiteTagVersion> siteTagVersions = DbContext.SiteTagVersions.AsNoTracking().ToList(); // Assert Assert.NotNull(siteTags); Assert.NotNull(siteTagVersions); Assert.AreEqual(siteTag.SiteId, siteTags[0].SiteId); Assert.AreEqual(siteTag.TagId, siteTags[0].TagId); Assert.AreEqual(siteTag.WorkflowState, Constants.WorkflowStates.Removed); Assert.AreEqual(siteTag.SiteId, siteTagVersions[0].SiteId); Assert.AreEqual(siteTag.TagId, siteTagVersions[0].TagId); Assert.AreEqual(siteTagVersions[0].WorkflowState, Constants.WorkflowStates.Created); Assert.AreEqual(siteTag.SiteId, siteTagVersions[1].SiteId); Assert.AreEqual(siteTag.TagId, siteTagVersions[1].TagId); Assert.AreEqual(siteTagVersions[1].WorkflowState, Constants.WorkflowStates.Removed); Assert.AreEqual(siteTag.SiteId, siteTagVersions[2].SiteId); Assert.AreEqual(siteTag.TagId, siteTagVersions[2].TagId); Assert.AreEqual(siteTagVersions[2].WorkflowState, Constants.WorkflowStates.Created); Assert.AreEqual(siteTag.SiteId, siteTagVersions[3].SiteId); Assert.AreEqual(siteTag.TagId, siteTagVersions[3].TagId); Assert.AreEqual(siteTagVersions[3].WorkflowState, Constants.WorkflowStates.Removed); } } }
//=================================================================================== // Microsoft patterns & practices // Composite Application Guidance for Windows Presentation Foundation and Silverlight //=================================================================================== // Copyright (c) Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=================================================================================== // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. //=================================================================================== using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Windows; using Microsoft.Practices.Composite.Regions; using Microsoft.Practices.Composite.Presentation.Properties; namespace Microsoft.Practices.Composite.Presentation.Regions { /// <summary> /// Implementation of <see cref="IRegion"/> that allows multiple active views. /// </summary> public class Region : IRegion { private ObservableCollection<ItemMetadata> itemMetadataCollection; private IViewsCollection views; private IViewsCollection activeViews; private object context; public Region() { this.Behaviors = new RegionBehaviorCollection(this); } /// <summary> /// Gets the collection of <see cref="IRegionBehavior"/>s that can extend the behavior of regions. /// </summary> public IRegionBehaviorCollection Behaviors { get; private set;} /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets a context for the region. This value can be used by the user to share context with the views. /// </summary> /// <value>The context value to be shared.</value> public object Context { get { return this.context; } set { if (this.context != value) { this.context = value; OnPropertyChanged("Context"); } } } private string name; /// <summary> /// Gets the name of the region that uniequely identifies the region within a <see cref="IRegionManager"/>. /// </summary> /// <value>The name of the region.</value> public string Name { get { return this.name; } set { if (this.name != null && this.name != value) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotChangeRegionNameException, this.name)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException(Resources.RegionNameCannotBeEmptyException); } this.name = value; OnPropertyChanged("Name"); } } /// <summary> /// Gets a readonly view of the collection of views in the region. /// </summary> /// <value>An <see cref="IViewsCollection"/> of all the added views.</value> public virtual IViewsCollection Views { get { if (views == null) { views = new ViewsCollection(ItemMetadataCollection, x => true); } return views; } } /// <summary> /// Gets a readonly view of the collection of all the active views in the region. /// </summary> /// <value>An <see cref="IViewsCollection"/> of all the active views.</value> public virtual IViewsCollection ActiveViews { get { if (activeViews == null) { activeViews = new ViewsCollection(ItemMetadataCollection, x => x.IsActive); } return activeViews; } } /// <summary> /// Inserts a view into the region a specific index /// </summary> /// <param name="view">The view to add.</param> /// <param name="index">The index to insert at</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns> public IRegionManager Insert(object view, int index) { return Insert(view, null, index, false); } /// <summary> /// Inserts a new view to the region at a specified index. /// </summary> /// <param name="view">The view to add.</param> /// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="GetView"/>.</param> /// <param name="index">The index to insert at</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns> public IRegionManager Insert(object view, string viewName, int index) { return Insert(view, viewName, index, false); } /// <summary> /// Inserts a new view to the region at a specified index. /// </summary> /// <param name="view">The view to add.</param> /// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="GetView"/>.</param> /// <param name="index">The index to insert at</param> /// <param name="createRegionManagerScope">When <see langword="true"/>, the added view will receive a new instance of <see cref="IRegionManager"/>, otherwise it will use the current region manager for this region.</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>.</returns> public virtual IRegionManager Insert(object view, string viewName, int index, bool createRegionManagerScope) { IRegionManager manager = createRegionManagerScope ? this.RegionManager.CreateRegionManager() : this.RegionManager; InnerAdd(view, viewName, index, manager); return manager; } ///<overloads>Adds a new view to the region.</overloads> /// <summary> /// Adds a new view to the region. /// </summary> /// <param name="view">The view to add.</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns> public IRegionManager Add(object view) { return Add(view, null, false); } /// <summary> /// Adds a new view to the region. /// </summary> /// <param name="view">The view to add.</param> /// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="IRegion.GetView"/>.</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns> public IRegionManager Add(object view, string viewName) { if (string.IsNullOrEmpty(viewName)) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeNullOrEmpty, "viewName")); return Add(view, viewName, false); } /// <summary> /// Adds a new view to the region. /// </summary> /// <param name="view">The view to add.</param> /// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="IRegion.GetView"/>.</param> /// <param name="createRegionManagerScope">When <see langword="true"/>, the added view will receive a new instance of <see cref="IRegionManager"/>, otherwise it will use the current region manager for this region.</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>.</returns> public virtual IRegionManager Add(object view, string viewName, bool createRegionManagerScope) { IRegionManager manager = createRegionManagerScope ? this.RegionManager.CreateRegionManager() : this.RegionManager; InnerAdd(view, viewName, ItemMetadataCollection.Count, manager); return manager; } /// <summary> /// Removes the specified view from the region. /// </summary> /// <param name="view">The view to remove.</param> public virtual void Remove(object view) { ItemMetadata itemMetadata = GetItemMetadataOrThrow(view); ItemMetadataCollection.Remove(itemMetadata); DependencyObject dependencyObject = view as DependencyObject; if (dependencyObject != null && Regions.RegionManager.GetRegionManager(dependencyObject) == this.RegionManager) { dependencyObject.ClearValue(Regions.RegionManager.RegionManagerProperty); } } /// <summary> /// Marks the specified view as active. /// </summary> /// <param name="view">The view to activate.</param> public virtual void Activate(object view) { ItemMetadata itemMetadata = GetItemMetadataOrThrow(view); if (!itemMetadata.IsActive) { itemMetadata.IsActive = true; } } /// <summary> /// Marks the specified view as inactive. /// </summary> /// <param name="view">The view to deactivate.</param> public virtual void Deactivate(object view) { ItemMetadata itemMetadata = GetItemMetadataOrThrow(view); if (itemMetadata.IsActive) { itemMetadata.IsActive = false; } } /// <summary> /// Returns the view instance that was added to the region using a specific name. /// </summary> /// <param name="viewName">The name used when adding the view to the region.</param> /// <returns>Returns the named view or <see langword="null"/> if the view with <paramref name="viewName"/> does not exist in the current region.</returns> public virtual object GetView(string viewName) { if (string.IsNullOrEmpty(viewName)) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeNullOrEmpty, "viewName")); ItemMetadata metadata = ItemMetadataCollection.FirstOrDefault(x => x.Name == viewName); if (metadata != null) return metadata.Item; return null; } private IRegionManager regionManager; /// <summary> /// Gets or sets the <see cref="IRegionManager"/> that will be passed to the views when adding them to the region, unless the view is added by specifying createRegionManagerScope as <see langword="true" />. /// </summary> /// <value>The <see cref="IRegionManager"/> where this <see cref="IRegion"/> is registered.</value> /// <remarks>This is usually used by implementations of <see cref="IRegionManager"/> and should not be /// used by the developer explicitely.</remarks> public IRegionManager RegionManager { get { return this.regionManager; } set { if (this.regionManager != value) { this.regionManager = value; OnPropertyChanged("RegionManager"); } } } /// <summary> /// Gets the collection with all the views along with their metadata. /// </summary> /// <value>An <see cref="ObservableCollection{T}"/> of <see cref="ItemMetadata"/> with all the added views.</value> protected virtual ObservableCollection<ItemMetadata> ItemMetadataCollection { get { if (itemMetadataCollection == null) { itemMetadataCollection = new ObservableCollection<ItemMetadata>(); } return itemMetadataCollection; } } private void InnerAdd(object view, string viewName, int index, IRegionManager scopedRegionManager) { if (ItemMetadataCollection.FirstOrDefault(x => x.Item == view) != null) throw new InvalidOperationException(Resources.RegionViewExistsException); ItemMetadata itemMetadata = new ItemMetadata(view); if (!string.IsNullOrEmpty(viewName)) { if (ItemMetadataCollection.FirstOrDefault(x => x.Name == viewName) != null) throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, Resources.RegionViewNameExistsException, viewName)); itemMetadata.Name = viewName; } DependencyObject dependencyObject = view as DependencyObject; if (dependencyObject != null) { Regions.RegionManager.SetRegionManager(dependencyObject, scopedRegionManager); } ItemMetadataCollection.Insert(index, itemMetadata); } private ItemMetadata GetItemMetadataOrThrow(object view) { if (view == null) throw new ArgumentNullException("view"); ItemMetadata itemMetadata = ItemMetadataCollection.FirstOrDefault(x => x.Item == view); if (itemMetadata == null) throw new ArgumentException(Resources.ViewNotInRegionException, "view"); return itemMetadata; } private void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler Handler = this.PropertyChanged; if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName)); } } }
/* * 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.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Land { public class LandChannel : ILandChannel { #region Constants //Land types set with flags in ParcelOverlay. //Only one of these can be used. public const float BAN_LINE_SAFETY_HIEGHT = 100; public const byte LAND_FLAG_PROPERTY_BORDER_SOUTH = 128; //Equals 10000000 public const byte LAND_FLAG_PROPERTY_BORDER_WEST = 64; //Equals 01000000 //RequestResults (I think these are right, they seem to work): public const int LAND_RESULT_MULTIPLE = 1; // The request they made contained more than a single peice of land public const int LAND_RESULT_SINGLE = 0; // The request they made contained only a single piece of land //ParcelSelectObjects public const int LAND_SELECT_OBJECTS_GROUP = 4; public const int LAND_SELECT_OBJECTS_OTHER = 8; public const int LAND_SELECT_OBJECTS_OWNER = 2; public const byte LAND_TYPE_IS_BEING_AUCTIONED = 5; //Equals 00000101 public const byte LAND_TYPE_IS_FOR_SALE = 4; //Equals 00000100 public const byte LAND_TYPE_OWNED_BY_GROUP = 2; //Equals 00000010 public const byte LAND_TYPE_OWNED_BY_OTHER = 1; //Equals 00000001 public const byte LAND_TYPE_OWNED_BY_REQUESTER = 3; //Equals 00000011 public const byte LAND_TYPE_PUBLIC = 0; //Equals 00000000 //These are other constants. Yay! public const int START_LAND_LOCAL_ID = 1; #endregion private readonly Scene m_scene; private readonly LandManagementModule m_landManagementModule; public LandChannel(Scene scene, LandManagementModule landManagementMod) { m_scene = scene; m_landManagementModule = landManagementMod; } #region ILandChannel Members public ILandObject GetLandObject(float x_float, float y_float) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(x_float, y_float); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.LandData.Name = "NO LAND"; return obj; } public ILandObject GetLandObject(int localID) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(localID); } return null; } public ILandObject GetLandObject(int x, int y) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(x, y); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.LandData.Name = "NO LAND"; return obj; } public List<ILandObject> AllParcels() { if (m_landManagementModule != null) { return m_landManagementModule.AllParcels(); } return new List<ILandObject>(); } public List<ILandObject> ParcelsNearPoint(Vector3 position) { if (m_landManagementModule != null) { return m_landManagementModule.ParcelsNearPoint(position); } return new List<ILandObject>(); } public bool IsLandPrimCountTainted() { if (m_landManagementModule != null) { return m_landManagementModule.IsLandPrimCountTainted(); } return false; } public bool IsForcefulBansAllowed() { if (m_landManagementModule != null) { return m_landManagementModule.AllowedForcefulBans; } return false; } public void UpdateLandObject(int localID, LandData data) { if (m_landManagementModule != null) { m_landManagementModule.UpdateLandObject(localID, data); } } public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) { if (m_landManagementModule != null) { m_landManagementModule.Join(start_x, start_y, end_x, end_y, attempting_user_id); } } public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) { if (m_landManagementModule != null) { m_landManagementModule.Subdivide(start_x, start_y, end_x, end_y, attempting_user_id); } } public void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient) { if (m_landManagementModule != null) { m_landManagementModule.ReturnObjectsInParcel(localID, returnType, agentIDs, taskIDs, remoteClient); } } public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) { if (m_landManagementModule != null) { m_landManagementModule.setParcelObjectMaxOverride(overrideDel); } } public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) { if (m_landManagementModule != null) { m_landManagementModule.setSimulatorObjectMaxOverride(overrideDel); } } public void SetParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime) { if (m_landManagementModule != null) { m_landManagementModule.setParcelOtherCleanTime(remoteClient, localID, otherCleanTime); } } #endregion } }
using System; using Content.Server.Popups; using Content.Server.Power.Components; using Content.Server.Shuttles.Components; using Content.Shared.ActionBlocker; using Content.Shared.Alert; using Content.Shared.Interaction; using Content.Shared.Popups; using Content.Shared.Shuttles; using Content.Shared.Shuttles.Components; using Content.Shared.Tag; using Content.Shared.Verbs; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Player; using Robust.Shared.Utility; namespace Content.Server.Shuttles.EntitySystems { internal sealed class ShuttleConsoleSystem : SharedShuttleConsoleSystem { [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly ActionBlockerSystem _blocker = default!; [Dependency] private readonly AlertsSystem _alertsSystem = default!; [Dependency] private readonly PopupSystem _popup = default!; [Dependency] private readonly TagSystem _tags = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<ShuttleConsoleComponent, ComponentShutdown>(HandleConsoleShutdown); SubscribeLocalEvent<ShuttleConsoleComponent, ActivateInWorldEvent>(HandleConsoleInteract); SubscribeLocalEvent<ShuttleConsoleComponent, PowerChangedEvent>(HandlePowerChange); SubscribeLocalEvent<ShuttleConsoleComponent, GetVerbsEvent<InteractionVerb>>(OnConsoleInteract); SubscribeLocalEvent<PilotComponent, ComponentShutdown>(HandlePilotShutdown); SubscribeLocalEvent<PilotComponent, MoveEvent>(HandlePilotMove); } private void OnConsoleInteract(EntityUid uid, ShuttleConsoleComponent component, GetVerbsEvent<InteractionVerb> args) { if (!args.CanAccess || !args.CanInteract) return; var xform = EntityManager.GetComponent<TransformComponent>(uid); // Maybe move mode onto the console instead? if (!_mapManager.TryGetGrid(xform.GridID, out var grid) || !EntityManager.TryGetComponent(grid.GridEntityId, out ShuttleComponent? shuttle)) return; InteractionVerb verb = new() { Text = Loc.GetString("shuttle-mode-toggle"), Act = () => ToggleShuttleMode(args.User, component, shuttle), Disabled = !xform.Anchored || EntityManager.TryGetComponent(uid, out ApcPowerReceiverComponent? receiver) && !receiver.Powered, }; args.Verbs.Add(verb); } private void ToggleShuttleMode(EntityUid user, ShuttleConsoleComponent consoleComponent, ShuttleComponent shuttleComponent, TransformComponent? consoleXform = null) { // Re-validate if (EntityManager.TryGetComponent(consoleComponent.Owner, out ApcPowerReceiverComponent? receiver) && !receiver.Powered) return; if (!Resolve(consoleComponent.Owner, ref consoleXform)) return; if (!consoleXform.Anchored || consoleXform.GridID != EntityManager.GetComponent<TransformComponent>(shuttleComponent.Owner).GridID) return; switch (shuttleComponent.Mode) { case ShuttleMode.Cruise: shuttleComponent.Mode = ShuttleMode.Docking; _popup.PopupEntity(Loc.GetString("shuttle-mode-docking"), consoleComponent.Owner, Filter.Entities(user)); break; case ShuttleMode.Docking: shuttleComponent.Mode = ShuttleMode.Cruise; _popup.PopupEntity(Loc.GetString("shuttle-mode-cruise"), consoleComponent.Owner, Filter.Entities(user)); break; default: throw new ArgumentOutOfRangeException(); } } public override void Update(float frameTime) { base.Update(frameTime); var toRemove = new RemQueue<PilotComponent>(); foreach (var comp in EntityManager.EntityQuery<PilotComponent>()) { if (comp.Console == null) continue; if (!_blocker.CanInteract(comp.Owner, comp.Console.Owner)) { toRemove.Add(comp); } } foreach (var comp in toRemove) { RemovePilot(comp); } } /// <summary> /// Console requires power to operate. /// </summary> private void HandlePowerChange(EntityUid uid, ShuttleConsoleComponent component, PowerChangedEvent args) { if (!args.Powered) { component.Enabled = false; ClearPilots(component); } else { component.Enabled = true; } } /// <summary> /// If pilot is moved then we'll stop them from piloting. /// </summary> private void HandlePilotMove(EntityUid uid, PilotComponent component, ref MoveEvent args) { if (component.Console == null || component.Position == null) { DebugTools.Assert(component.Position == null && component.Console == null); EntityManager.RemoveComponent<PilotComponent>(uid); return; } if (args.NewPosition.TryDistance(EntityManager, component.Position.Value, out var distance) && distance < PilotComponent.BreakDistance) return; RemovePilot(component); } /// <summary> /// For now pilots just interact with the console and can start piloting with wasd. /// </summary> private void HandleConsoleInteract(EntityUid uid, ShuttleConsoleComponent component, ActivateInWorldEvent args) { if (!_tags.HasTag(args.User, "CanPilot")) { return; } var pilotComponent = EntityManager.EnsureComponent<PilotComponent>(args.User); if (!component.Enabled) { args.User.PopupMessage($"Console is not powered."); return; } args.Handled = true; var console = pilotComponent.Console; if (console != null) { RemovePilot(pilotComponent); if (console == component) { return; } } AddPilot(args.User, component); } private void HandlePilotShutdown(EntityUid uid, PilotComponent component, ComponentShutdown args) { RemovePilot(component); } private void HandleConsoleShutdown(EntityUid uid, ShuttleConsoleComponent component, ComponentShutdown args) { ClearPilots(component); } public void AddPilot(EntityUid entity, ShuttleConsoleComponent component) { if (!EntityManager.TryGetComponent(entity, out PilotComponent? pilotComponent) || component.SubscribedPilots.Contains(pilotComponent)) { return; } if (TryComp<SharedEyeComponent>(entity, out var eye)) { eye.Zoom = component.Zoom; } component.SubscribedPilots.Add(pilotComponent); _alertsSystem.ShowAlert(entity, AlertType.PilotingShuttle); entity.PopupMessage(Loc.GetString("shuttle-pilot-start")); pilotComponent.Console = component; pilotComponent.Position = EntityManager.GetComponent<TransformComponent>(entity).Coordinates; pilotComponent.Dirty(); } public void RemovePilot(PilotComponent pilotComponent) { var console = pilotComponent.Console; if (console is not ShuttleConsoleComponent helmsman) return; pilotComponent.Console = null; pilotComponent.Position = null; if (TryComp<SharedEyeComponent>(pilotComponent.Owner, out var eye)) { eye.Zoom = new(1.0f, 1.0f); } if (!helmsman.SubscribedPilots.Remove(pilotComponent)) return; _alertsSystem.ClearAlert(pilotComponent.Owner, AlertType.PilotingShuttle); pilotComponent.Owner.PopupMessage(Loc.GetString("shuttle-pilot-end")); if (pilotComponent.LifeStage < ComponentLifeStage.Stopping) EntityManager.RemoveComponent<PilotComponent>(pilotComponent.Owner); } public void RemovePilot(EntityUid entity) { if (!EntityManager.TryGetComponent(entity, out PilotComponent? pilotComponent)) return; RemovePilot(pilotComponent); } public void ClearPilots(ShuttleConsoleComponent component) { while (component.SubscribedPilots.TryGetValue(0, out var pilot)) { RemovePilot(pilot); } } } }
// 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.IO; using System.Text; using System.Xml.XPath; using System.Xml.Schema; using System.Diagnostics; using System.Collections.Generic; using System.Globalization; using System.Runtime.Versioning; namespace System.Xml { // Specifies the state of the XmlWriter. public enum WriteState { // Nothing has been written yet. Start, // Writing the prolog. Prolog, // Writing a the start tag for an element. Element, // Writing an attribute value. Attribute, // Writing element content. Content, // XmlWriter is closed; Close has been called. Closed, // Writer is in error state. Error, }; // Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents // that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification. public abstract partial class XmlWriter : IDisposable { // Helper buffer for WriteNode(XmlReader, bool) private char[] _writeNodeBuffer; // Constants private const int WriteNodeBufferSize = 1024; // Returns the settings describing the features of the writer. Returns null for V1 XmlWriters (XmlTextWriter). public virtual XmlWriterSettings Settings { get { return null; } } // Write methods // Writes out the XML declaration with the version "1.0". public abstract void WriteStartDocument(); //Writes out the XML declaration with the version "1.0" and the specified standalone attribute. public abstract void WriteStartDocument(bool standalone); //Closes any open elements or attributes and puts the writer back in the Start state. public abstract void WriteEndDocument(); // Writes out the DOCTYPE declaration with the specified name and optional attributes. public abstract void WriteDocType(string name, string pubid, string sysid, string subset); // Writes out the specified start tag and associates it with the given namespace. public void WriteStartElement(string localName, string ns) { WriteStartElement(null, localName, ns); } // Writes out the specified start tag and associates it with the given namespace and prefix. public abstract void WriteStartElement(string prefix, string localName, string ns); // Writes out a start tag with the specified local name with no namespace. public void WriteStartElement(string localName) { WriteStartElement(null, localName, (string)null); } // Closes one element and pops the corresponding namespace scope. public abstract void WriteEndElement(); // Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>. public abstract void WriteFullEndElement(); // Writes out the attribute with the specified LocalName, value, and NamespaceURI. public void WriteAttributeString(string localName, string ns, string value) { WriteStartAttribute(null, localName, ns); WriteString(value); WriteEndAttribute(); } // Writes out the attribute with the specified LocalName and value. public void WriteAttributeString(string localName, string value) { WriteStartAttribute(null, localName, (string)null); WriteString(value); WriteEndAttribute(); } // Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value. public void WriteAttributeString(string prefix, string localName, string ns, string value) { WriteStartAttribute(prefix, localName, ns); WriteString(value); WriteEndAttribute(); } // Writes the start of an attribute. public void WriteStartAttribute(string localName, string ns) { WriteStartAttribute(null, localName, ns); } // Writes the start of an attribute. public abstract void WriteStartAttribute(string prefix, string localName, string ns); // Writes the start of an attribute. public void WriteStartAttribute(string localName) { WriteStartAttribute(null, localName, (string)null); } // Closes the attribute opened by WriteStartAttribute call. public abstract void WriteEndAttribute(); // Writes out a <![CDATA[...]]>; block containing the specified text. public abstract void WriteCData(string text); // Writes out a comment <!--...-->; containing the specified text. public abstract void WriteComment(string text); // Writes out a processing instruction with a space between the name and text as follows: <?name text?> public abstract void WriteProcessingInstruction(string name, string text); // Writes out an entity reference as follows: "&"+name+";". public abstract void WriteEntityRef(string name); // Forces the generation of a character entity for the specified Unicode character value. public abstract void WriteCharEntity(char ch); // Writes out the given whitespace. public abstract void WriteWhitespace(string ws); // Writes out the specified text content. public abstract void WriteString(string text); // Write out the given surrogate pair as an entity reference. public abstract void WriteSurrogateCharEntity(char lowChar, char highChar); // Writes out the specified text content. public abstract void WriteChars(char[] buffer, int index, int count); // Writes raw markup from the given character buffer. public abstract void WriteRaw(char[] buffer, int index, int count); // Writes raw markup from the given string. public abstract void WriteRaw(string data); // Encodes the specified binary bytes as base64 and writes out the resulting text. public abstract void WriteBase64(byte[] buffer, int index, int count); // Encodes the specified binary bytes as binhex and writes out the resulting text. public virtual void WriteBinHex(byte[] buffer, int index, int count) { BinHexEncoder.Encode(buffer, index, count, this); } // Returns the state of the XmlWriter. public abstract WriteState WriteState { get; } // Closes the XmlWriter and the underlying stream/TextReader (if Settings.CloseOutput is true). public virtual void Close() { } // Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader. public abstract void Flush(); // Returns the closest prefix defined in the current namespace scope for the specified namespace URI. public abstract string LookupPrefix(string ns); // Gets an XmlSpace representing the current xml:space scope. public virtual XmlSpace XmlSpace { get { return XmlSpace.Default; } } // Gets the current xml:lang scope. public virtual string XmlLang { get { return string.Empty; } } // Scalar Value Methods // Writes out the specified name, ensuring it is a valid NmToken according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual void WriteNmToken(string name) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } WriteString(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException)); } // Writes out the specified name, ensuring it is a valid Name according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual void WriteName(string name) { WriteString(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException)); } // Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace. public virtual void WriteQualifiedName(string localName, string ns) { if (ns != null && ns.Length > 0) { string prefix = LookupPrefix(ns); if (prefix == null) { throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns)); } WriteString(prefix); WriteString(":"); } WriteString(localName); } // Writes out the specified value. public virtual void WriteValue(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } WriteString(XmlUntypedConverter.Untyped.ToString(value, null)); } // Writes out the specified value. public virtual void WriteValue(string value) { if (value == null) { return; } WriteString(value); } // Writes out the specified value. public virtual void WriteValue(bool value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(DateTime value) { WriteString(XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind)); } // Writes out the specified value. public virtual void WriteValue(DateTimeOffset value) { // Under Win8P, WriteValue(DateTime) will invoke this overload, but custom writers // might not have implemented it. This base implementation should call WriteValue(DateTime). // The following conversion results in the same string as calling ToString with DateTimeOffset. if (value.Offset != TimeSpan.Zero) { WriteValue(value.LocalDateTime); } else { WriteValue(value.UtcDateTime); } } // Writes out the specified value. public virtual void WriteValue(double value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(float value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(decimal value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(int value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(long value) { WriteString(XmlConvert.ToString(value)); } // XmlReader Helper Methods // Writes out all the attributes found at the current position in the specified XmlReader. public virtual void WriteAttributes(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException(nameof(reader)); } if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration) { if (reader.MoveToFirstAttribute()) { WriteAttributes(reader, defattr); reader.MoveToElement(); } } else if (reader.NodeType != XmlNodeType.Attribute) { throw new XmlException(SR.Xml_InvalidPosition, string.Empty); } else { do { // we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault. // If either of these is true and defattr=false, we should not write the attribute out if (defattr || !reader.IsDefaultInternal) { WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI); while (reader.ReadAttributeValue()) { if (reader.NodeType == XmlNodeType.EntityReference) { WriteEntityRef(reader.Name); } else { WriteString(reader.Value); } } WriteEndAttribute(); } } while (reader.MoveToNextAttribute()); } } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. public virtual void WriteNode(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException(nameof(reader)); } bool canReadChunk = reader.CanReadValueChunk; int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth; do { switch (reader.NodeType) { case XmlNodeType.Element: WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); WriteAttributes(reader, defattr); if (reader.IsEmptyElement) { WriteEndElement(); break; } break; case XmlNodeType.Text: if (canReadChunk) { if (_writeNodeBuffer == null) { _writeNodeBuffer = new char[WriteNodeBufferSize]; } int read; while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0) { this.WriteChars(_writeNodeBuffer, 0, read); } } else { WriteString(reader.Value); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: WriteWhitespace(reader.Value); break; case XmlNodeType.CDATA: WriteCData(reader.Value); break; case XmlNodeType.EntityReference: WriteEntityRef(reader.Name); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: WriteProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.DocumentType: WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value); break; case XmlNodeType.Comment: WriteComment(reader.Value); break; case XmlNodeType.EndElement: WriteFullEndElement(); break; } } while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement))); } // Copies the current node from the given XPathNavigator to the writer (including child nodes). public virtual void WriteNode(XPathNavigator navigator, bool defattr) { if (navigator == null) { throw new ArgumentNullException(nameof(navigator)); } int iLevel = 0; navigator = navigator.Clone(); while (true) { bool mayHaveChildren = false; XPathNodeType nodeType = navigator.NodeType; switch (nodeType) { case XPathNodeType.Element: WriteStartElement(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI); // Copy attributes if (navigator.MoveToFirstAttribute()) { do { IXmlSchemaInfo schemaInfo = navigator.SchemaInfo; if (defattr || (schemaInfo == null || !schemaInfo.IsDefault)) { WriteStartAttribute(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI); // copy string value to writer WriteString(navigator.Value); WriteEndAttribute(); } } while (navigator.MoveToNextAttribute()); navigator.MoveToParent(); } // Copy namespaces if (navigator.MoveToFirstNamespace(XPathNamespaceScope.Local)) { WriteLocalNamespaces(navigator); navigator.MoveToParent(); } mayHaveChildren = true; break; case XPathNodeType.Attribute: // do nothing on root level attribute break; case XPathNodeType.Text: WriteString(navigator.Value); break; case XPathNodeType.SignificantWhitespace: case XPathNodeType.Whitespace: WriteWhitespace(navigator.Value); break; case XPathNodeType.Root: mayHaveChildren = true; break; case XPathNodeType.Comment: WriteComment(navigator.Value); break; case XPathNodeType.ProcessingInstruction: WriteProcessingInstruction(navigator.LocalName, navigator.Value); break; case XPathNodeType.Namespace: // do nothing on root level namespace break; default: Debug.Assert(false); break; } if (mayHaveChildren) { // If children exist, move down to next level if (navigator.MoveToFirstChild()) { iLevel++; continue; } else { // EndElement if (navigator.NodeType == XPathNodeType.Element) { if (navigator.IsEmptyElement) { WriteEndElement(); } else { WriteFullEndElement(); } } } } // No children while (true) { if (iLevel == 0) { // The entire subtree has been copied return; } if (navigator.MoveToNext()) { // Found a sibling, so break to outer loop break; } // No siblings, so move up to previous level iLevel--; navigator.MoveToParent(); // EndElement if (navigator.NodeType == XPathNodeType.Element) WriteFullEndElement(); } } } // Element Helper Methods // Writes out an element with the specified name containing the specified string value. public void WriteElementString(string localName, String value) { WriteElementString(localName, null, value); } // Writes out an attribute with the specified name, namespace URI and string value. public void WriteElementString(string localName, String ns, String value) { WriteStartElement(localName, ns); if (null != value && 0 != value.Length) { WriteString(value); } WriteEndElement(); } // Writes out an attribute with the specified name, namespace URI, and string value. public void WriteElementString(string prefix, String localName, String ns, String value) { WriteStartElement(prefix, localName, ns); if (null != value && 0 != value.Length) { WriteString(value); } WriteEndElement(); } public void Dispose() { Dispose(true); } // Dispose the underline stream objects (calls Close on the XmlWriter) protected virtual void Dispose(bool disposing) { if (disposing && WriteState != WriteState.Closed) { Close(); } } // Copy local namespaces on the navigator's current node to the raw writer. The namespaces are returned by the navigator in reversed order. // The recursive call reverses them back. private void WriteLocalNamespaces(XPathNavigator nsNav) { string prefix = nsNav.LocalName; string ns = nsNav.Value; if (nsNav.MoveToNextNamespace(XPathNamespaceScope.Local)) { WriteLocalNamespaces(nsNav); } if (prefix.Length == 0) { WriteAttributeString(string.Empty, "xmlns", XmlReservedNs.NsXmlNs, ns); } else { WriteAttributeString("xmlns", prefix, XmlReservedNs.NsXmlNs, ns); } } // // Static methods for creating writers // // Creates an XmlWriter for writing into the provided file. public static XmlWriter Create(string outputFileName) { return Create(outputFileName, null); } // Creates an XmlWriter for writing into the provided file with the specified settings. public static XmlWriter Create(string outputFileName, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } return settings.CreateWriter(outputFileName); } // Creates an XmlWriter for writing into the provided stream. public static XmlWriter Create(Stream output) { return Create(output, null); } // Creates an XmlWriter for writing into the provided stream with the specified settings. public static XmlWriter Create(Stream output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } return settings.CreateWriter(output); } // Creates an XmlWriter for writing into the provided TextWriter. public static XmlWriter Create(TextWriter output) { return Create(output, null); } // Creates an XmlWriter for writing into the provided TextWriter with the specified settings. public static XmlWriter Create(TextWriter output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } return settings.CreateWriter(output); } // Creates an XmlWriter for writing into the provided StringBuilder. public static XmlWriter Create(StringBuilder output) { return Create(output, null); } // Creates an XmlWriter for writing into the provided StringBuilder with the specified settings. public static XmlWriter Create(StringBuilder output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } if (output == null) { throw new ArgumentNullException(nameof(output)); } return settings.CreateWriter(new StringWriter(output, CultureInfo.InvariantCulture)); } // Creates an XmlWriter wrapped around the provided XmlWriter with the default settings. public static XmlWriter Create(XmlWriter output) { return Create(output, null); } // Creates an XmlWriter wrapped around the provided XmlWriter with the specified settings. public static XmlWriter Create(XmlWriter output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } return settings.CreateWriter(output); } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * 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.Text; using System.IO; using System.Xml; using System.Xml.Xsl; using System.Collections.Generic; using System.Management.Automation; using Trisoft.ISHRemote.Objects; using Trisoft.ISHRemote.Objects.Public; using Trisoft.ISHRemote.Exceptions; using Trisoft.ISHRemote.HelperClasses; namespace Trisoft.ISHRemote.Cmdlets.FileProcessor { /// <summary> /// <para type="synopsis">The New-IshDitaGeneralizedXml cmdlet generalizes all incoming files. Both the specialized input xml file and resulting generalized xml output file are validated.</para> /// <para type="description">The New-IshDitaGeneralizedXml cmdlet generalizes all incoming files. Both the specialized input xml file and resulting generalized xml output file are validated. Note that a DOCTYPE needs to be present in the input xml file and resulting generalized xml output file are validated.</para> /// </summary> /// <example> /// <code> /// # This sample script will process all DITA xml files in the input folder and will generalize all DITA files either to Topic or Map. /// # Note that ditabase and ditaval are not supported. /// # Note that the xmls in the input folder needs to have a DOCTYPE. /// /// # Input folder with the specialized xmls to generalize. /// $inputfolder = "Data-GeneralizeDitaXml\InputFiles" /// # Output folder with the generalize xmls. /// $outputfolder = "Data-GeneralizeDitaXml\OutputFiles" /// /// # Location of the catalog xml that contains the specialized dtds /// $specializedCatalogLocation = "Samples\Data-GeneralizeDitaXml\SpecializedDTDs\catalog-alldita12dtds.xml" /// # Location of the catalog xml that contains the "base" dtds /// $generalizedCatalogLocation = "Samples\Data-GeneralizeDitaXml\GeneralizedDTDs\catalog-dita12topic&amp;maponly.xml"; /// # File that contains a mapping between the specialized dtd and the according generalized dtd. /// $generalizationCatalogMappingLocation = "Samples\Data-GeneralizeDitaXml\generalization-catalog-mapping.xml" /// # If you would have specialized attributes from the DITA 1.2 "props" attribute, specify those attributes here to generalize them to the "props" attribute again. Here just using modelyear, market, vehicle as an example /// $attributesToGeneralizeToProps = @("modelA", "modelB", "modelC") /// # If you would have specialized attributes from the DITA 1.2 "base" attribute, specify those attributes here to generalize them to the "base" attribute again. Here just using basea, baseb, basec as an example /// $attributesToGeneralizeToBase = @("basea", "baseb", "basec") /// /// # Read all the xml files to process and generalize all the files in the outputfolder /// Get-ChildItem $inputfolder -Include *.xml -Recurse | /// New-IshDitaGeneralizedXml -SpecializedCatalogFilePath $SpecializedCatalogFilePath ` /// -GeneralizedCatalogFilePath $GeneralizedCatalogFilePath ` /// -GeneralizationCatalogMappingFilePath $GeneralizationCatalogMappingFilePath ` /// -AttributesToGeneralizeToProps $attributesToGeneralizeToProps ` /// -AttributesToGeneralizeToBase $attributesToGeneralizeToBase ` /// -FolderPath $outputfolder /// </code> /// <para>Generalize all DITA xml files in a certain directory</para> /// </example> /// <example> /// <code> /// $someLearningAssessmentFilePath = "Samples\InputFiles\Learning\LearningAssessment.xml" /// $outputfolder = "C:\temp\" /// $specializedCatalogLocation = "Samples\SpecializedDTDs\catalog-dita-1.2.xml" /// $generalizedCatalogLocation = "Samples\GeneralizedDTDs\catalog-dita-1.1.xml" /// $generalizationCatalogMappingLocation = "Samples\generalization-catalog-mapping.xml"; /// $attributesToGeneralizeToProps = @("complexity", "visibility") # array containing 2 elements /// $attributesToGeneralizeToBase = @(); # @() = empty array /// /// New-IshDitaGeneralizedXml -SpecializedCatalogFilePath $SpecializedCatalogFilePath ` /// -GeneralizedCatalogFilePath $GeneralizedCatalogFilePath ` /// -GeneralizationCatalogMappingFilePath $GeneralizationCatalogMappingFilePath ` /// -AttributesToGeneralizeToProps $attributesToGeneralizeToProps ` /// -AttributesToGeneralizeToBase $attributesToGeneralizeToBase /// -FilePath $someLearningAssessmentFilePath ` /// -FolderPath $outputfolder /// </code> /// <para>Generalize one DITA xml file</para> /// </example> [Cmdlet(VerbsCommon.New, "IshDitaGeneralizedXml", SupportsShouldProcess = false)] [OutputType(typeof(FileInfo))] public sealed class NewIshDitaGeneralizedXml : FileProcessorCmdlet { /// <summary> /// <para type="description">The filepath of the catalog with the specialized DTDs. Best is to make a separate folders with all the specialized DTD files together + a catalog with relative locations to the specialized DTD files.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false)] [ValidateNotNullOrEmpty] public string SpecializedCatalogFilePath { get; set; } /// <summary> /// <para type="description">The filepath of the catalog with the generalized/standard DTDs. Best is to make a separate folders with all the generalized DTD files together + a catalog with relative locations to the generalized DTD files.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false)] [ValidateNotNullOrEmpty] public string GeneralizedCatalogFilePath { get; set; } /// <summary> /// <para type="description">The location of a generalization mapping file. This mapping file defines the relation between the specialized dtd rootelements/public ids and the corresponding generalized dtd rootelements/public ids. It is of the following form: /// &lt;generalizationcataloglookup> /// &lt;match rootelement="learningSummary" dtdpublicid="-//OASIS//DTD DITA Learning Summary//EN" generalizedrootelement="topic" generalizeddtdpublicid="-//OASIS//DTD DITA Topic//EN" generalizeddtdsystemid="dita-oasis/1.1/topic.dtd" /> /// &lt;match rootelement="learningContent" generalizedrootelement="topic" generalizeddtdpublicid="-//OASIS//DTD DITA Topic//EN" generalizeddtdsystemid="dita-oasis/1.1/topic.dtd" /> /// ... /// &lt;/generalizationcataloglookup> The rootelement, dtdpublicid or dtdsystemid attributes are used to match the specialized xml rootelement or dtd, while the generalizedrootelement, generalizeddtdpublicid or generalizeddtdsystemid are used to specify the corresponding generalized rootelement/dtd. Note that: /// 1) At least one of the specialized attributes is required /// 2) The generalizedrootelement is required /// 3) Either the generalizeddtdpublicid or generalizeddtdsystemid is required</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false)] [ValidateNotNullOrEmpty] public string GeneralizationCatalogMappingFilePath { get; set; } /// <summary> /// <para type="description">Array of attributes that are specialized from the DITA "props" attribute (and need to be generalized to it).</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false)] public string[] AttributesToGeneralizeToProps { get; set; } /// <summary> /// <para type="description">Array of attributes that are specialized from the DITA "base" attribute (and need to be generalized to it).</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false)] public string[] AttributesToGeneralizeToBase { get; set; } /// <summary> /// <para type="description">FilePath can be used to specify one or more specialized input xml file locations.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public string[] FilePath { get; set; } /// <summary> /// <para type="description">Folder on the Windows filesystem where to store the new data files</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = false)] [ValidateNotNullOrEmpty] public string FolderPath { get; set; } #region Private fields /// <summary> /// Single conversion object /// </summary> private DitaXmlGeneralization _ditaXMLGeneralization = null; /// <summary> /// Collection of the files to process /// </summary> private readonly List<FileInfo> _files = new List<FileInfo>(); #endregion protected override void BeginProcessing() { //Validate all incoming catalogs once WriteDebug("Loading SpecializedCatalogFilePath[${SpecializedCatalogFilePath}]"); XmlResolverUsingCatalog specializedXmlResolver = new XmlResolverUsingCatalog(SpecializedCatalogFilePath); WriteDebug("Loading GeneralizedCatalogFilePath[${GeneralizedCatalogFilePath}]"); XmlResolverUsingCatalog generalizedXmlResolver = new XmlResolverUsingCatalog(GeneralizedCatalogFilePath); WriteDebug("Loading GeneralizationCatalogMappingFilePath[${GeneralizationCatalogMappingFilePath}]"); DitaXmlGeneralizationCatalogMapping generalizationCatalogMapping = new DitaXmlGeneralizationCatalogMapping(GeneralizationCatalogMappingFilePath); _ditaXMLGeneralization = new HelperClasses.DitaXmlGeneralization(specializedXmlResolver, generalizedXmlResolver, generalizationCatalogMapping); if (AttributesToGeneralizeToProps != null) { WriteDebug("Loading AttributesToGeneralizeToProps[" + String.Join(",", AttributesToGeneralizeToProps) + "]"); _ditaXMLGeneralization.AttributesToGeneralizeToProps = AttributesToGeneralizeToProps; } if (AttributesToGeneralizeToBase != null) { WriteDebug("Loading AttributesToGeneralizeToBase[" + String.Join(",", AttributesToGeneralizeToBase) + "]"); _ditaXMLGeneralization.AttributesToGeneralizeToBase = AttributesToGeneralizeToBase; } if (!Directory.Exists(FolderPath)) { WriteDebug("Creating FolderPath[${FolderPath}]"); string tempLocation = Directory.CreateDirectory(FolderPath).FullName; } base.BeginProcessing(); } /// <summary> /// Process the cmdlet. /// </summary> protected override void ProcessRecord() { try { foreach (string filePath in FilePath) { _files.Add(new FileInfo(filePath)); } } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } protected override void EndProcessing() { try { int current = 0; WriteDebug("Generalizing _files.Count[" + _files.Count + "]"); foreach (FileInfo inputFile in _files) { // Could be nicer, but currently loosing inputFile relative files and dropping all in OutputFolder FileInfo outputFile = new FileInfo(Path.Combine(FolderPath, inputFile.Name)); try { WriteDebug("Generalizing inputFile[" + inputFile.FullName + "] to outputFile[" + outputFile.FullName + "]"); WriteParentProgress("Generalizing inputFile["+inputFile.FullName+"] to outputFile["+ outputFile.FullName +"]", ++current, FilePath.Length); _ditaXMLGeneralization.Generalize(inputFile, outputFile); WriteObject(outputFile); } catch (Exception ex) { WriteWarning("Generalizing inputFile[" + inputFile.FullName + "] to outputFile[" + outputFile.FullName + "] failed: " + ex.Message); } } } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Seguetech.Zippy.Areas.HelpPage.ModelDescriptions; using Seguetech.Zippy.Areas.HelpPage.Models; #pragma warning disable 1591 namespace Seguetech.Zippy.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { private class MoveTypeEditor : Editor { public MoveTypeEditor( TService service, State state, string fileName, CancellationToken cancellationToken) : base(service, state, fileName, cancellationToken) { } /// <summary> /// Given a document and a type contained in it, moves the type /// out to its own document. The new document's name typically /// is the type name, or is atleast based on the type name. /// </summary> /// <remarks> /// The algorithm for this, is as follows: /// 1. Fork the original document that contains the type to be moved. /// 2. Keep the type, required namespace containers and using statements. /// remove everything else from the forked document. /// 3. Add this forked document to the solution. /// 4. Finally, update the original document and remove the type from it. /// </remarks> internal override async Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() { var solution = SemanticDocument.Document.Project.Solution; // Fork, update and add as new document. var projectToBeUpdated = SemanticDocument.Document.Project; var newDocumentId = DocumentId.CreateNewId(projectToBeUpdated.Id, FileName); var documentWithMovedType = await AddNewDocumentWithSingleTypeDeclarationAndImportsAsync(newDocumentId).ConfigureAwait(false); var solutionWithNewDocument = documentWithMovedType.Project.Solution; // Get the original source document again, from the latest forked solution. var sourceDocument = solutionWithNewDocument.GetDocument(SemanticDocument.Document.Id); // update source document to add partial modifiers to type chain // and/or remove type declaration from original source document. var solutionWithBothDocumentsUpdated = await RemoveTypeFromSourceDocumentAsync( sourceDocument, documentWithMovedType).ConfigureAwait(false); return ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(solutionWithBothDocumentsUpdated)); } /// <summary> /// Forks the source document, keeps required type, namespace containers /// and adds it the solution. /// </summary> /// <param name="newDocumentId">id for the new document to be added</param> /// <returns>the new solution which contains a new document with the type being moved</returns> private async Task<Document> AddNewDocumentWithSingleTypeDeclarationAndImportsAsync( DocumentId newDocumentId) { var document = SemanticDocument.Document; Debug.Assert(document.Name != FileName, $"New document name is same as old document name:{FileName}"); var root = SemanticDocument.Root; var projectToBeUpdated = document.Project; var documentEditor = await DocumentEditor.CreateAsync(document, CancellationToken).ConfigureAwait(false); // Make the type chain above this new type partial. Also, remove any // attributes from the containing partial types. We don't want to create // duplicate attributes on things. AddPartialModifiersToTypeChain(documentEditor, removeAttributesAndComments: true); // remove things that are not being moved, from the forked document. var membersToRemove = GetMembersToRemove(root); foreach (var member in membersToRemove) { documentEditor.RemoveNode(member, SyntaxRemoveOptions.KeepNoTrivia); } var modifiedRoot = documentEditor.GetChangedRoot(); // add an empty document to solution, so that we'll have options from the right context. var solutionWithNewDocument = projectToBeUpdated.Solution.AddDocument( newDocumentId, FileName, text: string.Empty, folders: document.Folders); // update the text for the new document solutionWithNewDocument = solutionWithNewDocument.WithDocumentSyntaxRoot(newDocumentId, modifiedRoot, PreservationMode.PreserveIdentity); // get the updated document, give it the minimal set of imports that the type // inside it needs. var service = document.GetLanguageService<IRemoveUnnecessaryImportsService>(); var newDocument = solutionWithNewDocument.GetDocument(newDocumentId); newDocument = await service.RemoveUnnecessaryImportsAsync(newDocument, CancellationToken).ConfigureAwait(false); return newDocument; } /// <summary> /// update the original document and remove the type that was moved. /// perform other fix ups as necessary. /// </summary> /// <returns>an updated solution with the original document fixed up as appropriate.</returns> private async Task<Solution> RemoveTypeFromSourceDocumentAsync( Document sourceDocument, Document documentWithMovedType) { var documentEditor = await DocumentEditor.CreateAsync(sourceDocument, CancellationToken).ConfigureAwait(false); // Make the type chain above the type we're moving 'partial'. // However, keep all the attributes on these types as theses are the // original attributes and we don't want to mess with them. AddPartialModifiersToTypeChain(documentEditor, removeAttributesAndComments: false); documentEditor.RemoveNode(State.TypeNode, SyntaxRemoveOptions.KeepNoTrivia); var updatedDocument = documentEditor.GetChangedDocument(); // Now, remove any imports that we no longer need *if* they were used in the new // file with the moved type. Essentially, those imports were here just to serve // that new type and we shoudl remove them. If we have *other* imports that that // other file does not use *and* we do not use, we'll still keep those around. // Those may be important to the user for code they're about to write, and we // don't want to interfere with them by removing them. var service = sourceDocument.GetLanguageService<IRemoveUnnecessaryImportsService>(); var syntaxFacts = sourceDocument.GetLanguageService<ISyntaxFactsService>(); var rootWithMovedType = await documentWithMovedType.GetSyntaxRootAsync(CancellationToken).ConfigureAwait(false); var movedImports = rootWithMovedType.DescendantNodes() .Where(syntaxFacts.IsUsingOrExternOrImport) .ToImmutableArray(); Func<SyntaxNode, bool> predicate = n => movedImports.Contains(i => i.IsEquivalentTo(n)); updatedDocument = await service.RemoveUnnecessaryImportsAsync( updatedDocument, predicate, CancellationToken).ConfigureAwait(false); return updatedDocument.Project.Solution; } /// <summary> /// Traverses the syntax tree of the forked document and /// collects a list of nodes that are not being moved. /// This list of nodes are then removed from the forked copy. /// </summary> /// <param name="root">root, of the syntax tree of forked document</param> /// <returns>list of syntax nodes, to be removed from the forked copy.</returns> private ISet<SyntaxNode> GetMembersToRemove(SyntaxNode root) { var spine = new HashSet<SyntaxNode>(); // collect the parent chain of declarations to keep. spine.AddRange(State.TypeNode.GetAncestors()); // get potential namespace, types and members to remove. var removableCandidates = root .DescendantNodes(n => spine.Contains(n)) .Where(n => FilterToTopLevelMembers(n, State.TypeNode)).ToSet(); // diff candidates with items we want to keep. removableCandidates.ExceptWith(spine); #if DEBUG // None of the nodes we're removing should also have any of their parent // nodes removed. If that happened we could get a crash by first trying to remove // the parent, then trying to remove the child. foreach (var node in removableCandidates) { foreach (var ancestor in node.GetAncestors()) { Debug.Assert(!removableCandidates.Contains(ancestor)); } } #endif return removableCandidates; } private static bool FilterToTopLevelMembers(SyntaxNode node, SyntaxNode typeNode) { // We never filter out the actual node we're trying to keep around. if (node == typeNode) { return false; } return node is TTypeDeclarationSyntax || node is TMemberDeclarationSyntax || node is TNamespaceDeclarationSyntax; } /// <summary> /// if a nested type is being moved, this ensures its containing type is partial. /// </summary> private void AddPartialModifiersToTypeChain( DocumentEditor documentEditor, bool removeAttributesAndComments) { var semanticFacts = State.SemanticDocument.Document.GetLanguageService<ISemanticFactsService>(); var typeChain = State.TypeNode.Ancestors().OfType<TTypeDeclarationSyntax>(); foreach (var node in typeChain) { var symbol = (ITypeSymbol)State.SemanticDocument.SemanticModel.GetDeclaredSymbol(node, CancellationToken); if (!semanticFacts.IsPartial(symbol, CancellationToken)) { documentEditor.SetModifiers(node, documentEditor.Generator.GetModifiers(node) | DeclarationModifiers.Partial); } if (removeAttributesAndComments) { documentEditor.RemoveAllAttributes(node); documentEditor.RemoveAllComments(node); } } documentEditor.ReplaceNode(State.TypeNode, (currentNode, generator) => { var currentTypeNode = (TTypeDeclarationSyntax)currentNode; // Trim leading whitespace from the type so we don't have excessive // leading blank lines. return RemoveLeadingWhitespace(currentTypeNode); }); } private TTypeDeclarationSyntax RemoveLeadingWhitespace( TTypeDeclarationSyntax currentTypeNode) { var syntaxFacts = State.SemanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); var leadingTrivia = currentTypeNode.GetLeadingTrivia(); var afterWhitespace = leadingTrivia.SkipWhile( t => syntaxFacts.IsWhitespaceTrivia(t) || syntaxFacts.IsEndOfLineTrivia(t)); var withoutLeadingWhitespace = currentTypeNode.WithLeadingTrivia(afterWhitespace); return withoutLeadingWhitespace.ReplaceToken( withoutLeadingWhitespace.GetFirstToken(), withoutLeadingWhitespace.GetFirstToken().WithAdditionalAnnotations(Formatter.Annotation)); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SampleWebApi.Inheritance.WebApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Author: Robert Scheller, Melissa Lucash using Landis.Core; using Landis.SpatialModeling; using Landis.Utilities; using Landis.Library.Succession; using Landis.Library.Parameters; using System.Collections.Generic; using System.Diagnostics; namespace Landis.Extension.Succession.NECN { /// <summary> /// The parameters for biomass succession. /// </summary> public class InputParameters : IInputParameters { private int timestep; private SeedingAlgorithms seedAlg; private string climateConfigFile; private string initCommunities; private string communitiesMap; private string soilDepthMapName; private string soilDrainMapName; private string soilBaseFlowMapName; private string soilStormFlowMapName; private string soilFieldCapacityMapName; private string soilWiltingPointMapName; private string soilPercentSandMapName; private string soilPercentClayMapName; private string initialSOM1CSurfaceMapName; private string initialSOM1NSurfaceMapName; private string initialSOM1CSoilMapName; private string initialSOM1NSoilMapName; private string initialSOM2CMapName; private string initialSOM2NMapName; private string initialSOM3CMapName; private string initialSOM3NMapName; private string initialDeadSurfaceMapName; private string initialDeadSoilMapName; private bool calibrateMode; private bool smokeModelOutputs; private bool henne_watermode; private WaterType wtype; private double probEstablishAdjust; private double atmosNslope; private double atmosNintercept; private double latitude; private double denitrif; private double decayRateSurf; private double decayRateSOM1; private double decayRateSOM2; private double decayRateSOM3; private double[] maximumShadeLAI; private double initMineralN; private double initFineFuels; private ISpeciesDataset speciesDataset; private FunctionalTypeTable functionalTypes; private FireReductions[] fireReductionsTable; private List<HarvestReductions> harvestReductionsTable; private Landis.Library.Parameters.Species.AuxParm<int> sppFunctionalType; private Landis.Library.Parameters.Species.AuxParm<bool> nFixer; private Landis.Library.Parameters.Species.AuxParm<int> gddMin; private Landis.Library.Parameters.Species.AuxParm<int> gddMax; private Landis.Library.Parameters.Species.AuxParm<int> minJanTemp; private Landis.Library.Parameters.Species.AuxParm<double> maxDrought; private Landis.Library.Parameters.Species.AuxParm<double> leafLongevity; private Landis.Library.Parameters.Species.AuxParm<bool> epicormic; private Landis.Library.Parameters.Species.AuxParm<double> leafLignin; private Landis.Library.Parameters.Species.AuxParm<double> woodLignin; private Landis.Library.Parameters.Species.AuxParm<double> coarseRootLignin; private Landis.Library.Parameters.Species.AuxParm<double> fineRootLignin; private Landis.Library.Parameters.Species.AuxParm<double> leafCN; private Landis.Library.Parameters.Species.AuxParm<double> woodCN; private Landis.Library.Parameters.Species.AuxParm<double> coarseRootCN; private Landis.Library.Parameters.Species.AuxParm<double> foliageLitterCN; private Landis.Library.Parameters.Species.AuxParm<double> fineRootCN; private Landis.Library.Parameters.Species.AuxParm<int> maxANPP; private Landis.Library.Parameters.Species.AuxParm<int> maxBiomass; private List<ISufficientLight> sufficientLight; private Landis.Library.Parameters.Species.AuxParm<bool> grass; private double grassThresholdMultiplier; // W.Hotta 2020.07.07 public double GrassThresholdMultiplier { get { return grassThresholdMultiplier; } } //--------------------------------------------------------------------- /// <summary> /// Timestep (years) /// </summary> public int Timestep { get { return timestep; } set { if (value < 0) throw new InputValueException(value.ToString(), "Timestep must be > or = 0"); timestep = value; } } //--------------------------------------------------------------------- /// <summary> /// Seeding algorithm /// </summary> public SeedingAlgorithms SeedAlgorithm { get { return seedAlg; } set { seedAlg = value; } } //--------------------------------------------------------------------- /// <summary> /// Path to the file with the initial communities' definitions. /// </summary> public string InitialCommunities { get { return initCommunities; } set { if (value != null) { ValidatePath(value); } initCommunities = value; } } //--------------------------------------------------------------------- /// <summary> /// Path to the raster file showing where the initial communities are. /// </summary> public string InitialCommunitiesMap { get { return communitiesMap; } set { if (value != null) { ValidatePath(value); } communitiesMap = value; } } //--------------------------------------------------------------------- public string ClimateConfigFile { get { return climateConfigFile; } set { climateConfigFile = value; } } //--------------------------------------------------------------------- /// <summary> /// Determines whether months are simulated 0 - 12 (calibration mode) or /// 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5 (normal mode with disturbance at June 30). /// </summary> public bool CalibrateMode { get { return calibrateMode; } set { calibrateMode = value; } } //--------------------------------------------------------------------- /// <summary> /// </summary> public bool SoilWater_Henne { get { return henne_watermode; } set { henne_watermode = value; } } //--------------------------------------------------------------------- /// <summary> /// </summary> public bool SmokeModelOutputs { get { return smokeModelOutputs; } set { smokeModelOutputs = value; } } //--------------------------------------------------------------------- /// <summary> /// Determines whether moisture effects on decomposition follow a linear or ratio calculation. /// </summary> public WaterType WType { get { return wtype; } set { wtype = value; } } //--------------------------------------------------------------------- /// <summary> /// Adjust probability of establishment due to variable time step. A multiplier. /// </summary> public double ProbEstablishAdjustment { get { return probEstablishAdjust; } set { if (value < 0.0 || value > 1.0) throw new InputValueException(value.ToString(), "Probability of adjustment factor must be > 0.0 and < 1"); probEstablishAdjust = value; } } //--------------------------------------------------------------------- public double AtmosNslope { get { return atmosNslope; } } //--------------------------------------------------------------------- public double AtmosNintercept { get { return atmosNintercept; } } //--------------------------------------------------------------------- /// <summary> /// Functional type parameters. /// </summary> public FunctionalTypeTable FunctionalTypes { get { return functionalTypes; } set { functionalTypes = value; } } //--------------------------------------------------------------------- /// <summary> /// Fire reduction of leaf and wood litter parameters. /// </summary> public FireReductions[] FireReductionsTable { get { return fireReductionsTable; } set { fireReductionsTable = value; } } //--------------------------------------------------------------------- /// <summary> /// Harvest reduction of leaf and wood litter parameters. /// </summary> public List<HarvestReductions> HarvestReductionsTable { get { return harvestReductionsTable; } set { harvestReductionsTable = value; } } //--------------------------------------------------------------------- public double[] MaximumShadeLAI { get { return maximumShadeLAI; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<int> SppFunctionalType {get {return sppFunctionalType;}} public Landis.Library.Parameters.Species.AuxParm<bool> NFixer { get {return nFixer;}} public Landis.Library.Parameters.Species.AuxParm<bool> Grass { get { return grass; } } public Landis.Library.Parameters.Species.AuxParm<int> GDDmin { get { return gddMin; }} public Landis.Library.Parameters.Species.AuxParm<int> GDDmax { get { return gddMax; }} public Landis.Library.Parameters.Species.AuxParm<int> MinJanTemp { get { return minJanTemp; }} public Landis.Library.Parameters.Species.AuxParm<double> MaxDrought { get { return maxDrought; }} public Landis.Library.Parameters.Species.AuxParm<double> LeafLongevity {get {return leafLongevity;}} //--------------------------------------------------------------------- /// <summary> /// Can the species resprout epicormically following a fire? /// </summary> public Landis.Library.Parameters.Species.AuxParm<bool> Epicormic { get { return epicormic; } set { epicormic = value; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<double> LeafLignin { get { return leafLignin; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<double> WoodLignin { get { return woodLignin; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<double> CoarseRootLignin { get { return coarseRootLignin; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<double> FineRootLignin { get { return fineRootLignin; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<double> LeafCN { get { return leafCN; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<double> WoodCN { get { return woodCN; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<double> CoarseRootCN { get { return coarseRootCN; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<double> FoliageLitterCN { get { return foliageLitterCN; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<double> FineRootCN { get { return fineRootCN; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<int> MaxANPP { get { return maxANPP; } } //--------------------------------------------------------------------- public Landis.Library.Parameters.Species.AuxParm<int> MaxBiomass { get { return maxBiomass; } } //--------------------------------------------------------------------- /// <summary> /// Definitions of sufficient light probabilities. /// </summary> public List<ISufficientLight> LightClassProbabilities { get { return sufficientLight; } set { Debug.Assert(sufficientLight.Count != 0); sufficientLight = value; } } //--------------------------------------------------------------------- public double Latitude { get { return latitude; } } //----------------------------------------------- public double DecayRateSurf { get { return decayRateSurf; } } //----------------------------------------------- public double DecayRateSOM1 { get { return decayRateSOM1; } }//--------------------------------------------------------------------- public double DecayRateSOM2 { get { return decayRateSOM2; } } //--------------------------------------------------------------------- public double DecayRateSOM3 { get { return decayRateSOM3; } } //----------------------------------------------- public double DenitrificationRate { get { return denitrif; } } public double InitialMineralN { get { return initMineralN; } } public double InitialFineFuels { get { return initFineFuels; } } //--------------------------------------------------------------------- //public string AgeOnlyDisturbanceParms //{ // get { // return ageOnlyDisturbanceParms; // } // set { // string path = value; // if (path.Trim(null).Length == 0) // throw new InputValueException(path,"\"{0}\" is not a valid path.",path); // ageOnlyDisturbanceParms = value; // } //} //--------------------------------------------------------------------- public string SoilDepthMapName { get { return soilDepthMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); soilDepthMapName = value; } } //--------------------------------------------------------------------- public string SoilDrainMapName { get { return soilDrainMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); soilDrainMapName = value; } } //--------------------------------------------------------------------- public string SoilBaseFlowMapName { get { return soilBaseFlowMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); soilBaseFlowMapName = value; } } //--------------------------------------------------------------------- public string SoilStormFlowMapName { get { return soilStormFlowMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); soilStormFlowMapName = value; } } //--------------------------------------------------------------------- public string SoilFieldCapacityMapName { get { return soilFieldCapacityMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); soilFieldCapacityMapName = value; } } //--------------------------------------------------------------------- public string SoilWiltingPointMapName { get { return soilWiltingPointMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); soilWiltingPointMapName = value; } } //--------------------------------------------------------------------- public string SoilPercentSandMapName { get { return soilPercentSandMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); soilPercentSandMapName = value; } } //--------------------------------------------------------------------- public string SoilPercentClayMapName { get { return soilPercentClayMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); soilPercentClayMapName = value; } } //--------------------------------------------------------------------- public string InitialSOM1CSurfaceMapName { get { return initialSOM1CSurfaceMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); initialSOM1CSurfaceMapName = value; } } //--------------------------------------------------------------------- public string InitialSOM1NSurfaceMapName { get { return initialSOM1NSurfaceMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); initialSOM1NSurfaceMapName = value; } } //--------------------------------------------------------------------- public string InitialSOM1CSoilMapName { get { return initialSOM1CSoilMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); initialSOM1CSoilMapName = value; } } //--------------------------------------------------------------------- public string InitialSOM1NSoilMapName { get { return initialSOM1NSoilMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); initialSOM1NSoilMapName = value; } } //--------------------------------------------------------------------- public string InitialSOM2CMapName { get { return initialSOM2CMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); initialSOM2CMapName = value; } } //--------------------------------------------------------------------- public string InitialSOM2NMapName { get { return initialSOM2NMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); initialSOM2NMapName = value; } } //--------------------------------------------------------------------- public string InitialSOM3CMapName { get { return initialSOM3CMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); initialSOM3CMapName = value; } } //--------------------------------------------------------------------- public string InitialSOM3NMapName { get { return initialSOM3NMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); initialSOM3NMapName = value; } } //--------------------------------------------------------------------- public string InitialDeadSurfaceMapName { get { return initialDeadSurfaceMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); initialDeadSurfaceMapName = value; } } //--------------------------------------------------------------------- public string InitialDeadSoilMapName { get { return initialDeadSoilMapName; } set { string path = value; if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); initialDeadSoilMapName = value; } } //--------------------------------------------------------------------- public void SetMaximumShadeLAI(byte shadeClass, //IEcoregion ecoregion, InputValue<double> newValue) { Debug.Assert(1 <= shadeClass && shadeClass <= 5); //Debug.Assert(ecoregion != null); if (newValue != null) { if (newValue.Actual < 0.0 || newValue.Actual > 20) throw new InputValueException(newValue.String, "{0} is not between 0 and 20", newValue.String); } maximumShadeLAI[shadeClass] = newValue; //minRelativeBiomass[shadeClass][ecoregion] = newValue; } //--------------------------------------------------------------------- public void SetFunctionalType(ISpecies species, InputValue<int> newValue) { Debug.Assert(species != null); sppFunctionalType[species] = VerifyRange(newValue, 0, 100); } public void SetFunctionalType(ISpecies species, int newValue) { Debug.Assert(species != null); sppFunctionalType[species] = VerifyRange(newValue, 0, 100); } //--------------------------------------------------------------------- //public void SetNFixer(ISpecies species, // InputValue<int> newValue) //{ // Debug.Assert(species != null); // nTolerance[species] = CheckBiomassParm(newValue, 1, 4); //} //--------------------------------------------------------------------- public void SetGDDmin(ISpecies species, InputValue<int> newValue) { Debug.Assert(species != null); gddMin[species] = VerifyRange(newValue, 1, 4000); } public void SetGDDmin(ISpecies species,int newValue) { Debug.Assert(species != null); gddMin[species] = VerifyRange(newValue, 1, 4000); } //--------------------------------------------------------------------- public void SetGDDmax(ISpecies species, InputValue<int> newValue) { Debug.Assert(species != null); gddMax[species] = VerifyRange(newValue, 500, 7000); } public void SetGDDmax(ISpecies species,int newValue) { Debug.Assert(species != null); gddMax[species] = VerifyRange(newValue, 500, 7000); } //--------------------------------------------------------------------- public void SetMinJanTemp(ISpecies species, InputValue<int> newValue) { Debug.Assert(species != null); minJanTemp[species] = VerifyRange(newValue, -60, 20); } public void SetMinJanTemp(ISpecies species,int newValue) { Debug.Assert(species != null); minJanTemp[species] = VerifyRange(newValue, -60, 20); } //--------------------------------------------------------------------- public void SetMaxDrought(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); maxDrought[species] = VerifyRange(newValue, 0.0, 1.0); } public void SetMaxDrought(ISpecies species,double newValue) { Debug.Assert(species != null); maxDrought[species] = VerifyRange(newValue, 0.0, 1.0); } //--------------------------------------------------------------------- public void SetLeafLongevity(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); leafLongevity[species] = VerifyRange(newValue, 1.0, 10.0); } public void SetLeafLongevity(ISpecies species,double newValue) { Debug.Assert(species != null); leafLongevity[species] = VerifyRange(newValue, 1.0, 10.0); } //--------------------------------------------------------------------- public void SetLeafLignin(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); leafLignin[species] = VerifyRange(newValue, 0.0, 0.4); } public void SetLeafLignin(ISpecies species,double newValue) { Debug.Assert(species != null); leafLignin[species] = VerifyRange(newValue, 0.0, 0.4); } //--------------------------------------------------------------------- public void SetWoodLignin(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); woodLignin[species] = VerifyRange(newValue, 0.0, 0.4); } public void SetWoodLignin(ISpecies species,double newValue) { Debug.Assert(species != null); woodLignin[species] = VerifyRange(newValue, 0.0, 0.4); } //--------------------------------------------------------------------- public void SetCoarseRootLignin(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); coarseRootLignin[species] = VerifyRange(newValue, 0.0, 0.4); } public void SetCoarseRootLignin(ISpecies species,double newValue) { Debug.Assert(species != null); coarseRootLignin[species] = VerifyRange(newValue, 0.0, 0.4); } //--------------------------------------------------------------------- public void SetFineRootLignin(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); fineRootLignin[species] = VerifyRange(newValue, 0.0, 0.4); } public void SetFineRootLignin(ISpecies species,double newValue) { Debug.Assert(species != null); fineRootLignin[species] = VerifyRange(newValue, 0.0, 0.4); } //--------------------------------------------------------------------- public void SetLeafCN(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); leafCN[species] = VerifyRange(newValue, 5.0, 100.0); } public void SetLeafCN(ISpecies species,double newValue) { Debug.Assert(species != null); leafCN[species] = VerifyRange(newValue, 5.0, 100.0); } //--------------------------------------------------------------------- public void SetWoodCN(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); woodCN[species] = VerifyRange(newValue, 5.0, 900.0); } public void SetWoodCN(ISpecies species,double newValue) { Debug.Assert(species != null); woodCN[species] = VerifyRange(newValue, 5.0, 900.0); } //--------------------------------------------------------------------- public void SetCoarseRootCN(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); coarseRootCN[species] = VerifyRange(newValue, 5.0, 500.0); } public void SetCoarseRootCN(ISpecies species,double newValue) { Debug.Assert(species != null); coarseRootCN[species] = VerifyRange(newValue, 5.0, 500.0); } //--------------------------------------------------------------------- public void SetFoliageLitterCN(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); foliageLitterCN[species] = VerifyRange(newValue, 5.0, 100.0); } public void SetFoliageLitterCN(ISpecies species,double newValue) { Debug.Assert(species != null); foliageLitterCN[species] = VerifyRange(newValue, 5.0, 100.0); } //--------------------------------------------------------------------- public void SetFineRootCN(ISpecies species, InputValue<double> newValue) { Debug.Assert(species != null); fineRootCN[species] = VerifyRange(newValue, 5.0, 100.0); } public void SetFineRootCN(ISpecies species,double newValue) { Debug.Assert(species != null); fineRootCN[species] = VerifyRange(newValue, 5.0, 100.0); } //--------------------------------------------------------------------- public void SetMaxANPP(ISpecies species, InputValue<int> newValue) { Debug.Assert(species != null); maxANPP[species] = VerifyRange(newValue, 2, 1000); } public void SetMaxANPP(ISpecies species,int newValue) { Debug.Assert(species != null); maxANPP[species] = VerifyRange(newValue, 2, 1000); } //--------------------------------------------------------------------- public void SetMaxBiomass(ISpecies species, InputValue<int> newValue) { Debug.Assert(species != null); maxBiomass[species] = VerifyRange(newValue, 2, 100000); } public void SetMaxBiomass(ISpecies species, int newValue) { Debug.Assert(species != null); maxBiomass[species] = VerifyRange(newValue, 2, 100000); } //--------------------------------------------------------------------- public void SetAtmosNslope(InputValue<double> newValue) { atmosNslope = VerifyRange(newValue, -1.0, 2.0); } //--------------------------------------------------------------------- public void SetAtmosNintercept(InputValue<double> newValue) { atmosNintercept = VerifyRange(newValue, -1.0, 2.0); } //--------------------------------------------------------------------- public void SetLatitude(InputValue<double> newValue) { latitude = VerifyRange(newValue, 0.0, 50.0); } //--------------------------------------------------------------------- public void SetDecayRateSurf(InputValue<double> newValue) { decayRateSurf = VerifyRange(newValue, 0.0, 10.0); } //--------------------------------------------------------------------- public void SetDecayRateSOM1(InputValue<double> newValue) { decayRateSOM1 = VerifyRange(newValue, 0.0, 10.0); } //--------------------------------------------------------------------- public void SetDecayRateSOM2(InputValue<double> newValue) { decayRateSOM2 = VerifyRange(newValue, 0.0, 1.0); } //--------------------------------------------------------------------- public void SetDecayRateSOM3(InputValue<double> newValue) { decayRateSOM3 = VerifyRange(newValue, 0.0, 1.0); } // -------------------------------------------------------------------- // Multiplier to adjust judgement whether a tree-cohort is larger than grass layer // W.Hotta 2020.07.07 public void SetGrassThresholdMultiplier(InputValue<double> newValue) { grassThresholdMultiplier = VerifyRange(newValue, 0.0, 10.0); } //--------------------------------------------------------------------- public void SetDenitrif(InputValue<double> newValue) { denitrif = VerifyRange(newValue, 0.0, 1.0); } //--------------------------------------------------------------------- public void SetInitMineralN(InputValue<double> newValue) { initMineralN = VerifyRange(newValue, 0.0, 5000.0); } //--------------------------------------------------------------------- public void SetInitFineFuels(InputValue<double> newValue) { initFineFuels = VerifyRange(newValue, 0.0, 1.0); } //--------------------------------------------------------------------- public InputParameters(ISpeciesDataset speciesDataset, int litterCnt, int functionalCnt) { this.speciesDataset = speciesDataset; functionalTypes = new FunctionalTypeTable(functionalCnt); fireReductionsTable = new FireReductions[11]; harvestReductionsTable = new List<HarvestReductions>(); sppFunctionalType = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset); nFixer = new Landis.Library.Parameters.Species.AuxParm<bool>(speciesDataset); grass = new Landis.Library.Parameters.Species.AuxParm<bool>(speciesDataset); gddMin = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset); gddMax = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset); minJanTemp = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset); maxDrought = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); leafLongevity = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); epicormic = new Landis.Library.Parameters.Species.AuxParm<bool>(speciesDataset); leafLignin = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); woodLignin = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); coarseRootLignin = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); fineRootLignin = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); leafCN = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); woodCN = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); coarseRootCN = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); foliageLitterCN = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); fineRootCN = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset); maxANPP = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset); maxBiomass = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset); maximumShadeLAI = new double[6]; sufficientLight = new List<ISufficientLight>(); } //--------------------------------------------------------------------- public static double VerifyRange(InputValue<double> newValue, double minValue, double maxValue) { if (newValue != null) { if (newValue.Actual < minValue || newValue.Actual > maxValue) throw new InputValueException(newValue.String, "{0} is not between {1:0.0} and {2:0.0}", newValue.String, minValue, maxValue); } return newValue.Actual; } public static double VerifyRange(double newValue, double minValue, double maxValue) { if (newValue < minValue || newValue > maxValue) throw new InputValueException(newValue.ToString(), "{0} is not between {1:0.0} and {2:0.0}", newValue.ToString(), minValue, maxValue); return newValue; } //--------------------------------------------------------------------- public static int VerifyRange(InputValue<int> newValue, int minValue, int maxValue) { if (newValue != null) { if (newValue.Actual < minValue || newValue.Actual > maxValue) throw new InputValueException(newValue.String, "{0} is not between {1:0.0} and {2:0.0}", newValue.String, minValue, maxValue); } return newValue.Actual; } public static int VerifyRange(int newValue, int minValue, int maxValue) { if (newValue < minValue || newValue > maxValue) throw new InputValueException(newValue.ToString(), "{0} is not between {1:0.0} and {2:0.0}", newValue.ToString(), minValue, maxValue); return newValue; } //--------------------------------------------------------------------- private void ValidatePath(string path) { if (string.IsNullOrEmpty(path)) throw new InputValueException(); if (path.Trim(null).Length == 0) throw new InputValueException(path, "\"{0}\" is not a valid path.", path); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Security; using System.Net.Sockets; using System.Runtime.ExceptionServices; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.WebSockets { internal sealed class WebSocketHandle { /// <summary>Per-thread cached StringBuilder for building of strings to send on the connection.</summary> [ThreadStatic] private static StringBuilder t_cachedStringBuilder; /// <summary>Default encoding for HTTP requests. Latin alphabet no 1, ISO/IEC 8859-1.</summary> private static readonly Encoding s_defaultHttpEncoding = Encoding.GetEncoding(28591); /// <summary>Size of the receive buffer to use.</summary> private const int DefaultReceiveBufferSize = 0x1000; /// <summary>GUID appended by the server as part of the security key response. Defined in the RFC.</summary> private const string WSServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private readonly CancellationTokenSource _abortSource = new CancellationTokenSource(); private WebSocketState _state = WebSocketState.Connecting; private WebSocket _webSocket; public static WebSocketHandle Create() => new WebSocketHandle(); public static bool IsValid(WebSocketHandle handle) => handle != null; public WebSocketCloseStatus? CloseStatus => _webSocket?.CloseStatus; public string CloseStatusDescription => _webSocket?.CloseStatusDescription; public WebSocketState State => _webSocket?.State ?? _state; public string SubProtocol => _webSocket?.SubProtocol; public static void CheckPlatformSupport() { /* nop */ } public void Dispose() { _state = WebSocketState.Closed; _webSocket?.Dispose(); } public void Abort() { _abortSource.Cancel(); _webSocket?.Abort(); } public Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) => _webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); public Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) => _webSocket.ReceiveAsync(buffer, cancellationToken); public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) => _webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken); public Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) => _webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken); public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { // TODO #14480 : Not currently implemented, or explicitly ignored: // - ClientWebSocketOptions.UseDefaultCredentials // - ClientWebSocketOptions.Credentials // - ClientWebSocketOptions.Proxy // - ClientWebSocketOptions._sendBufferSize // Establish connection to the server CancellationTokenRegistration registration = cancellationToken.Register(s => ((WebSocketHandle)s).Abort(), this); try { // Connect to the remote server Socket connectedSocket = await ConnectSocketAsync(uri.Host, uri.Port, cancellationToken).ConfigureAwait(false); Stream stream = new NetworkStream(connectedSocket, ownsSocket:true); // Upgrade to SSL if needed if (uri.Scheme == UriScheme.Wss) { var sslStream = new SslStream(stream); await sslStream.AuthenticateAsClientAsync( uri.Host, options.ClientCertificates, SecurityProtocol.AllowedSecurityProtocols, checkCertificateRevocation: false).ConfigureAwait(false); stream = sslStream; } // Create the security key and expected response, then build all of the request headers KeyValuePair<string, string> secKeyAndSecWebSocketAccept = CreateSecKeyAndSecWebSocketAccept(); byte[] requestHeader = BuildRequestHeader(uri, options, secKeyAndSecWebSocketAccept.Key); // Write out the header to the connection await stream.WriteAsync(requestHeader, 0, requestHeader.Length, cancellationToken).ConfigureAwait(false); // Parse the response and store our state for the remainder of the connection string subprotocol = await ParseAndValidateConnectResponseAsync(stream, options, secKeyAndSecWebSocketAccept.Value, cancellationToken).ConfigureAwait(false); _webSocket = WebSocket.CreateClientWebSocket( stream, subprotocol, options.ReceiveBufferSize, options.SendBufferSize, options.KeepAliveInterval, false, options.Buffer.GetValueOrDefault()); // If a concurrent Abort or Dispose came in before we set _webSocket, make sure to update it appropriately if (_state == WebSocketState.Aborted) { _webSocket.Abort(); } else if (_state == WebSocketState.Closed) { _webSocket.Dispose(); } } catch (Exception exc) { if (_state < WebSocketState.Closed) { _state = WebSocketState.Closed; } Abort(); if (exc is WebSocketException) { throw; } throw new WebSocketException(SR.net_webstatus_ConnectFailure, exc); } finally { registration.Dispose(); } } /// <summary>Connects a socket to the specified host and port, subject to cancellation and aborting.</summary> /// <param name="host">The host to which to connect.</param> /// <param name="port">The port to which to connect on the host.</param> /// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param> /// <returns>The connected Socket.</returns> private async Task<Socket> ConnectSocketAsync(string host, int port, CancellationToken cancellationToken) { IPAddress[] addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false); ExceptionDispatchInfo lastException = null; foreach (IPAddress address in addresses) { var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { using (cancellationToken.Register(s => ((Socket)s).Dispose(), socket)) using (_abortSource.Token.Register(s => ((Socket)s).Dispose(), socket)) { try { await socket.ConnectAsync(address, port).ConfigureAwait(false); } catch (ObjectDisposedException ode) { // If the socket was disposed because cancellation was requested, translate the exception // into a new OperationCanceledException. Otherwise, let the original ObjectDisposedexception propagate. CancellationToken token = cancellationToken.IsCancellationRequested ? cancellationToken : _abortSource.Token; if (token.IsCancellationRequested) { throw new OperationCanceledException(new OperationCanceledException().Message, ode, token); } } } cancellationToken.ThrowIfCancellationRequested(); // in case of a race and socket was disposed after the await _abortSource.Token.ThrowIfCancellationRequested(); return socket; } catch (Exception exc) { socket.Dispose(); lastException = ExceptionDispatchInfo.Capture(exc); } } lastException?.Throw(); Debug.Fail("We should never get here. We should have already returned or an exception should have been thrown."); throw new WebSocketException(SR.net_webstatus_ConnectFailure); } /// <summary>Creates a byte[] containing the headers to send to the server.</summary> /// <param name="uri">The Uri of the server.</param> /// <param name="options">The options used to configure the websocket.</param> /// <param name="secKey">The generated security key to send in the Sec-WebSocket-Key header.</param> /// <returns>The byte[] containing the encoded headers ready to send to the network.</returns> private static byte[] BuildRequestHeader(Uri uri, ClientWebSocketOptions options, string secKey) { StringBuilder builder = t_cachedStringBuilder ?? (t_cachedStringBuilder = new StringBuilder()); Debug.Assert(builder.Length == 0, $"Expected builder to be empty, got one of length {builder.Length}"); try { builder.Append("GET ").Append(uri.PathAndQuery).Append(" HTTP/1.1\r\n"); // Add all of the required headers, honoring Host header if set. string hostHeader = options.RequestHeaders[HttpKnownHeaderNames.Host]; builder.Append("Host: "); if (string.IsNullOrEmpty(hostHeader)) { builder.Append(uri.IdnHost).Append(':').Append(uri.Port).Append("\r\n"); } else { builder.Append(hostHeader).Append("\r\n"); } builder.Append("Connection: Upgrade\r\n"); builder.Append("Upgrade: websocket\r\n"); builder.Append("Sec-WebSocket-Version: 13\r\n"); builder.Append("Sec-WebSocket-Key: ").Append(secKey).Append("\r\n"); // Add all of the additionally requested headers foreach (string key in options.RequestHeaders.AllKeys) { if (string.Equals(key, HttpKnownHeaderNames.Host, StringComparison.OrdinalIgnoreCase)) { // Host header handled above continue; } builder.Append(key).Append(": ").Append(options.RequestHeaders[key]).Append("\r\n"); } // Add the optional subprotocols header if (options.RequestedSubProtocols.Count > 0) { builder.Append(HttpKnownHeaderNames.SecWebSocketProtocol).Append(": "); builder.Append(options.RequestedSubProtocols[0]); for (int i = 1; i < options.RequestedSubProtocols.Count; i++) { builder.Append(", ").Append(options.RequestedSubProtocols[i]); } builder.Append("\r\n"); } // Add an optional cookies header if (options.Cookies != null) { string header = options.Cookies.GetCookieHeader(uri); if (!string.IsNullOrWhiteSpace(header)) { builder.Append(HttpKnownHeaderNames.Cookie).Append(": ").Append(header).Append("\r\n"); } } // End the headers builder.Append("\r\n"); // Return the bytes for the built up header return s_defaultHttpEncoding.GetBytes(builder.ToString()); } finally { // Make sure we clear the builder builder.Clear(); } } /// <summary> /// Creates a pair of a security key for sending in the Sec-WebSocket-Key header and /// the associated response we expect to receive as the Sec-WebSocket-Accept header value. /// </summary> /// <returns>A key-value pair of the request header security key and expected response header value.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "Required by RFC6455")] private static KeyValuePair<string, string> CreateSecKeyAndSecWebSocketAccept() { string secKey = Convert.ToBase64String(Guid.NewGuid().ToByteArray()); using (SHA1 sha = SHA1.Create()) { return new KeyValuePair<string, string>( secKey, Convert.ToBase64String(sha.ComputeHash(Encoding.ASCII.GetBytes(secKey + WSServerGuid)))); } } /// <summary>Read and validate the connect response headers from the server.</summary> /// <param name="stream">The stream from which to read the response headers.</param> /// <param name="options">The options used to configure the websocket.</param> /// <param name="expectedSecWebSocketAccept">The expected value of the Sec-WebSocket-Accept header.</param> /// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param> /// <returns>The agreed upon subprotocol with the server, or null if there was none.</returns> private async Task<string> ParseAndValidateConnectResponseAsync( Stream stream, ClientWebSocketOptions options, string expectedSecWebSocketAccept, CancellationToken cancellationToken) { // Read the first line of the response string statusLine = await ReadResponseHeaderLineAsync(stream, cancellationToken).ConfigureAwait(false); // Depending on the underlying sockets implementation and timing, connecting to a server that then // immediately closes the connection may either result in an exception getting thrown from the connect // earlier, or it may result in getting to here but reading 0 bytes. If we read 0 bytes and thus have // an empty status line, treat it as a connect failure. if (string.IsNullOrEmpty(statusLine)) { throw new WebSocketException(SR.Format(SR.net_webstatus_ConnectFailure)); } const string ExpectedStatusStart = "HTTP/1.1 "; const string ExpectedStatusStatWithCode = "HTTP/1.1 101"; // 101 == SwitchingProtocols // If the status line doesn't begin with "HTTP/1.1" or isn't long enough to contain a status code, fail. if (!statusLine.StartsWith(ExpectedStatusStart, StringComparison.Ordinal) || statusLine.Length < ExpectedStatusStatWithCode.Length) { throw new WebSocketException(WebSocketError.HeaderError); } // If the status line doesn't contain a status code 101, or if it's long enough to have a status description // but doesn't contain whitespace after the 101, fail. if (!statusLine.StartsWith(ExpectedStatusStatWithCode, StringComparison.Ordinal) || (statusLine.Length > ExpectedStatusStatWithCode.Length && !char.IsWhiteSpace(statusLine[ExpectedStatusStatWithCode.Length]))) { throw new WebSocketException(SR.net_webstatus_ConnectFailure); } // Read each response header. Be liberal in parsing the response header, treating // everything to the left of the colon as the key and everything to the right as the value, trimming both. // For each header, validate that we got the expected value. bool foundUpgrade = false, foundConnection = false, foundSecWebSocketAccept = false; string subprotocol = null; string line; while (!string.IsNullOrEmpty(line = await ReadResponseHeaderLineAsync(stream, cancellationToken).ConfigureAwait(false))) { int colonIndex = line.IndexOf(':'); if (colonIndex == -1) { throw new WebSocketException(WebSocketError.HeaderError); } string headerName = line.SubstringTrim(0, colonIndex); string headerValue = line.SubstringTrim(colonIndex + 1); // The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values. ValidateAndTrackHeader(HttpKnownHeaderNames.Connection, "Upgrade", headerName, headerValue, ref foundConnection); ValidateAndTrackHeader(HttpKnownHeaderNames.Upgrade, "websocket", headerName, headerValue, ref foundUpgrade); ValidateAndTrackHeader(HttpKnownHeaderNames.SecWebSocketAccept, expectedSecWebSocketAccept, headerName, headerValue, ref foundSecWebSocketAccept); // The SecWebSocketProtocol header is optional. We should only get it with a non-empty value if we requested subprotocols, // and then it must only be one of the ones we requested. If we got a subprotocol other than one we requested (or if we // already got one in a previous header), fail. Otherwise, track which one we got. if (string.Equals(HttpKnownHeaderNames.SecWebSocketProtocol, headerName, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(headerValue)) { string newSubprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, headerValue, StringComparison.OrdinalIgnoreCase)); if (newSubprotocol == null || subprotocol != null) { throw new WebSocketException( WebSocketError.UnsupportedProtocol, SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol, string.Join(", ", options.RequestedSubProtocols), subprotocol)); } subprotocol = newSubprotocol; } } if (!foundUpgrade || !foundConnection || !foundSecWebSocketAccept) { throw new WebSocketException(SR.net_webstatus_ConnectFailure); } return subprotocol; } /// <summary>Validates a received header against expected values and tracks that we've received it.</summary> /// <param name="targetHeaderName">The header name against which we're comparing.</param> /// <param name="targetHeaderValue">The header value against which we're comparing.</param> /// <param name="foundHeaderName">The actual header name received.</param> /// <param name="foundHeaderValue">The actual header value received.</param> /// <param name="foundHeader">A bool tracking whether this header has been seen.</param> private static void ValidateAndTrackHeader( string targetHeaderName, string targetHeaderValue, string foundHeaderName, string foundHeaderValue, ref bool foundHeader) { bool isTargetHeader = string.Equals(targetHeaderName, foundHeaderName, StringComparison.OrdinalIgnoreCase); if (!foundHeader) { if (isTargetHeader) { if (!string.Equals(targetHeaderValue, foundHeaderValue, StringComparison.OrdinalIgnoreCase)) { throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidResponseHeader, targetHeaderName, foundHeaderValue)); } foundHeader = true; } } else { if (isTargetHeader) { throw new WebSocketException(SR.Format(SR.net_webstatus_ConnectFailure)); } } } /// <summary>Reads a line from the stream.</summary> /// <param name="stream">The stream from which to read.</param> /// <param name="cancellationToken">The CancellationToken used to cancel the websocket.</param> /// <returns>The read line, or null if none could be read.</returns> private static async Task<string> ReadResponseHeaderLineAsync(Stream stream, CancellationToken cancellationToken) { StringBuilder sb = t_cachedStringBuilder; if (sb != null) { t_cachedStringBuilder = null; Debug.Assert(sb.Length == 0, $"Expected empty StringBuilder"); } else { sb = new StringBuilder(); } var arr = new byte[1]; char prevChar = '\0'; try { // TODO: Reading one byte is extremely inefficient. The problem, however, // is that if we read multiple bytes, we could end up reading bytes post-headers // that are part of messages meant to be read by the managed websocket after // the connection. The likely solution here is to wrap the stream in a BufferedStream, // though a) that comes at the expense of an extra set of virtual calls, b) // it adds a buffer when the managed websocket will already be using a buffer, and // c) it's not exposed on the version of the System.IO contract we're currently using. while (await stream.ReadAsync(arr, 0, 1, cancellationToken).ConfigureAwait(false) == 1) { // Process the next char char curChar = (char)arr[0]; if (prevChar == '\r' && curChar == '\n') { break; } sb.Append(curChar); prevChar = curChar; } if (sb.Length > 0 && sb[sb.Length - 1] == '\r') { sb.Length = sb.Length - 1; } return sb.ToString(); } finally { sb.Clear(); t_cachedStringBuilder = sb; } } } }
using J2N.Text; using YAF.Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace YAF.Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ArrayUtil = YAF.Lucene.Net.Util.ArrayUtil; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using FlushInfo = YAF.Lucene.Net.Store.FlushInfo; using IOContext = YAF.Lucene.Net.Store.IOContext; using IOUtils = YAF.Lucene.Net.Util.IOUtils; using RamUsageEstimator = YAF.Lucene.Net.Util.RamUsageEstimator; using TermVectorsWriter = YAF.Lucene.Net.Codecs.TermVectorsWriter; internal sealed class TermVectorsConsumer : TermsHashConsumer { internal TermVectorsWriter writer; internal readonly DocumentsWriterPerThread docWriter; internal readonly DocumentsWriterPerThread.DocState docState; internal readonly BytesRef flushTerm = new BytesRef(); // Used by perField when serializing the term vectors internal readonly ByteSliceReader vectorSliceReaderPos = new ByteSliceReader(); internal readonly ByteSliceReader vectorSliceReaderOff = new ByteSliceReader(); internal bool hasVectors; internal int numVectorFields; internal int lastDocID; private TermVectorsConsumerPerField[] perFields = new TermVectorsConsumerPerField[1]; public TermVectorsConsumer(DocumentsWriterPerThread docWriter) { this.docWriter = docWriter; docState = docWriter.docState; } // LUCENENE specific - original was internal, but FreqProxTermsWriter requires public (little point, since both are internal classes) [MethodImpl(MethodImplOptions.NoInlining)] public override void Flush(IDictionary<string, TermsHashConsumerPerField> fieldsToFlush, SegmentWriteState state) { if (writer != null) { int numDocs = state.SegmentInfo.DocCount; Debug.Assert(numDocs > 0); // At least one doc in this run had term vectors enabled try { Fill(numDocs); Debug.Assert(state.SegmentInfo != null); writer.Finish(state.FieldInfos, numDocs); } finally { IOUtils.Dispose(writer); writer = null; lastDocID = 0; hasVectors = false; } } foreach (TermsHashConsumerPerField field in fieldsToFlush.Values) { TermVectorsConsumerPerField perField = (TermVectorsConsumerPerField)field; perField.termsHashPerField.Reset(); perField.ShrinkHash(); } } /// <summary> /// Fills in no-term-vectors for all docs we haven't seen /// since the last doc that had term vectors. /// </summary> internal void Fill(int docID) { while (lastDocID < docID) { writer.StartDocument(0); writer.FinishDocument(); lastDocID++; } } [MethodImpl(MethodImplOptions.NoInlining)] private void InitTermVectorsWriter() { if (writer == null) { IOContext context = new IOContext(new FlushInfo(docWriter.NumDocsInRAM, docWriter.BytesUsed)); writer = docWriter.codec.TermVectorsFormat.VectorsWriter(docWriter.directory, docWriter.SegmentInfo, context); lastDocID = 0; } } [MethodImpl(MethodImplOptions.NoInlining)] internal override void FinishDocument(TermsHash termsHash) { Debug.Assert(docWriter.TestPoint("TermVectorsTermsWriter.finishDocument start")); if (!hasVectors) { return; } InitTermVectorsWriter(); Fill(docState.docID); // Append term vectors to the real outputs: writer.StartDocument(numVectorFields); for (int i = 0; i < numVectorFields; i++) { perFields[i].FinishDocument(); } writer.FinishDocument(); Debug.Assert(lastDocID == docState.docID, "lastDocID=" + lastDocID + " docState.docID=" + docState.docID); lastDocID++; termsHash.Reset(); Reset(); Debug.Assert(docWriter.TestPoint("TermVectorsTermsWriter.finishDocument end")); } [MethodImpl(MethodImplOptions.NoInlining)] public override void Abort() { hasVectors = false; if (writer != null) { writer.Abort(); writer = null; } lastDocID = 0; Reset(); } internal void Reset() { Arrays.Fill(perFields, null); // don't hang onto stuff from previous doc numVectorFields = 0; } public override TermsHashConsumerPerField AddField(TermsHashPerField termsHashPerField, FieldInfo fieldInfo) { return new TermVectorsConsumerPerField(termsHashPerField, this, fieldInfo); } [MethodImpl(MethodImplOptions.NoInlining)] internal void AddFieldToFlush(TermVectorsConsumerPerField fieldToFlush) { if (numVectorFields == perFields.Length) { int newSize = ArrayUtil.Oversize(numVectorFields + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF); TermVectorsConsumerPerField[] newArray = new TermVectorsConsumerPerField[newSize]; Array.Copy(perFields, 0, newArray, 0, numVectorFields); perFields = newArray; } perFields[numVectorFields++] = fieldToFlush; } internal override void StartDocument() { Debug.Assert(ClearLastVectorFieldName()); Reset(); } // Called only by assert internal bool ClearLastVectorFieldName() { lastVectorFieldName = null; return true; } // Called only by assert internal string lastVectorFieldName; internal bool VectorFieldsInOrder(FieldInfo fi) { try { return lastVectorFieldName != null ? lastVectorFieldName.CompareToOrdinal(fi.Name) < 0 : true; } finally { lastVectorFieldName = fi.Name; } } } }
// <copyright file=HydraMonoBehaviour company=Hydra> // Copyright (c) 2015 All Rights Reserved // </copyright> // <author>Christopher Cameron</author> using System; using System.Collections.Generic; using Hydra.HydraCommon.API; using Hydra.HydraCommon.EventArguments; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace Hydra.HydraCommon.Abstract { /// <summary> /// HydraMonoBehaviour simply provides a common base class for all Hydra MonoBehaviours. /// </summary> public abstract class HydraMonoBehaviour : MonoBehaviour, IRecyclable { public event EventHandler onUpdateCallback; public event EventHandler onFixedUpdateCallback; public event EventHandler onWillRenderObjectCallback; public event EventHandler<EventArg<Collision>> onCollisionEnterCallback; #if UNITY_EDITOR /// <summary> /// When the editor goes out of focus it may be an extended amount of /// time before it updates again. To avoid processing long update /// intervals (and potentially locking up) we will ignore updates that /// take longer than this amount of time. /// </summary> private const float MAX_EDITOR_UPDATE_TIME = 3.0f; private float? m_LastEditorUpdateTime; #endif private List<HydraMonoBehaviourChild> m_MonoBehaviourChildren; // Cache private Camera m_CachedCamera; private Collider m_CachedCollider; private Transform m_CachedTransform; private Rigidbody m_CachedRigidbody; private Renderer m_CachedRenderer; #region Optimized Properties /// <summary> /// Gets the camera. /// </summary> /// <value>The camera.</value> public new Camera camera { get { if (m_CachedCamera == null) m_CachedCamera = base.GetComponent<Camera>(); return m_CachedCamera; } } /// <summary> /// Gets the collider. /// </summary> /// <value>The collider.</value> public new Collider collider { get { if (m_CachedCollider == null) m_CachedCollider = base.GetComponent<Collider>(); return m_CachedCollider; } } /// <summary> /// Gets the transform. /// </summary> /// <value>The transform.</value> public new Transform transform { get { if (m_CachedTransform == null) m_CachedTransform = base.transform; return m_CachedTransform; } } /// <summary> /// Gets the rigidbody. /// </summary> /// <value>The rigidbody.</value> public new Rigidbody rigidbody { get { if (m_CachedRigidbody == null) m_CachedRigidbody = base.GetComponent<Rigidbody>(); return m_CachedRigidbody; } } /// <summary> /// Gets the renderer. /// </summary> /// <value>The renderer.</value> public new Renderer renderer { get { if (m_CachedRenderer == null) m_CachedRenderer = base.GetComponent<Renderer>(); return m_CachedRenderer; } } #endregion #region Messages /// <summary> /// Resets the instances values back to defaults. /// </summary> public virtual void Reset() { ProcessMessage(HydraMonoBehaviourChild.Message.OnReset); } /// <summary> /// Called before the first Update. /// </summary> protected virtual void Start() {} /// <summary> /// Called when the object is instantiated. /// </summary> protected virtual void Awake() {} /// <summary> /// Called once every frame. /// </summary> protected virtual void Update() { EventHandler handler = onUpdateCallback; if (handler != null) handler(this, EventArgs.Empty); ProcessMessage(HydraMonoBehaviourChild.Message.OnUpdate); } /// <summary> /// Called every physics timestep. /// </summary> protected virtual void FixedUpdate() { EventHandler handler = onFixedUpdateCallback; if (handler != null) handler(this, EventArgs.Empty); } /// <summary> /// Called after all Updates have finished. /// </summary> protected virtual void LateUpdate() {} /// <summary> /// Called when the component is enabled. /// </summary> protected virtual void OnEnable() { ProcessMessage(HydraMonoBehaviourChild.Message.OnEnable); Subscribe(); } /// <summary> /// Called when the component is disabled. /// </summary> protected virtual void OnDisable() { ProcessMessage(HydraMonoBehaviourChild.Message.OnDisable); Unsubscribe(); } /// <summary> /// Called when culling is about to take place. /// </summary> protected virtual void OnPreCull() {} /// <summary> /// Called when the editor updates. /// </summary> protected virtual void OnEditorUpdate() { #if UNITY_EDITOR float realTime = Time.realtimeSinceStartup; if (m_LastEditorUpdateTime != null) { float updateTime = realTime - (float)m_LastEditorUpdateTime; // Don't process every little update interval if (updateTime < Time.fixedDeltaTime) return; if (updateTime <= MAX_EDITOR_UPDATE_TIME) OnEditorUpdate(updateTime); } m_LastEditorUpdateTime = realTime; #endif } /// <summary> /// Called when the editor updates. /// </summary> /// <param name="updateTime">Update time.</param> protected virtual void OnEditorUpdate(float updateTime) {} /// <summary> /// Called when the attached Camera component is done rendering. /// </summary> protected virtual void OnPostRender() {} /// <summary> /// Called once for each camera if the object is visible. /// </summary> protected virtual void OnWillRenderObject() { EventHandler handler = onWillRenderObjectCallback; if (handler != null) handler(this, EventArgs.Empty); } /// <summary> /// OnControllerColliderHit is called when the CharacterController hits a collider while performing a Move. /// </summary> /// <param name="hit">Hit.</param> protected virtual void OnControllerColliderHit(ControllerColliderHit hit) {} /// <summary> /// OnCollisionEnter is called when this collider/rigidbody has begun /// touching another rigidbody/collider. /// </summary> /// <param name="collision">Collision.</param> protected virtual void OnCollisionEnter(Collision collision) { EventHandler<EventArg<Collision>> handler = onCollisionEnterCallback; if (handler != null) handler(this, new EventArg<Collision>(collision)); } /// <summary> /// OnTriggerStay is called every FixedUpdate for every Collider that is /// touching the trigger. /// </summary> /// <param name="other">Other.</param> protected virtual void OnTriggerStay(Collider other) {} /// <summary> /// OnTriggerEnter is called when the Collider other enters the trigger. /// </summary> /// <param name="other">Other.</param> protected virtual void OnTriggerEnter(Collider other) {} /// <summary> /// OnTriggerExit is called when the Collider other has stopped touching the trigger. /// </summary> /// <param name="other">Other.</param> protected virtual void OnTriggerExit(Collider other) {} /// <summary> /// Called to draw gizmos in the scene view. /// </summary> protected virtual void OnDrawGizmos() {} /// <summary> /// Called to draw gizmos in the scene view while selected. /// </summary> protected virtual void OnDrawGizmosSelected() {} /// <summary> /// Called when the object is destroyed. /// </summary> protected virtual void OnDestroy() { ProcessMessage(HydraMonoBehaviourChild.Message.OnDestroy); } /// <summary> /// Called to draw to the GUI. /// </summary> protected virtual void OnGUI() {} /// <summary> /// OnMouseDown is called when the user has pressed the mouse button while over the /// GUIElement or Collider. /// </summary> protected virtual void OnMouseDown() {} /// <summary> /// Called when a level finishes loading. /// </summary> /// <param name="index">Index.</param> protected virtual void OnLevelWasLoaded(int index) {} #endregion /// <summary> /// Override this method to return any HydraMonoBehaviourChild instances. /// </summary> /// <returns>The mono behaviour children.</returns> protected virtual List<HydraMonoBehaviourChild> GetMonoBehaviourChildren() { if (m_MonoBehaviourChildren == null) m_MonoBehaviourChildren = new List<HydraMonoBehaviourChild>(); m_MonoBehaviourChildren.Clear(); return m_MonoBehaviourChildren; } /// <summary> /// Processes the message. /// </summary> /// <param name="message">Message.</param> private void ProcessMessage(HydraMonoBehaviourChild.Message message) { HydraMonoBehaviourChild.ProcessMessage(GetMonoBehaviourChildren(), this, message); } /// <summary> /// Subscribe to Unity events. /// </summary> private void Subscribe() { #if UNITY_EDITOR m_LastEditorUpdateTime = null; EditorApplication.update += OnEditorUpdate; #endif } /// <summary> /// Unsubscribe from Unity events. /// </summary> private void Unsubscribe() { #if UNITY_EDITOR m_LastEditorUpdateTime = null; EditorApplication.update -= OnEditorUpdate; #endif } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/proto/grpc/testing/payloads.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Grpc.Testing { /// <summary>Holder for reflection information generated from src/proto/grpc/testing/payloads.proto</summary> public static partial class PayloadsReflection { #region Descriptor /// <summary>File descriptor for src/proto/grpc/testing/payloads.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static PayloadsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiVzcmMvcHJvdG8vZ3JwYy90ZXN0aW5nL3BheWxvYWRzLnByb3RvEgxncnBj", "LnRlc3RpbmciNwoQQnl0ZUJ1ZmZlclBhcmFtcxIQCghyZXFfc2l6ZRgBIAEo", "BRIRCglyZXNwX3NpemUYAiABKAUiOAoRU2ltcGxlUHJvdG9QYXJhbXMSEAoI", "cmVxX3NpemUYASABKAUSEQoJcmVzcF9zaXplGAIgASgFIhQKEkNvbXBsZXhQ", "cm90b1BhcmFtcyLKAQoNUGF5bG9hZENvbmZpZxI4Cg5ieXRlYnVmX3BhcmFt", "cxgBIAEoCzIeLmdycGMudGVzdGluZy5CeXRlQnVmZmVyUGFyYW1zSAASOAoN", "c2ltcGxlX3BhcmFtcxgCIAEoCzIfLmdycGMudGVzdGluZy5TaW1wbGVQcm90", "b1BhcmFtc0gAEjoKDmNvbXBsZXhfcGFyYW1zGAMgASgLMiAuZ3JwYy50ZXN0", "aW5nLkNvbXBsZXhQcm90b1BhcmFtc0gAQgkKB3BheWxvYWRiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.ByteBufferParams), global::Grpc.Testing.ByteBufferParams.Parser, new[]{ "ReqSize", "RespSize" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.SimpleProtoParams), global::Grpc.Testing.SimpleProtoParams.Parser, new[]{ "ReqSize", "RespSize" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.ComplexProtoParams), global::Grpc.Testing.ComplexProtoParams.Parser, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.PayloadConfig), global::Grpc.Testing.PayloadConfig.Parser, new[]{ "BytebufParams", "SimpleParams", "ComplexParams" }, new[]{ "Payload" }, null, null) })); } #endregion } #region Messages public sealed partial class ByteBufferParams : pb::IMessage<ByteBufferParams> { private static readonly pb::MessageParser<ByteBufferParams> _parser = new pb::MessageParser<ByteBufferParams>(() => new ByteBufferParams()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ByteBufferParams> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.PayloadsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ByteBufferParams() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ByteBufferParams(ByteBufferParams other) : this() { reqSize_ = other.reqSize_; respSize_ = other.respSize_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ByteBufferParams Clone() { return new ByteBufferParams(this); } /// <summary>Field number for the "req_size" field.</summary> public const int ReqSizeFieldNumber = 1; private int reqSize_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int ReqSize { get { return reqSize_; } set { reqSize_ = value; } } /// <summary>Field number for the "resp_size" field.</summary> public const int RespSizeFieldNumber = 2; private int respSize_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int RespSize { get { return respSize_; } set { respSize_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ByteBufferParams); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ByteBufferParams other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ReqSize != other.ReqSize) return false; if (RespSize != other.RespSize) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ReqSize != 0) hash ^= ReqSize.GetHashCode(); if (RespSize != 0) hash ^= RespSize.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ReqSize != 0) { output.WriteRawTag(8); output.WriteInt32(ReqSize); } if (RespSize != 0) { output.WriteRawTag(16); output.WriteInt32(RespSize); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ReqSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(ReqSize); } if (RespSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(RespSize); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ByteBufferParams other) { if (other == null) { return; } if (other.ReqSize != 0) { ReqSize = other.ReqSize; } if (other.RespSize != 0) { RespSize = other.RespSize; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { ReqSize = input.ReadInt32(); break; } case 16: { RespSize = input.ReadInt32(); break; } } } } } public sealed partial class SimpleProtoParams : pb::IMessage<SimpleProtoParams> { private static readonly pb::MessageParser<SimpleProtoParams> _parser = new pb::MessageParser<SimpleProtoParams>(() => new SimpleProtoParams()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<SimpleProtoParams> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.PayloadsReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SimpleProtoParams() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SimpleProtoParams(SimpleProtoParams other) : this() { reqSize_ = other.reqSize_; respSize_ = other.respSize_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SimpleProtoParams Clone() { return new SimpleProtoParams(this); } /// <summary>Field number for the "req_size" field.</summary> public const int ReqSizeFieldNumber = 1; private int reqSize_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int ReqSize { get { return reqSize_; } set { reqSize_ = value; } } /// <summary>Field number for the "resp_size" field.</summary> public const int RespSizeFieldNumber = 2; private int respSize_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int RespSize { get { return respSize_; } set { respSize_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as SimpleProtoParams); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(SimpleProtoParams other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ReqSize != other.ReqSize) return false; if (RespSize != other.RespSize) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ReqSize != 0) hash ^= ReqSize.GetHashCode(); if (RespSize != 0) hash ^= RespSize.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ReqSize != 0) { output.WriteRawTag(8); output.WriteInt32(ReqSize); } if (RespSize != 0) { output.WriteRawTag(16); output.WriteInt32(RespSize); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ReqSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(ReqSize); } if (RespSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(RespSize); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SimpleProtoParams other) { if (other == null) { return; } if (other.ReqSize != 0) { ReqSize = other.ReqSize; } if (other.RespSize != 0) { RespSize = other.RespSize; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { ReqSize = input.ReadInt32(); break; } case 16: { RespSize = input.ReadInt32(); break; } } } } } /// <summary> /// TODO (vpai): Fill this in once the details of complex, representative /// protos are decided /// </summary> public sealed partial class ComplexProtoParams : pb::IMessage<ComplexProtoParams> { private static readonly pb::MessageParser<ComplexProtoParams> _parser = new pb::MessageParser<ComplexProtoParams>(() => new ComplexProtoParams()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ComplexProtoParams> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.PayloadsReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ComplexProtoParams() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ComplexProtoParams(ComplexProtoParams other) : this() { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ComplexProtoParams Clone() { return new ComplexProtoParams(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ComplexProtoParams); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ComplexProtoParams other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ComplexProtoParams other) { if (other == null) { return; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } } public sealed partial class PayloadConfig : pb::IMessage<PayloadConfig> { private static readonly pb::MessageParser<PayloadConfig> _parser = new pb::MessageParser<PayloadConfig>(() => new PayloadConfig()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PayloadConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.PayloadsReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PayloadConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PayloadConfig(PayloadConfig other) : this() { switch (other.PayloadCase) { case PayloadOneofCase.BytebufParams: BytebufParams = other.BytebufParams.Clone(); break; case PayloadOneofCase.SimpleParams: SimpleParams = other.SimpleParams.Clone(); break; case PayloadOneofCase.ComplexParams: ComplexParams = other.ComplexParams.Clone(); break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PayloadConfig Clone() { return new PayloadConfig(this); } /// <summary>Field number for the "bytebuf_params" field.</summary> public const int BytebufParamsFieldNumber = 1; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Grpc.Testing.ByteBufferParams BytebufParams { get { return payloadCase_ == PayloadOneofCase.BytebufParams ? (global::Grpc.Testing.ByteBufferParams) payload_ : null; } set { payload_ = value; payloadCase_ = value == null ? PayloadOneofCase.None : PayloadOneofCase.BytebufParams; } } /// <summary>Field number for the "simple_params" field.</summary> public const int SimpleParamsFieldNumber = 2; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Grpc.Testing.SimpleProtoParams SimpleParams { get { return payloadCase_ == PayloadOneofCase.SimpleParams ? (global::Grpc.Testing.SimpleProtoParams) payload_ : null; } set { payload_ = value; payloadCase_ = value == null ? PayloadOneofCase.None : PayloadOneofCase.SimpleParams; } } /// <summary>Field number for the "complex_params" field.</summary> public const int ComplexParamsFieldNumber = 3; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Grpc.Testing.ComplexProtoParams ComplexParams { get { return payloadCase_ == PayloadOneofCase.ComplexParams ? (global::Grpc.Testing.ComplexProtoParams) payload_ : null; } set { payload_ = value; payloadCase_ = value == null ? PayloadOneofCase.None : PayloadOneofCase.ComplexParams; } } private object payload_; /// <summary>Enum of possible cases for the "payload" oneof.</summary> public enum PayloadOneofCase { None = 0, BytebufParams = 1, SimpleParams = 2, ComplexParams = 3, } private PayloadOneofCase payloadCase_ = PayloadOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PayloadOneofCase PayloadCase { get { return payloadCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearPayload() { payloadCase_ = PayloadOneofCase.None; payload_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PayloadConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PayloadConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(BytebufParams, other.BytebufParams)) return false; if (!object.Equals(SimpleParams, other.SimpleParams)) return false; if (!object.Equals(ComplexParams, other.ComplexParams)) return false; if (PayloadCase != other.PayloadCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (payloadCase_ == PayloadOneofCase.BytebufParams) hash ^= BytebufParams.GetHashCode(); if (payloadCase_ == PayloadOneofCase.SimpleParams) hash ^= SimpleParams.GetHashCode(); if (payloadCase_ == PayloadOneofCase.ComplexParams) hash ^= ComplexParams.GetHashCode(); hash ^= (int) payloadCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (payloadCase_ == PayloadOneofCase.BytebufParams) { output.WriteRawTag(10); output.WriteMessage(BytebufParams); } if (payloadCase_ == PayloadOneofCase.SimpleParams) { output.WriteRawTag(18); output.WriteMessage(SimpleParams); } if (payloadCase_ == PayloadOneofCase.ComplexParams) { output.WriteRawTag(26); output.WriteMessage(ComplexParams); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (payloadCase_ == PayloadOneofCase.BytebufParams) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(BytebufParams); } if (payloadCase_ == PayloadOneofCase.SimpleParams) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SimpleParams); } if (payloadCase_ == PayloadOneofCase.ComplexParams) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ComplexParams); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PayloadConfig other) { if (other == null) { return; } switch (other.PayloadCase) { case PayloadOneofCase.BytebufParams: if (BytebufParams == null) { BytebufParams = new global::Grpc.Testing.ByteBufferParams(); } BytebufParams.MergeFrom(other.BytebufParams); break; case PayloadOneofCase.SimpleParams: if (SimpleParams == null) { SimpleParams = new global::Grpc.Testing.SimpleProtoParams(); } SimpleParams.MergeFrom(other.SimpleParams); break; case PayloadOneofCase.ComplexParams: if (ComplexParams == null) { ComplexParams = new global::Grpc.Testing.ComplexProtoParams(); } ComplexParams.MergeFrom(other.ComplexParams); break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { global::Grpc.Testing.ByteBufferParams subBuilder = new global::Grpc.Testing.ByteBufferParams(); if (payloadCase_ == PayloadOneofCase.BytebufParams) { subBuilder.MergeFrom(BytebufParams); } input.ReadMessage(subBuilder); BytebufParams = subBuilder; break; } case 18: { global::Grpc.Testing.SimpleProtoParams subBuilder = new global::Grpc.Testing.SimpleProtoParams(); if (payloadCase_ == PayloadOneofCase.SimpleParams) { subBuilder.MergeFrom(SimpleParams); } input.ReadMessage(subBuilder); SimpleParams = subBuilder; break; } case 26: { global::Grpc.Testing.ComplexProtoParams subBuilder = new global::Grpc.Testing.ComplexProtoParams(); if (payloadCase_ == PayloadOneofCase.ComplexParams) { subBuilder.MergeFrom(ComplexParams); } input.ReadMessage(subBuilder); ComplexParams = subBuilder; break; } } } } } #endregion } #endregion Designer generated code
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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 the following location: * * 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. */ //package org.jasig.cas.web.flow; //import javax.servlet.http.HttpRequest; //import javax.servlet.http.HttpResponse; //import javax.validation.constraints.NotNull; //import org.jasig.cas.CentralAuthenticationService; //import org.jasig.cas.authentication.handler.AuthenticationException; //import org.jasig.cas.authentication.principal.Credentials; //import org.jasig.cas.authentication.principal.Service; //import org.jasig.cas.ticket.TicketException; //import org.jasig.cas.web.bind.CredentialsBinder; //import org.jasig.cas.web.support.WebUtils; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import org.springframework.binding.message.MessageBuilder; //import org.springframework.binding.message.MessageContext; //import org.springframework.util.StringUtils; //import org.springframework.web.util.CookieGenerator; //import org.springframework.webflow.execution.HttpContext; /** * Action to authenticate credentials and retrieve a TicketGrantingTicket for * those credentials. If there is a request for renew, then it also generates * the Service Ticket required. * * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.0.4 */ using System; using System.Web; using NCAS.jasig.authentication.handler; using NCAS.jasig.authentication.principal; using NCAS.jasig.ticket; using NCAS.jasig.web.MOCK2JAVA; using NCAS.jasig.web.bind; using NCAS.jasig.web.support; namespace NCAS.jasig.web.flow { public class AuthenticationViaFormAction { /** * Binder that allows additional binding of form object beyond Spring * defaults. */ private CredentialsBinder _credentialsBinder; /** Core we delegate to for handling all ticket related tasks. */ ////@NotNull private CentralAuthenticationService _centralAuthenticationService; ////@NotNull private CookieGenerator _warnCookieGenerator; public AuthenticationViaFormAction(CentralAuthenticationService centralAuthenticationService, CookieGenerator warnCookieGenerator) : this(null, centralAuthenticationService, warnCookieGenerator) { } private AuthenticationViaFormAction(CredentialsBinder credentialsBinder, CentralAuthenticationService centralAuthenticationService, CookieGenerator warnCookieGenerator) { _credentialsBinder = credentialsBinder; _centralAuthenticationService = centralAuthenticationService; _warnCookieGenerator = warnCookieGenerator; } //protected Logger logger = LoggerFactory.getLogger(getClass()); public void doBind(HttpContext context, Credentials credentials) { HttpRequest request = WebUtils.getHttpServletRequest(context); if (this._credentialsBinder != null && this._credentialsBinder.supports(credentials.GetType())) { this._credentialsBinder.bind(request, credentials); } } public string submit(HttpContext context, Credentials credentials, MessageContext messageContext) { // Validate login ticket string authoritativeLoginTicket = WebUtils.getLoginTicketFromFlowScope(context); string providedLoginTicket = WebUtils.getLoginTicketFromRequest(context); if (!authoritativeLoginTicket.Equals(providedLoginTicket)) { //this.logger.warn("Invalid login ticket " + providedLoginTicket); string code = "INVALID_TICKET"; //messageContext.addMessage( // new MessageBuilder().error().code(code).arg(providedLoginTicket).defaultText(code).build()); return "error"; } string ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context); Service service = WebUtils.getService(context); if (!string.IsNullOrEmpty(context.Request.QueryString["renew"]) && ticketGrantingTicketId != null && service != null) { try { string serviceTicketId = this._centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId, service, credentials); WebUtils.putServiceTicketInRequestScope(context, serviceTicketId); this.putWarnCookieIfRequestParameterPresent(context); return "warn"; } catch (TicketException e) { if (this.isCauseAuthenticationException(e)) { this.populateErrorsInstance(e, messageContext); return this.getAuthenticationExceptionEventId(e); } this._centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketId); //if (logger.isDebugEnabled()) { // logger.debug("Attempted to generate a ServiceTicket using renew=true with different credentials", e); //} } } try { var ticketValue = this._centralAuthenticationService.createTicketGrantingTicket(credentials); WebUtils.putTicketGrantingTicketInRequestScope(context, ticketValue); this.putWarnCookieIfRequestParameterPresent(context); return "success"; } catch (TicketException e) { this.populateErrorsInstance(e, messageContext); if (this.isCauseAuthenticationException(e)) return this.getAuthenticationExceptionEventId(e); return "error"; } } private void populateErrorsInstance(TicketException e, MessageContext messageContext) { //try //{ // messageContext.addMessage(new MessageBuilder().error().code(e.getCode()).defaultText(e.getCode()).build()); //} //catch (Exception fe) //{ // logger.error(fe.getMessage(), fe); //} } private void putWarnCookieIfRequestParameterPresent(HttpContext context) { HttpResponse response = WebUtils.getHttpServletResponse(context); if (!string.IsNullOrEmpty(context.Request["warn"])) { this._warnCookieGenerator.addCookie(response, "true"); } else { this._warnCookieGenerator.removeCookie(response); } } private AuthenticationException getAuthenticationExceptionAsCause(TicketException e) { throw new NotImplementedException(); //return (AuthenticationException)e; } private string getAuthenticationExceptionEventId(TicketException e) { AuthenticationException authEx = this.getAuthenticationExceptionAsCause(e); //if (this.logger.isDebugEnabled()) // this.logger.debug("An authentication error has occurred. Returning the event id " + authEx.getType()); return authEx.getType(); } private bool isCauseAuthenticationException(TicketException e) { return e.getCode() != null && typeof(AuthenticationException).IsAssignableFrom(e.GetType()); } //public void setCentralAuthenticationService(CentralAuthenticationService centralAuthenticationService) //{ // this._centralAuthenticationService = centralAuthenticationService; //} /** * Set a CredentialsBinder for additional binding of the HttpRequest * to the Credentials instance, beyond our default binding of the * Credentials as a Form Object in Spring WebMVC parlance. By the time we * invoke this CredentialsBinder, we have already engaged in default binding * such that for each HttpRequest parameter, if there was a JavaBean * property of the Credentials implementation of the same name, we have set * that property to be the value of the corresponding request parameter. * This CredentialsBinder plugin point exists to allow consideration of * things other than HttpRequest parameters in populating the * Credentials (or more sophisticated consideration of the * HttpRequest parameters). * * @param credentialsBinder the credentials binder to set. */ //public void setCredentialsBinder(CredentialsBinder credentialsBinder) //{ // this._credentialsBinder = credentialsBinder; //} //public void setWarnCookieGenerator(CookieGenerator warnCookieGenerator) //{ // this._warnCookieGenerator = warnCookieGenerator; //} } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Lucene.Net.Search { sealed class BooleanScorer : Scorer { private void InitBlock() { bucketTable = new BucketTable(); } private SubScorer scorers = null; private BucketTable bucketTable; private int maxCoord = 1; private float[] coordFactors = null; private int requiredMask = 0; private int prohibitedMask = 0; private int nextMask = 1; private int minNrShouldMatch; internal BooleanScorer(Similarity similarity) : this(similarity, 1) { } internal BooleanScorer(Similarity similarity, int minNrShouldMatch) : base(similarity) { InitBlock(); this.minNrShouldMatch = minNrShouldMatch; } internal sealed class SubScorer { public Scorer scorer; public bool done; public bool required = false; public bool prohibited = false; public HitCollector collector; public SubScorer next; public SubScorer(Scorer scorer, bool required, bool prohibited, HitCollector collector, SubScorer next) { this.scorer = scorer; this.done = !scorer.Next(); this.required = required; this.prohibited = prohibited; this.collector = collector; this.next = next; } } internal void Add(Scorer scorer, bool required, bool prohibited) { int mask = 0; if (required || prohibited) { if (nextMask == 0) throw new System.IndexOutOfRangeException("More than 32 required/prohibited clauses in query."); mask = nextMask; nextMask = nextMask << 1; } else mask = 0; if (!prohibited) maxCoord++; if (prohibited) prohibitedMask |= mask; // update prohibited mask else if (required) requiredMask |= mask; // update required mask scorers = new SubScorer(scorer, required, prohibited, bucketTable.NewCollector(mask), scorers); } private void ComputeCoordFactors() { coordFactors = new float[maxCoord]; for (int i = 0; i < maxCoord; i++) coordFactors[i] = GetSimilarity().Coord(i, maxCoord - 1); } private int end; private Bucket current; public override void Score(HitCollector hc) { Next(); Score(hc, System.Int32.MaxValue); } protected internal override bool Score(HitCollector hc, int max) { if (coordFactors == null) ComputeCoordFactors(); bool more; Bucket tmp; do { bucketTable.first = null; while (current != null) { // more queued // check prohibited & required if ((current.bits & prohibitedMask) == 0 && (current.bits & requiredMask) == requiredMask) { if (current.doc >= max) { tmp = current; current = current.next; tmp.next = bucketTable.first; bucketTable.first = tmp; continue; } if (current.coord >= minNrShouldMatch) { hc.Collect(current.doc, current.score * coordFactors[current.coord]); } } current = current.next; // pop the queue } if (bucketTable.first != null) { current = bucketTable.first; bucketTable.first = current.next; return true; } // refill the queue more = false; end += BucketTable.SIZE; for (SubScorer sub = scorers; sub != null; sub = sub.next) { if (!sub.done) { sub.done = !sub.scorer.Score(sub.collector, end); if (!sub.done) more = true; } } current = bucketTable.first; } while (current != null || more); return false; } public override int Doc() { return current.doc; } public override bool Next() { bool more; do { while (bucketTable.first != null) { // more queued current = bucketTable.first; bucketTable.first = current.next; // pop the queue // check prohibited & required, and minNrShouldMatch if ((current.bits & prohibitedMask) == 0 && (current.bits & requiredMask) == requiredMask && current.coord >= minNrShouldMatch) { return true; } } // refill the queue more = false; end += BucketTable.SIZE; for (SubScorer sub = scorers; sub != null; sub = sub.next) { Scorer scorer = sub.scorer; while (!sub.done && scorer.Doc() < end) { sub.collector.Collect(scorer.Doc(), scorer.Score()); sub.done = !scorer.Next(); } if (!sub.done) { more = true; } } } while (bucketTable.first != null || more); return false; } public override float Score() { if (coordFactors == null) ComputeCoordFactors(); return current.score * coordFactors[current.coord]; } internal sealed class Bucket { internal int doc = - 1; // tells if bucket is valid internal float score; // incremental score internal int bits; // used for bool constraints internal int coord; // count of terms in score internal Bucket next; // next valid bucket } /// <summary>A simple hash table of document scores within a range. </summary> internal sealed class BucketTable { private void InitBlock() { buckets = new Bucket[SIZE]; } public const int SIZE = 1 << 11; public static readonly int MASK; internal Bucket[] buckets; internal Bucket first = null; // head of valid list public BucketTable() { InitBlock(); } public int Size() { return SIZE; } public HitCollector NewCollector(int mask) { return new Collector(mask, this); } static BucketTable() { MASK = SIZE - 1; } } internal sealed class Collector : HitCollector { private BucketTable bucketTable; private int mask; public Collector(int mask, BucketTable bucketTable) { this.mask = mask; this.bucketTable = bucketTable; } public override void Collect(int doc, float score) { BucketTable table = bucketTable; int i = doc & Lucene.Net.Search.BooleanScorer.BucketTable.MASK; Bucket bucket = table.buckets[i]; if (bucket == null) table.buckets[i] = bucket = new Bucket(); if (bucket.doc != doc) { // invalid bucket bucket.doc = doc; // set doc bucket.score = score; // initialize score bucket.bits = mask; // initialize mask bucket.coord = 1; // initialize coord bucket.next = table.first; // push onto valid list table.first = bucket; } else { // valid bucket bucket.score += score; // increment score bucket.bits |= mask; // add bits in mask bucket.coord++; // increment coord } } } public override bool SkipTo(int target) { throw new System.NotSupportedException(); } public override Explanation Explain(int doc) { throw new System.NotSupportedException(); } public override System.String ToString() { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); buffer.Append("boolean("); for (SubScorer sub = scorers; sub != null; sub = sub.next) { buffer.Append(sub.scorer.ToString()); buffer.Append(" "); } buffer.Append(")"); return buffer.ToString(); } } }
/* ==================================================================== 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 NPOI.HSSF.Record.Aggregates { using System; using System.Collections; using NPOI.HSSF.Model; using NPOI.HSSF.Record; using NPOI.SS.UserModel; using NPOI.Util; using System.Collections.Generic; /** * Groups the page settings records for a worksheet.<p/> * * See OOO excelfileformat.pdf sec 4.4 'Page Settings Block' * * @author Josh Micich */ public class PageSettingsBlock : RecordAggregate { // Every one of these component records is optional // (The whole PageSettingsBlock may not be present) private PageBreakRecord _rowBreaksRecord; private PageBreakRecord _columnBreaksRecord; private HeaderRecord header; private FooterRecord footer; private HCenterRecord _hCenter; private VCenterRecord _vCenter; private LeftMarginRecord _leftMargin; private RightMarginRecord _rightMargin; private TopMarginRecord _topMargin; private BottomMarginRecord _bottomMargin; // fix warning CS0169 "never used": private Record _pls; private PrintSetupRecord printSetup; private Record _bitmap; private HeaderFooterRecord _headerFooter; private List<HeaderFooterRecord> _sviewHeaderFooters = new List<HeaderFooterRecord>(); private List<PLSAggregate> _plsRecords; private Record _printSize; public PageSettingsBlock(RecordStream rs) { _plsRecords = new List<PLSAggregate>(); while (ReadARecord(rs)) ; } /** * Creates a PageSettingsBlock with default settings */ public PageSettingsBlock() { _plsRecords = new List<PLSAggregate>(); _rowBreaksRecord = new HorizontalPageBreakRecord(); _columnBreaksRecord = new VerticalPageBreakRecord(); header = new HeaderRecord(string.Empty); footer = new FooterRecord(string.Empty); _hCenter = CreateHCenter(); _vCenter = CreateVCenter(); printSetup = CreatePrintSetup(); } /** * @return <c>true</c> if the specified Record sid is one belonging to the * 'Page Settings Block'. */ public static bool IsComponentRecord(int sid) { switch (sid) { case HorizontalPageBreakRecord.sid: case VerticalPageBreakRecord.sid: case HeaderRecord.sid: case FooterRecord.sid: case HCenterRecord.sid: case VCenterRecord.sid: case LeftMarginRecord.sid: case RightMarginRecord.sid: case TopMarginRecord.sid: case BottomMarginRecord.sid: case UnknownRecord.PLS_004D: case PrintSetupRecord.sid: case UnknownRecord.BITMAP_00E9: //case UnknownRecord.PRINTSIZE_0033: case PrintSizeRecord.sid: case HeaderFooterRecord.sid: // extra header/footer settings supported by Excel 2007 return true; } return false; } private bool ReadARecord(RecordStream rs) { switch (rs.PeekNextSid()) { case HorizontalPageBreakRecord.sid: CheckNotPresent(_rowBreaksRecord); _rowBreaksRecord = (PageBreakRecord)rs.GetNext(); break; case VerticalPageBreakRecord.sid: CheckNotPresent(_columnBreaksRecord); _columnBreaksRecord = (PageBreakRecord)rs.GetNext(); break; case HeaderRecord.sid: CheckNotPresent(header); header = (HeaderRecord)rs.GetNext(); break; case FooterRecord.sid: CheckNotPresent(footer); footer = (FooterRecord)rs.GetNext(); break; case HCenterRecord.sid: CheckNotPresent(_hCenter); _hCenter = (HCenterRecord)rs.GetNext(); break; case VCenterRecord.sid: CheckNotPresent(_vCenter); _vCenter = (VCenterRecord)rs.GetNext(); break; case LeftMarginRecord.sid: CheckNotPresent(_leftMargin); _leftMargin = (LeftMarginRecord)rs.GetNext(); break; case RightMarginRecord.sid: CheckNotPresent(_rightMargin); _rightMargin = (RightMarginRecord)rs.GetNext(); break; case TopMarginRecord.sid: CheckNotPresent(_topMargin); _topMargin = (TopMarginRecord)rs.GetNext(); break; case BottomMarginRecord.sid: CheckNotPresent(_bottomMargin); _bottomMargin = (BottomMarginRecord)rs.GetNext(); break; case UnknownRecord.PLS_004D: // PLS _plsRecords.Add(new PLSAggregate(rs)); break; case PrintSetupRecord.sid: CheckNotPresent(printSetup); printSetup = (PrintSetupRecord)rs.GetNext(); break; case UnknownRecord.BITMAP_00E9: // BITMAP CheckNotPresent(_bitmap); _bitmap = rs.GetNext(); break; case PrintSizeRecord.sid: CheckNotPresent(_printSize); _printSize = rs.GetNext(); break; case HeaderFooterRecord.sid: HeaderFooterRecord hf = (HeaderFooterRecord)rs.GetNext(); if (hf.IsCurrentSheet) _headerFooter = hf; else _sviewHeaderFooters.Add(hf); break; default: // all other record types are not part of the PageSettingsBlock return false; } return true; } private void CheckNotPresent(Record rec) { if (rec != null) { throw new RecordFormatException("Duplicate PageSettingsBlock record (sid=0x" + StringUtil.ToHexString(rec.Sid) + ")"); } } private PageBreakRecord RowBreaksRecord { get { if (_rowBreaksRecord == null) { _rowBreaksRecord = new HorizontalPageBreakRecord(); } return _rowBreaksRecord; } } private PageBreakRecord ColumnBreaksRecord { get { if (_columnBreaksRecord == null) { _columnBreaksRecord = new VerticalPageBreakRecord(); } return _columnBreaksRecord; } } public IEnumerator GetEnumerator() { return _plsRecords.GetEnumerator(); } /** * Sets a page break at the indicated column * */ public void SetColumnBreak(int column, int fromRow, int toRow) { this.ColumnBreaksRecord.AddBreak(column, fromRow, toRow); } /** * Removes a page break at the indicated column * */ public void RemoveColumnBreak(int column) { this.ColumnBreaksRecord.RemoveBreak(column); } public override void VisitContainedRecords(RecordVisitor rv) { VisitIfPresent(_rowBreaksRecord, rv); VisitIfPresent(_columnBreaksRecord, rv); // Write out empty header / footer records if these are missing if (header == null) { rv.VisitRecord(new HeaderRecord("")); } else { rv.VisitRecord(header); } if (footer == null) { rv.VisitRecord(new FooterRecord("")); } else { rv.VisitRecord(footer); } VisitIfPresent(_hCenter, rv); VisitIfPresent(_vCenter, rv); VisitIfPresent(_leftMargin, rv); VisitIfPresent(_rightMargin, rv); VisitIfPresent(_topMargin, rv); VisitIfPresent(_bottomMargin, rv); foreach (RecordAggregate pls in _plsRecords) { pls.VisitContainedRecords(rv); } VisitIfPresent(printSetup, rv); VisitIfPresent(_printSize, rv); VisitIfPresent(_headerFooter, rv); VisitIfPresent(_bitmap, rv); } private static void VisitIfPresent(Record r, RecordVisitor rv) { if (r != null) { rv.VisitRecord(r); } } private static void VisitIfPresent(PageBreakRecord r, RecordVisitor rv) { if (r != null) { if (r.IsEmpty) { // its OK to not serialize empty page break records return; } rv.VisitRecord(r); } } /** * Creates the HCenter Record and sets it to false (don't horizontally center) */ private static HCenterRecord CreateHCenter() { HCenterRecord retval = new HCenterRecord(); retval.HCenter = (false); return retval; } /** * Creates the VCenter Record and sets it to false (don't horizontally center) */ private static VCenterRecord CreateVCenter() { VCenterRecord retval = new VCenterRecord(); retval.VCenter = (false); return retval; } /** * Creates the PrintSetup Record and sets it to defaults and marks it invalid * @see org.apache.poi.hssf.record.PrintSetupRecord * @see org.apache.poi.hssf.record.Record * @return record containing a PrintSetupRecord */ private static PrintSetupRecord CreatePrintSetup() { PrintSetupRecord retval = new PrintSetupRecord(); retval.PaperSize = ((short)1); retval.Scale = ((short)100); retval.PageStart = ((short)1); retval.FitWidth = ((short)1); retval.FitHeight = ((short)1); retval.Options = ((short)2); retval.HResolution = ((short)300); retval.VResolution = ((short)300); retval.HeaderMargin = (0.5); retval.FooterMargin = (0.5); retval.Copies = ((short)1); return retval; } /** * Returns the HeaderRecord. * @return HeaderRecord for the sheet. */ public HeaderRecord Header { get { return header; } set { header = value; } } /** * Returns the FooterRecord. * @return FooterRecord for the sheet. */ public FooterRecord Footer { get { return footer; } set { footer = value; } } /** * Returns the PrintSetupRecord. * @return PrintSetupRecord for the sheet. */ public PrintSetupRecord PrintSetup { get { return printSetup; } set { printSetup = value; } } private IMargin GetMarginRec(MarginType margin) { switch (margin) { case MarginType.LeftMargin: return _leftMargin; case MarginType.RightMargin: return _rightMargin; case MarginType.TopMargin: return _topMargin; case MarginType.BottomMargin: return _bottomMargin; default: throw new InvalidOperationException("Unknown margin constant: " + (short)margin); } } /** * Gets the size of the margin in inches. * @param margin which margin to Get * @return the size of the margin */ public double GetMargin(MarginType margin) { IMargin m = GetMarginRec(margin); if (m != null) { return m.Margin; } else { switch (margin) { case MarginType.LeftMargin: return .75; case MarginType.RightMargin: return .75; case MarginType.TopMargin: return 1.0; case MarginType.BottomMargin: return 1.0; } throw new InvalidOperationException("Unknown margin constant: " + margin); } } /** * Sets the size of the margin in inches. * @param margin which margin to Get * @param size the size of the margin */ public void SetMargin(MarginType margin, double size) { IMargin m = GetMarginRec(margin); if (m == null) { switch (margin) { case MarginType.LeftMargin: _leftMargin = new LeftMarginRecord(); m = _leftMargin; break; case MarginType.RightMargin: _rightMargin = new RightMarginRecord(); m = _rightMargin; break; case MarginType.TopMargin: _topMargin = new TopMarginRecord(); m = _topMargin; break; case MarginType.BottomMargin: _bottomMargin = new BottomMarginRecord(); m = _bottomMargin; break; default: throw new InvalidOperationException("Unknown margin constant: " + margin); } } m.Margin= size; } /** * Shifts all the page breaks in the range "count" number of rows/columns * @param breaks The page record to be shifted * @param start Starting "main" value to shift breaks * @param stop Ending "main" value to shift breaks * @param count number of units (rows/columns) to shift by */ private static void ShiftBreaks(PageBreakRecord breaks, int start, int stop, int count) { IEnumerator iterator = breaks.GetBreaksEnumerator(); IList shiftedBreak = new ArrayList(); while(iterator.MoveNext()) { PageBreakRecord.Break breakItem = (PageBreakRecord.Break)iterator.Current; int breakLocation = breakItem.main; bool inStart = (breakLocation >= start); bool inEnd = (breakLocation <= stop); if(inStart && inEnd) shiftedBreak.Add(breakItem); } iterator = shiftedBreak.GetEnumerator(); while (iterator.MoveNext()) { PageBreakRecord.Break breakItem = (PageBreakRecord.Break)iterator.Current; breaks.RemoveBreak(breakItem.main); breaks.AddBreak((short)(breakItem.main+count), breakItem.subFrom, breakItem.subTo); } } /** * Sets a page break at the indicated row * @param row */ public void SetRowBreak(int row, short fromCol, short toCol) { this.RowBreaksRecord.AddBreak((short)row, fromCol, toCol); } /** * Removes a page break at the indicated row * @param row */ public void RemoveRowBreak(int row) { if (this.RowBreaksRecord.GetBreaks().Length < 1) throw new ArgumentException("Sheet does not define any row breaks"); this.RowBreaksRecord.RemoveBreak((short)row); } /** * Queries if the specified row has a page break * @param row * @return true if the specified row has a page break */ public bool IsRowBroken(int row) { return this.RowBreaksRecord.GetBreak(row) != null; } /** * Queries if the specified column has a page break * * @return <c>true</c> if the specified column has a page break */ public bool IsColumnBroken(int column) { return this.ColumnBreaksRecord.GetBreak(column) != null; } /** * Shifts the horizontal page breaks for the indicated count * @param startingRow * @param endingRow * @param count */ public void ShiftRowBreaks(int startingRow, int endingRow, int count) { ShiftBreaks(this.RowBreaksRecord, startingRow, endingRow, count); } /** * Shifts the vertical page breaks for the indicated count * @param startingCol * @param endingCol * @param count */ public void ShiftColumnBreaks(short startingCol, short endingCol, short count) { ShiftBreaks(this.ColumnBreaksRecord, startingCol, endingCol, count); } /** * @return all the horizontal page breaks, never <c>null</c> */ public int[] RowBreaks { get { return this.RowBreaksRecord.GetBreaks(); } } /** * @return the number of row page breaks */ public int NumRowBreaks { get { return this.RowBreaksRecord.NumBreaks; } } /** * @return all the column page breaks, never <c>null</c> */ public int[] ColumnBreaks { get { return this.ColumnBreaksRecord.GetBreaks(); } } /** * @return the number of column page breaks */ public int NumColumnBreaks { get { return this.ColumnBreaksRecord.NumBreaks; } } public VCenterRecord VCenter { get { return _vCenter; } } public HCenterRecord HCenter { get { return _hCenter; } } /// <summary> /// HEADERFOOTER is new in 2007. Some apps seem to have scattered this record long after /// the PageSettingsBlock where it belongs. /// </summary> /// <param name="rec"></param> public void AddLateHeaderFooter(HeaderFooterRecord rec) { if (_headerFooter != null) { throw new ArgumentNullException("This page settings block already has a header/footer record"); } if (rec.Sid != UnknownRecord.HEADER_FOOTER_089C) { throw new RecordFormatException("Unexpected header-footer record sid: 0x" + StringUtil.ToHexString(rec.Sid)); } _headerFooter = rec; } /// <summary> /// This method reads PageSettingsBlock records from the supplied RecordStream until the first non-PageSettingsBlock record is encountered. /// As each record is read, it is incorporated into this PageSettingsBlock. /// </summary> /// <param name="rs"></param> public void AddLateRecords(RecordStream rs) { while (true) { if (!ReadARecord(rs)) { break; } } } public void PositionRecords(List<RecordBase> sheetRecords) { // Take a copy to loop over, so we can update the real one // without concurrency issues List<HeaderFooterRecord> hfRecordsToIterate = new List<HeaderFooterRecord>(_sviewHeaderFooters); Dictionary<String, HeaderFooterRecord> hfGuidMap = new Dictionary<String, HeaderFooterRecord>(); foreach (HeaderFooterRecord hf in hfRecordsToIterate) { string key = HexDump.ToHex(hf.Guid); if (hfGuidMap.ContainsKey(key)) hfGuidMap[key] = hf; else hfGuidMap.Add(HexDump.ToHex(hf.Guid), hf); } // loop through HeaderFooterRecord records having not-empty GUID and match them with // CustomViewSettingsRecordAggregate blocks having UserSViewBegin with the same GUID foreach (HeaderFooterRecord hf in hfRecordsToIterate) { foreach (RecordBase rb in sheetRecords) { if (rb is CustomViewSettingsRecordAggregate) { CustomViewSettingsRecordAggregate cv = (CustomViewSettingsRecordAggregate)rb; cv.VisitContainedRecords(new CustomRecordVisitor1(cv,hf,_sviewHeaderFooters,hfGuidMap)); } } } } private class CustomRecordVisitor1 : RecordVisitor { CustomViewSettingsRecordAggregate _cv; HeaderFooterRecord _hf; List<HeaderFooterRecord> _sviewHeaderFooters; Dictionary<String, HeaderFooterRecord> _hfGuidMap; public CustomRecordVisitor1(CustomViewSettingsRecordAggregate cv, HeaderFooterRecord hf, List<HeaderFooterRecord> sviewHeaderFooter, Dictionary<String, HeaderFooterRecord> hfGuidMap) { this._cv = cv; this._hf = hf; this._sviewHeaderFooters = sviewHeaderFooter; _hfGuidMap = hfGuidMap; } #region RecordVisitor Members public void VisitRecord(Record r) { if (r.Sid == UserSViewBegin.sid) { String guid = HexDump.ToHex(((UserSViewBegin) r).Guid); HeaderFooterRecord hf = _hfGuidMap[guid]; if (hf != null) { { _cv.Append(_hf); _sviewHeaderFooters.Remove(_hf); } } } } #endregion } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Printing; using System.Windows.Forms; namespace Factotum { // An instance of this class is created when the user selects to print an inspected component. // The object is maintained throughout the printing process. Each time a PrintPage event is received, // the report object's OutputToGraphics method is called with the event's arguments, more report data // is painted to the graphics, and the HasMorePages property of the graphics is set. // Each time the QueryPageSettings event is received (just before the PrintPage event), // the NextPageLandscape property of the report object is checked and the page orientation set // accordingly. This property will only be set by the report object if the next page(s) will contain // a very wide grid. class MainReport { // These objects are loaded in the constructor public EInspectedComponent eInspectedComponent; public EComponent eComponent; public EUnit eUnit; public EOutage eOutage; public EInspectorCollection eInspectors; // If the Inspected component has at least one inspection, the collection is filled in the constructor public EInspectionCollection eInspections; public int curInspectionIdx; public EInspection eInspection; // the current inspection // If the Inspection has at least one dataset, the collection is filled in the constructor public EDsetCollection eDsets; public int curDsetIdx; public EDset eDset; // the current dataset public EGraphic eGraphic; public EGrid eGrid; // As we output report data to a provided graphic object, we increment curReportSection // each time we finish a section. We increment curRow and curCol each time we output // part of a section. We reset them to zero when a section is complete. If a section is broken // across pages, we use curRow and curCol to figure out how to pick up where we left off. // curCol would only be non-zero after a page break if we were printing a grid with more columns than // would fit on a page. private ReportSectionEnum curReportSection; public bool nextPageLandscape; private PrintDocument printDocument = null; public Font titleFont; public Font bigTextFont; public Font smallTextFont; public Font regTextFont; public Font boldRegTextFont; public Font boldSmallTextFont; public Font italicTextFont; public int footerHeight; private int footerRowPadding; public int curPageNumber; private string[,] signerInfo; private int signers; private ReportSection[] sections; // Report constructor public MainReport(Guid InspectedComponentID) { // Assemble the source data for the report eInspectedComponent = new EInspectedComponent(InspectedComponentID); eComponent = new EComponent(eInspectedComponent.InspComponentCmpID); eInspections = EInspection.ListByReportOrderForInspectedComponent( (Guid)eInspectedComponent.ID, false); eUnit = new EUnit(eComponent.ComponentUntID); eOutage = new EOutage(eInspectedComponent.InspComponentOtgID); eInspectors = EInspector.ListForInspectedComponent((Guid)eInspectedComponent.ID,true); // Use this for the report title only titleFont = new Font("Times New Roman",14); // Used for site/unit, outage, rept#, insp date, ut proc, grid proc bigTextFont = new Font("Times New Roman",12); // Not currently used smallTextFont = new Font("Times New Roman", 8); // Used for all other text exept headings and footnotes regTextFont = new Font("Times New Roman", 9); // Used for headings boldRegTextFont = new Font(regTextFont, FontStyle.Bold); boldSmallTextFont = new Font(smallTextFont, FontStyle.Bold); // Used for footnotes italicTextFont = new Font(regTextFont, FontStyle.Italic); ResetReport(); printDocument = new PrintDocument(); // Setup the footer data. This method will set the footerHeight and footerY // and also initialize the footerData array. SetupFooter(); // Wire up the event handlers printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage); printDocument.QueryPageSettings += new QueryPageSettingsEventHandler(printDocument_QueryPageSettings); } private void ResetReport() { // Get data for the current inspection if (eInspections.Count > 0) { curInspectionIdx = 0; eInspection = eInspections.Count == 0 ? null : eInspections[curInspectionIdx]; curDsetIdx = 0; if (eInspection != null) { if (eInspection.GraphicID != null) eGraphic = new EGraphic(eInspection.GraphicID); if (eInspection.GridID != null) eGrid = new EGrid(eInspection.GridID); eDsets = EDset.ListByNameForInspection((Guid)eInspection.ID); eDset = eDsets.Count == 0 ? null : eDsets[curDsetIdx]; } } // Initialize the report sections InitializeReportSections(); // Set the current report section to the report heading curReportSection = ReportSectionEnum.Heading; nextPageLandscape = false; curPageNumber = 1; } public void SetupFooter() { EInspector reviewer = null; if (eInspectedComponent.InspComponentInsID != null) reviewer = new EInspector(eInspectedComponent.InspComponentInsID); this.signers = eInspectors.Count + (reviewer == null ? 0 : 1); this.signerInfo = new string[this.signers, 3]; int idx = 0; foreach (EInspector inspector in eInspectors) { signerInfo[idx, 0] = "Inspector # " + (idx+1); signerInfo[idx, 1] = inspector.InspectorName; signerInfo[idx, 2] = inspector.InspectorLevelString; idx++; } if (reviewer != null) { signerInfo[idx, 0] = "Reviewer:"; signerInfo[idx, 1] = reviewer.InspectorName; signerInfo[idx, 2] = reviewer.InspectorLevelString; } footerRowPadding = 20; this.footerHeight = (this.signers) * (regTextFont.Height + footerRowPadding) + regTextFont.Height*2; } // Optionally print a hardcopy of the report or show a preview of it. public void Print(bool hardcopy) { // create a PrintDialog based on the PrintDocument PrintDialog pdlg = new PrintDialog(); pdlg.Document = printDocument; // show the PrintDialog if (pdlg.ShowDialog() == DialogResult.OK) { // decide what action to take if (hardcopy) { // actually print hardcopy printDocument.Print(); } else { // preview onscreen instead PrintPreviewDialog prvw = new PrintPreviewDialog(); prvw.Document = printDocument; prvw.ShowDialog(); } } } void printDocument_QueryPageSettings(object sender, QueryPageSettingsEventArgs e) { // Get the default page settings for the current printer and set the margins // Try changing the bottom margin to help with goofy old printer... e.PageSettings.Margins = new Margins(50, 50, 50, 75); // Ask the current report if the next page to be printed needs to be landscape. e.PageSettings.Landscape = nextPageLandscape; } // Get the next report section, while managing collection indices. // It's ok if we return a section that isn't actually included, because the // function that's calling us is doing so from a loop where that's being checked. ReportSection GetNextSection() { ReportSection section; // Increment the current report section curReportSection++; // Now find the next section to include while (curReportSection != ReportSectionEnum.None) { section = sections[(int)curReportSection]; if (section.IsIncluded()) break; curReportSection++; } // If we've reached the end, we need to check first for more datasets, then // more inspections. if (curReportSection == ReportSectionEnum.None) { if (eInspections == null) { // No inspections, so just leave it at section none. We're done. return null; } else if (curInspectionIdx < eInspections.Count) { if (eDsets != null && curDsetIdx < eDsets.Count - 1) { // If the current inspection has more datasets, go back to do the next // instrument section. curDsetIdx++; eDset = eDsets[curDsetIdx]; curReportSection = ReportSectionEnum.Instrument; } else if (curInspectionIdx < eInspections.Count - 1) { // The current inspection has no more datasets, but we have more inspections curInspectionIdx++; eInspection = eInspections[curInspectionIdx]; if (eInspection.GraphicID != null) eGraphic = new EGraphic(eInspection.GraphicID); if (eInspection.GridID != null) eGrid = new EGrid(eInspection.GridID); // Re-Initialize the report sections InitializeReportSections(); eDsets = EDset.ListByNameForInspection((Guid)eInspection.ID); curDsetIdx = 0; if (eDsets.Count > 0) eDset = eDsets[curDsetIdx]; else eDset = null; curReportSection = ReportSectionEnum.InspectionHeading; } // else just leave it at section none. } } if (curReportSection != ReportSectionEnum.None) { return sections[(int)curReportSection]; } return null; } // Print report sections until we're finished or can't fit any more on the page void printDocument_PrintPage(object sender, PrintPageEventArgs e) { Graphics g = e.Graphics; Graphics measure = e.PageSettings.PrinterSettings.CreateMeasurementGraphics(); Rectangle marginBounds = e.MarginBounds; float curX = marginBounds.X; float curY = marginBounds.Y; bool sectionDone = false; bool reportDone = false; bool nextSectionFits = true; ReportSection section = sections[(int)curReportSection]; // Print report sections until we can't fit any more while (nextSectionFits) { // Print whatever will fit, picking up where we left off if we're continuing from the prev. page // The print method returns true once all is printed. sectionDone = section.Print(e, curY); if (sectionDone) { // Set the Y coord for the page to the section's Y coord. curY = section.Y; } else { // If we weren't able to finish the section, break out of the loop break; } // Get the next section that needs to be displayed section = GetNextSection(); while (curReportSection != ReportSectionEnum.None && !section.IsIncluded()) section = GetNextSection(); if (curReportSection == ReportSectionEnum.None) { // No more inspections -- we're really done! reportDone = true; break; } // Check whether some or all of the current section can fit on the page // If the current section is the Inspection heading and this is not the first // inspection, we always start a new page. nextSectionFits = !(curReportSection == ReportSectionEnum.InspectionHeading && curInspectionIdx > 0) && section.CanFitSome(e, curY); } // Print the page footer PrintFooter(e); e.HasMorePages = (!reportDone); if (reportDone) { // Reset some report variables (in case the user prints from preview mode) ResetReport(); } else { curPageNumber++; } } // Print the footer bool PrintFooter(PrintPageEventArgs args) { Graphics g = args.Graphics; Graphics measure = args.PageSettings.PrinterSettings.CreateMeasurementGraphics(); int leftX = args.MarginBounds.X; int centerX = (int)(leftX + args.MarginBounds.Width / 2); int rightX = leftX + args.MarginBounds.Width; float curX = leftX; Font curFont = regTextFont; float curY = args.MarginBounds.Bottom - this.footerHeight + curFont.Height; float startY = curY; string s; int padding = 5; // SIGNERS for (int i = 0; i < signers; i++) { curX = leftX; g.DrawString(signerInfo[i, 0], curFont, Brushes.Black, new Point((int)curX, (int)curY)); curX += 75; s = Chop(measure, curFont, signerInfo[i, 1], 175); g.DrawString(s, curFont, Brushes.Black, curX, curY); curX += 175; g.DrawString(signerInfo[i, 2], curFont, Brushes.Black, new Point((int)curX, (int)curY)); curX += 50; g.DrawLine(Pens.Black, curX, curY + curFont.Height, curX + 200, curY + curFont.Height); curX += 200 + padding * 4; g.DrawString("Date:", curFont, Brushes.Black, curX, curY); curX += 40; g.DrawLine(Pens.Black, curX, curY + curFont.Height, curX + 150, curY + curFont.Height); curY += curFont.Height + footerRowPadding; } curX = leftX; // Date/time g.DrawString("Printed: " + DateTime.Now, curFont, Brushes.Black, curX, curY); // Component ID s = "Component ID: " + eComponent.ComponentName; SizeF siz = measure.MeasureString(s, curFont); curX = centerX - siz.Width / 2; g.DrawString(s, curFont, Brushes.Black, curX, curY); s = String.Format("Page {0}", curPageNumber) + (eInspectedComponent.InspComponentPageCountOverride == null ? "" : String.Format(" of {0}", eInspectedComponent.InspComponentPageCountOverride)); // Page # siz = measure.MeasureString(s, curFont); curX = rightX - siz.Width; g.DrawString(s, curFont, Brushes.Black, curX, curY); return true; } // Truncate a string unless it fits in the specified width public string Chop(Graphics measure, Font fnt, string s, float width) { int charsFit; int linesFit; string cs = s; StringFormat format = new StringFormat(StringFormatFlags.FitBlackBox | StringFormatFlags.LineLimit); measure.MeasureString(s, fnt, new SizeF(width, fnt.Height*1.5f), format, out charsFit, out linesFit); if (charsFit < s.Length) cs = s.Substring(0, charsFit - 3) + "..."; return cs; } // Fill the array of report section rules. private void InitializeReportSections() { sections = new ReportSection[] { // these first three sections are only on the first page, near the top, so they're easy new RsHeading(this, new ReportSectionRules(ReportSectionEnum.Heading, PageForceMode.UnlessAllFits, 0),3), new RsCmpDefinition(this, new ReportSectionRules(ReportSectionEnum.CmpDefinition, PageForceMode.UnlessAllFits, 0),3), new RsCmpDetails(this, new ReportSectionRules(ReportSectionEnum.CmpDetails, PageForceMode.UnlessAllFits, 0),2), // The Inspection heading section always starts a new page, except if it falls on the first page. // It is not allowed to break. new RsInspectionHeading(this, new ReportSectionRules(ReportSectionEnum.InspectionHeading, PageForceMode.AlwaysExcept1stPage, 0),2), // The Graphic/Notes section always follows the inspection heading, so the graphic should // always fit. The text may be longer than the graphic and may break if needed. new RsGraphicNotes(this, new ReportSectionRules(ReportSectionEnum.GraphicNotes, PageForceMode.UnlessMinRowsAnyPage, 0),2), // The Statistics and Nongrid measurements section can break, but unless we can fit 4 lines // we'll put it on the next page new RsStatsAndNonGrid(this, new ReportSectionRules(ReportSectionEnum.StatsAndNonGrid, PageForceMode.UnlessMinRowsAnyPage, 4),2), // The partition info section isn't allowed to break. new RsPartition(this, new ReportSectionRules(ReportSectionEnum.Partition, PageForceMode.UnlessAllFits, 0), 3), // The grid can break, but unless we can fit the whole thing, we'll put it on the next page new RsGrid(this, new ReportSectionRules(ReportSectionEnum.Grid, PageForceMode.UnlessMinRowsAnyPage, 4), 1), // The next three sections aren't allowed to break (although the CalData section is several rows. new RsLegend(this, new ReportSectionRules(ReportSectionEnum.CrewDoseAndLegend, PageForceMode.UnlessAllFits, 0), 2), new RsInstrument(this, new ReportSectionRules(ReportSectionEnum.Instrument, PageForceMode.UnlessAllFits, 0),3), new RsCalData(this, new ReportSectionRules(ReportSectionEnum.CalData, PageForceMode.UnlessAllFits, 0),3) }; } } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using ZXing.Common; namespace ZXing.QrCode.Internal { /// <summary> /// /// </summary> /// <author> /// [email protected] (Satoru Takabayashi) - creator /// </author> public static class MatrixUtil { private static readonly int[][] POSITION_DETECTION_PATTERN = new int[][] { new int[] {1, 1, 1, 1, 1, 1, 1}, new int[] {1, 0, 0, 0, 0, 0, 1}, new int[] {1, 0, 1, 1, 1, 0, 1}, new int[] {1, 0, 1, 1, 1, 0, 1}, new int[] {1, 0, 1, 1, 1, 0, 1}, new int[] {1, 0, 0, 0, 0, 0, 1}, new int[] {1, 1, 1, 1, 1, 1, 1} }; private static readonly int[][] POSITION_ADJUSTMENT_PATTERN = new int[][] { new int[] {1, 1, 1, 1, 1}, new int[] {1, 0, 0, 0, 1}, new int[] {1, 0, 1, 0, 1}, new int[] {1, 0, 0, 0, 1}, new int[] {1, 1, 1, 1, 1} }; // From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu. private static readonly int[][] POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = new int[][] { new int[] {-1, -1, -1, -1, -1, -1, -1}, new int[] {6, 18, -1, -1, -1, -1, -1}, new int[] {6, 22, -1, -1, -1, -1, -1}, new int[] {6, 26, -1, -1, -1, -1, -1}, new int[] {6, 30, -1, -1, -1, -1, -1}, new int[] {6, 34, -1, -1, -1, -1, -1}, new int[] {6, 22, 38, -1, -1, -1, -1}, new int[] {6, 24, 42, -1, -1, -1, -1}, new int[] {6, 26, 46, -1, -1, -1, -1}, new int[] {6, 28, 50, -1, -1, -1, -1}, new int[] {6, 30, 54, -1, -1, -1, -1}, new int[] {6, 32, 58, -1, -1, -1, -1}, new int[] {6, 34, 62, -1, -1, -1, -1}, new int[] {6, 26, 46, 66, -1, -1, -1}, new int[] {6, 26, 48, 70, -1, -1, -1}, new int[] {6, 26, 50, 74, -1, -1, -1}, new int[] {6, 30, 54, 78, -1, -1, -1}, new int[] {6, 30, 56, 82, -1, -1, -1}, new int[] {6, 30, 58, 86, -1, -1, -1}, new int[] {6, 34, 62, 90, -1, -1, -1}, new int[] {6, 28, 50, 72, 94, -1, -1}, new int[] {6, 26, 50, 74, 98, -1, -1}, new int[] {6, 30, 54, 78, 102, -1, -1}, new int[] {6, 28, 54, 80, 106, -1, -1}, new int[] {6, 32, 58, 84, 110, -1, -1}, new int[] {6, 30, 58, 86, 114, -1, -1}, new int[] {6, 34, 62, 90, 118, -1, -1}, new int[] {6, 26, 50, 74, 98, 122, -1}, new int[] {6, 30, 54, 78, 102, 126, -1}, new int[] {6, 26, 52, 78, 104, 130, -1}, new int[] {6, 30, 56, 82, 108, 134, -1}, new int[] {6, 34, 60, 86, 112, 138, -1}, new int[] {6, 30, 58, 86, 114, 142, -1}, new int[] {6, 34, 62, 90, 118, 146, -1}, new int[] {6, 30, 54, 78, 102, 126, 150}, new int[] {6, 24, 50, 76, 102, 128, 154}, new int[] {6, 28, 54, 80, 106, 132, 158}, new int[] {6, 32, 58, 84, 110, 136, 162}, new int[] {6, 26, 54, 82, 110, 138, 166}, new int[] {6, 30, 58, 86, 114, 142, 170} }; // Type info cells at the left top corner. private static readonly int[][] TYPE_INFO_COORDINATES = new int[][] { new int[] {8, 0}, new int[] {8, 1}, new int[] {8, 2}, new int[] {8, 3}, new int[] {8, 4}, new int[] {8, 5}, new int[] {8, 7}, new int[] {8, 8}, new int[] {7, 8}, new int[] {5, 8}, new int[] {4, 8}, new int[] {3, 8}, new int[] {2, 8}, new int[] {1, 8}, new int[] {0, 8} }; // From Appendix D in JISX0510:2004 (p. 67) private const int VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101 // From Appendix C in JISX0510:2004 (p.65). private const int TYPE_INFO_POLY = 0x537; private const int TYPE_INFO_MASK_PATTERN = 0x5412; /// <summary> /// Set all cells to 2. 2 means that the cell is empty (not set yet). /// /// JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding /// with the ByteMatrix initialized all to zero. /// </summary> /// <param name="matrix">The matrix.</param> public static void clearMatrix(ByteMatrix matrix) { matrix.clear(2); } /// <summary> /// Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On /// success, store the result in "matrix" and return true. /// </summary> /// <param name="dataBits">The data bits.</param> /// <param name="ecLevel">The ec level.</param> /// <param name="version">The version.</param> /// <param name="maskPattern">The mask pattern.</param> /// <param name="matrix">The matrix.</param> public static void buildMatrix(BitArray dataBits, ErrorCorrectionLevel ecLevel, Version version, int maskPattern, ByteMatrix matrix) { clearMatrix(matrix); embedBasicPatterns(version, matrix); // Type information appear with any version. embedTypeInfo(ecLevel, maskPattern, matrix); // Version info appear if version >= 7. maybeEmbedVersionInfo(version, matrix); // Data should be embedded at end. embedDataBits(dataBits, maskPattern, matrix); } /// <summary> /// Embed basic patterns. On success, modify the matrix and return true. /// The basic patterns are: /// - Position detection patterns /// - Timing patterns /// - Dark dot at the left bottom corner /// - Position adjustment patterns, if need be /// </summary> /// <param name="version">The version.</param> /// <param name="matrix">The matrix.</param> public static void embedBasicPatterns(Version version, ByteMatrix matrix) { // Let's get started with embedding big squares at corners. embedPositionDetectionPatternsAndSeparators(matrix); // Then, embed the dark dot at the left bottom corner. embedDarkDotAtLeftBottomCorner(matrix); // Position adjustment patterns appear if version >= 2. maybeEmbedPositionAdjustmentPatterns(version, matrix); // Timing patterns should be embedded after position adj. patterns. embedTimingPatterns(matrix); } /// <summary> /// Embed type information. On success, modify the matrix. /// </summary> /// <param name="ecLevel">The ec level.</param> /// <param name="maskPattern">The mask pattern.</param> /// <param name="matrix">The matrix.</param> public static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix) { BitArray typeInfoBits = new BitArray(); makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits); for (int i = 0; i < typeInfoBits.Size; ++i) { // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in // "typeInfoBits". int bit = typeInfoBits[typeInfoBits.Size - 1 - i] ? 1 : 0; // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46). int[] coordinates = TYPE_INFO_COORDINATES[i]; int x1 = coordinates[0]; int y1 = coordinates[1]; matrix[x1, y1] = bit; int x2; int y2; if (i < 8) { // Right top corner. x2 = matrix.Width - i - 1; y2 = 8; } else { // Left bottom corner. x2 = 8; y2 = matrix.Height - 7 + (i - 8); } matrix[x2, y2] = bit; } } /// <summary> /// Embed version information if need be. On success, modify the matrix and return true. /// See 8.10 of JISX0510:2004 (p.47) for how to embed version information. /// </summary> /// <param name="version">The version.</param> /// <param name="matrix">The matrix.</param> public static void maybeEmbedVersionInfo(Version version, ByteMatrix matrix) { if (version.VersionNumber < 7) { // Version info is necessary if version >= 7. return; // Don't need version info. } BitArray versionInfoBits = new BitArray(); makeVersionInfoBits(version, versionInfoBits); int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. for (int i = 0; i < 6; ++i) { for (int j = 0; j < 3; ++j) { // Place bits in LSB (least significant bit) to MSB order. var bit = versionInfoBits[bitIndex] ? 1 : 0; bitIndex--; // Left bottom corner. matrix[i, matrix.Height - 11 + j] = bit; // Right bottom corner. matrix[matrix.Height - 11 + j, i] = bit; } } } /// <summary> /// Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true. /// For debugging purposes, it skips masking process if "getMaskPattern" is -1. /// See 8.7 of JISX0510:2004 (p.38) for how to embed data bits. /// </summary> /// <param name="dataBits">The data bits.</param> /// <param name="maskPattern">The mask pattern.</param> /// <param name="matrix">The matrix.</param> public static void embedDataBits(BitArray dataBits, int maskPattern, ByteMatrix matrix) { int bitIndex = 0; int direction = -1; // Start from the right bottom cell. int x = matrix.Width - 1; int y = matrix.Height - 1; while (x > 0) { // Skip the vertical timing pattern. if (x == 6) { x -= 1; } while (y >= 0 && y < matrix.Height) { for (int i = 0; i < 2; ++i) { int xx = x - i; // Skip the cell if it's not empty. if (!isEmpty(matrix[xx, y])) { continue; } int bit; if (bitIndex < dataBits.Size) { bit = dataBits[bitIndex] ? 1 : 0; ++bitIndex; } else { // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described // in 8.4.9 of JISX0510:2004 (p. 24). bit = 0; } // Skip masking if mask_pattern is -1. if (maskPattern != -1) { if (MaskUtil.getDataMaskBit(maskPattern, xx, y)) { bit ^= 0x1; } } matrix[xx, y] = bit; } y += direction; } direction = -direction; // Reverse the direction. y += direction; x -= 2; // Move to the left. } // All bits should be consumed. if (bitIndex != dataBits.Size) { throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.Size); } } /// <summary> /// Return the position of the most significant bit set (to one) in the "value". The most /// significant bit is position 32. If there is no bit set, return 0. Examples: /// - findMSBSet(0) => 0 /// - findMSBSet(1) => 1 /// - findMSBSet(255) => 8 /// </summary> /// <param name="value_Renamed">The value_ renamed.</param> /// <returns></returns> public static int findMSBSet(int value_Renamed) { int numDigits = 0; while (value_Renamed != 0) { value_Renamed = (int)((uint)value_Renamed >> 1); ++numDigits; } return numDigits; } /// <summary> /// Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH /// code is used for encoding type information and version information. /// Example: Calculation of version information of 7. /// f(x) is created from 7. /// - 7 = 000111 in 6 bits /// - f(x) = x^2 + x^2 + x^1 /// g(x) is given by the standard (p. 67) /// - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1 /// Multiply f(x) by x^(18 - 6) /// - f'(x) = f(x) * x^(18 - 6) /// - f'(x) = x^14 + x^13 + x^12 /// Calculate the remainder of f'(x) / g(x) /// x^2 /// __________________________________________________ /// g(x) )x^14 + x^13 + x^12 /// x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2 /// -------------------------------------------------- /// x^11 + x^10 + x^7 + x^4 + x^2 /// /// The remainder is x^11 + x^10 + x^7 + x^4 + x^2 /// Encode it in binary: 110010010100 /// The return value is 0xc94 (1100 1001 0100) /// /// Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit /// operations. We don't care if coefficients are positive or negative. /// </summary> /// <param name="value">The value.</param> /// <param name="poly">The poly.</param> /// <returns></returns> public static int calculateBCHCode(int value, int poly) { if (poly == 0) throw new ArgumentException("0 polynominal", "poly"); // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 // from 13 to make it 12. int msbSetInPoly = findMSBSet(poly); value <<= msbSetInPoly - 1; // Do the division business using exclusive-or operations. while (findMSBSet(value) >= msbSetInPoly) { value ^= poly << (findMSBSet(value) - msbSetInPoly); } // Now the "value" is the remainder (i.e. the BCH code) return value; } /// <summary> /// Make bit vector of type information. On success, store the result in "bits" and return true. /// Encode error correction level and mask pattern. See 8.9 of /// JISX0510:2004 (p.45) for details. /// </summary> /// <param name="ecLevel">The ec level.</param> /// <param name="maskPattern">The mask pattern.</param> /// <param name="bits">The bits.</param> public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits) { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new WriterException("Invalid mask pattern"); } int typeInfo = (ecLevel.Bits << 3) | maskPattern; bits.appendBits(typeInfo, 5); int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); bits.appendBits(bchCode, 10); BitArray maskBits = new BitArray(); maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); bits.xor(maskBits); if (bits.Size != 15) { // Just in case. throw new WriterException("should not happen but we got: " + bits.Size); } } /// <summary> /// Make bit vector of version information. On success, store the result in "bits" and return true. /// See 8.10 of JISX0510:2004 (p.45) for details. /// </summary> /// <param name="version">The version.</param> /// <param name="bits">The bits.</param> public static void makeVersionInfoBits(Version version, BitArray bits) { bits.appendBits(version.VersionNumber, 6); int bchCode = calculateBCHCode(version.VersionNumber, VERSION_INFO_POLY); bits.appendBits(bchCode, 12); if (bits.Size != 18) { // Just in case. throw new WriterException("should not happen but we got: " + bits.Size); } } /// <summary> /// Check if "value" is empty. /// </summary> /// <param name="value">The value.</param> /// <returns> /// <c>true</c> if the specified value is empty; otherwise, <c>false</c>. /// </returns> private static bool isEmpty(int value) { return value == 2; } private static void embedTimingPatterns(ByteMatrix matrix) { // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical // separation patterns (size 1). Thus, 8 = 7 + 1. for (int i = 8; i < matrix.Width - 8; ++i) { int bit = (i + 1) % 2; // Horizontal line. if (isEmpty(matrix[i, 6])) { matrix[i, 6] = bit; } // Vertical line. if (isEmpty(matrix[6, i])) { matrix[6, i] = bit; } } } /// <summary> /// Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) /// </summary> /// <param name="matrix">The matrix.</param> private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) { if (matrix[8, matrix.Height - 8] == 0) { throw new WriterException(); } matrix[8, matrix.Height - 8] = 1; } private static void embedHorizontalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) { for (int x = 0; x < 8; ++x) { if (!isEmpty(matrix[xStart + x, yStart])) { throw new WriterException(); } matrix[xStart + x, yStart] = 0; } } private static void embedVerticalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) { for (int y = 0; y < 7; ++y) { if (!isEmpty(matrix[xStart, yStart + y])) { throw new WriterException(); } matrix[xStart, yStart + y] = 0; } } /// <summary> /// /// </summary> /// <param name="xStart">The x start.</param> /// <param name="yStart">The y start.</param> /// <param name="matrix">The matrix.</param> private static void embedPositionAdjustmentPattern(int xStart, int yStart, ByteMatrix matrix) { for (int y = 0; y < 5; ++y) { var patternY = POSITION_ADJUSTMENT_PATTERN[y]; for (int x = 0; x < 5; ++x) { matrix[xStart + x, yStart + y] = patternY[x]; } } } private static void embedPositionDetectionPattern(int xStart, int yStart, ByteMatrix matrix) { for (int y = 0; y < 7; ++y) { var patternY = POSITION_DETECTION_PATTERN[y]; for (int x = 0; x < 7; ++x) { matrix[xStart + x, yStart + y] = patternY[x]; } } } /// <summary> /// Embed position detection patterns and surrounding vertical/horizontal separators. /// </summary> /// <param name="matrix">The matrix.</param> private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) { // Embed three big squares at corners. int pdpWidth = POSITION_DETECTION_PATTERN[0].Length; // Left top corner. embedPositionDetectionPattern(0, 0, matrix); // Right top corner. embedPositionDetectionPattern(matrix.Width - pdpWidth, 0, matrix); // Left bottom corner. embedPositionDetectionPattern(0, matrix.Width - pdpWidth, matrix); // Embed horizontal separation patterns around the squares. const int hspWidth = 8; // Left top corner. embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); // Right top corner. embedHorizontalSeparationPattern(matrix.Width - hspWidth, hspWidth - 1, matrix); // Left bottom corner. embedHorizontalSeparationPattern(0, matrix.Width - hspWidth, matrix); // Embed vertical separation patterns around the squares. const int vspSize = 7; // Left top corner. embedVerticalSeparationPattern(vspSize, 0, matrix); // Right top corner. embedVerticalSeparationPattern(matrix.Height - vspSize - 1, 0, matrix); // Left bottom corner. embedVerticalSeparationPattern(vspSize, matrix.Height - vspSize, matrix); } /// <summary> /// Embed position adjustment patterns if need be. /// </summary> /// <param name="version">The version.</param> /// <param name="matrix">The matrix.</param> private static void maybeEmbedPositionAdjustmentPatterns(Version version, ByteMatrix matrix) { if (version.VersionNumber < 2) { // The patterns appear if version >= 2 return; } int index = version.VersionNumber - 1; int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index]; foreach (int y in coordinates) { if (y >= 0) { foreach (int x in coordinates) { if (x >= 0 && isEmpty(matrix[x, y])) { // If the cell is unset, we embed the position adjustment pattern here. // -2 is necessary since the x/y coordinates point to the center of the pattern, not the // left top corner. embedPositionAdjustmentPattern(x - 2, y - 2, matrix); } } } } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPersonList { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPersonList() : base() { FormClosed += frmPersonList_FormClosed; KeyDown += frmPersonList_KeyDown; Load += frmPersonList_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.Button withEventsField_cmdNew; public System.Windows.Forms.Button cmdNew { get { return withEventsField_cmdNew; } set { if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click -= cmdNew_Click; } withEventsField_cmdNew = value; if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click += cmdNew_Click; } } } private myDataGridView withEventsField_DataList1; public myDataGridView DataList1 { get { return withEventsField_DataList1; } set { if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick -= DataList1_DblClick; withEventsField_DataList1.KeyPress -= DataList1_KeyPress; } withEventsField_DataList1 = value; if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick += DataList1_DblClick; withEventsField_DataList1.KeyPress += DataList1_KeyPress; } } } private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter -= txtSearch_Enter; withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter += txtSearch_Enter; withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Label lbl; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPersonList)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.cmdNew = new System.Windows.Forms.Button(); this.DataList1 = new myDataGridView(); this.txtSearch = new System.Windows.Forms.TextBox(); this.cmdExit = new System.Windows.Forms.Button(); this.lbl = new System.Windows.Forms.Label(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Select an Employee"; this.ClientSize = new System.Drawing.Size(259, 433); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmPersonList"; this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNew.Text = "&New"; this.cmdNew.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdNew.Size = new System.Drawing.Size(97, 52); this.cmdNew.Location = new System.Drawing.Point(6, 375); this.cmdNew.TabIndex = 4; this.cmdNew.TabStop = false; this.cmdNew.BackColor = System.Drawing.SystemColors.Control; this.cmdNew.CausesValidation = true; this.cmdNew.Enabled = true; this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNew.Name = "cmdNew"; //'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State) this.DataList1.Size = new System.Drawing.Size(244, 342); this.DataList1.Location = new System.Drawing.Point(6, 26); this.DataList1.TabIndex = 2; this.DataList1.Name = "DataList1"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(199, 19); this.txtSearch.Location = new System.Drawing.Point(51, 3); this.txtSearch.TabIndex = 1; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(153, 375); this.cmdExit.TabIndex = 3; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lbl.Text = "&Search :"; this.lbl.Size = new System.Drawing.Size(40, 13); this.lbl.Location = new System.Drawing.Point(8, 6); this.lbl.TabIndex = 0; this.lbl.BackColor = System.Drawing.Color.Transparent; this.lbl.Enabled = true; this.lbl.ForeColor = System.Drawing.SystemColors.ControlText; this.lbl.Cursor = System.Windows.Forms.Cursors.Default; this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lbl.UseMnemonic = true; this.lbl.Visible = true; this.lbl.AutoSize = true; this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lbl.Name = "lbl"; this.Controls.Add(cmdNew); this.Controls.Add(DataList1); this.Controls.Add(txtSearch); this.Controls.Add(cmdExit); this.Controls.Add(lbl); ((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Globalization; using System.IO; using System.Linq; using NuGet.Common; namespace NuGet.Commands { [Command(typeof(NuGetCommand), "pack", "PackageCommandDescription", MaxArgs = 1, UsageSummaryResourceName = "PackageCommandUsageSummary", UsageDescriptionResourceName = "PackageCommandUsageDescription", UsageExampleResourceName = "PackCommandUsageExamples")] public class PackCommand : Command { internal static readonly string SymbolsExtension = ".symbols" + Constants.PackageExtension; private static readonly string[] _defaultExcludes = new[] { // Exclude previous package files @"**\*" + Constants.PackageExtension, // Exclude all files and directories that begin with "." @"**\\.**", ".**" }; // Target file paths to exclude when building the lib package for symbol server scenario private static readonly string[] _libPackageExcludes = new[] { @"**\*.pdb", @"src\**\*" }; // Target file paths to exclude when building the symbols package for symbol server scenario private static readonly string[] _symbolPackageExcludes = new[] { @"content\**\*", @"tools\**\*.ps1" }; private readonly HashSet<string> _excludes = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, string> _properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private static readonly HashSet<string> _allowedExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { Constants.ManifestExtension, ".csproj", ".vbproj", ".fsproj", ".nproj" }; private Version _minClientVersionValue; [Option(typeof(NuGetCommand), "PackageCommandOutputDirDescription")] public string OutputDirectory { get; set; } [Option(typeof(NuGetCommand), "PackageCommandBasePathDescription")] public string BasePath { get; set; } [Option(typeof(NuGetCommand), "PackageCommandVerboseDescription")] public bool Verbose { get; set; } [Option(typeof(NuGetCommand), "PackageCommandVersionDescription")] public string Version { get; set; } [Option(typeof(NuGetCommand), "PackageCommandExcludeDescription")] public ICollection<string> Exclude { get { return _excludes; } } [Option(typeof(NuGetCommand), "PackageCommandSymbolsDescription")] public bool Symbols { get; set; } [Option(typeof(NuGetCommand), "PackageCommandToolDescription")] public bool Tool { get; set; } [Option(typeof(NuGetCommand), "PackageCommandBuildDescription")] public bool Build { get; set; } [Option(typeof(NuGetCommand), "PackageCommandNoDefaultExcludes")] public bool NoDefaultExcludes { get; set; } [Option(typeof(NuGetCommand), "PackageCommandNoRunAnalysis")] public bool NoPackageAnalysis { get; set; } [Option(typeof(NuGetCommand), "PackageCommandExcludeEmptyDirectories")] public bool ExcludeEmptyDirectories { get; set; } [Option(typeof(NuGetCommand), "PackageCommandIncludeReferencedProjects")] public bool IncludeReferencedProjects { get; set; } [Option(typeof(NuGetCommand), "PackageCommandPropertiesDescription")] public Dictionary<string, string> Properties { get { return _properties; } } [Option(typeof(NuGetCommand), "PackageCommandMinClientVersion")] public string MinClientVersion { get; set; } [ImportMany] public IEnumerable<IPackageRule> Rules { get; set; } // TODO: Temporarily hide the real ConfigFile parameter from the help text. // When we fix #3230, we should remove this property. public new string ConfigFile { get; set; } public override void ExecuteCommand() { if (IncludeReferencedProjects && Symbols) { throw new CommandLineException( NuGetResources.Error_IncludeReferencedProjectsAndSymbolsNotSupported); } if (Verbose) { Console.WriteWarning(NuGetResources.Option_VerboseDeprecated); Verbosity = Verbosity.Detailed; } // Get the input file string path = GetInputFile(); Console.WriteLine(NuGetResources.PackageCommandAttemptingToBuildPackage, Path.GetFileName(path)); // If the BasePath is not specified, use the directory of the input file (nuspec / proj) file BasePath = String.IsNullOrEmpty(BasePath) ? Path.GetDirectoryName(Path.GetFullPath(path)) : BasePath; if (!String.IsNullOrEmpty(MinClientVersion)) { if (!System.Version.TryParse(MinClientVersion, out _minClientVersionValue)) { throw new CommandLineException(NuGetResources.PackageCommandInvalidMinClientVersion); } } IPackage package = BuildPackage(path); if (package != null && !NoPackageAnalysis) { AnalyzePackage(package); } } private IPackage BuildPackage(PackageBuilder builder, string outputPath = null) { if (!String.IsNullOrEmpty(Version)) { builder.Version = new SemanticVersion(Version); } if (_minClientVersionValue != null) { builder.MinClientVersion = _minClientVersionValue; } outputPath = outputPath ?? GetOutputPath(builder); ExcludeFiles(builder.Files); // Track if the package file was already present on disk bool isExistingPackage = File.Exists(outputPath); try { using (Stream stream = File.Create(outputPath)) { builder.Save(stream); } } catch { if (!isExistingPackage && File.Exists(outputPath)) { File.Delete(outputPath); } throw; } if (Verbosity == Verbosity.Detailed) { PrintVerbose(outputPath); } Console.WriteLine(NuGetResources.PackageCommandSuccess, outputPath); return new OptimizedZipPackage(outputPath); } private void PrintVerbose(string outputPath) { Console.WriteLine(); var package = new OptimizedZipPackage(outputPath); Console.WriteLine("Id: {0}", package.Id); Console.WriteLine("Version: {0}", package.Version); Console.WriteLine("Authors: {0}", String.Join(", ", package.Authors)); Console.WriteLine("Description: {0}", package.Description); if (package.LicenseUrl != null) { Console.WriteLine("License Url: {0}", package.LicenseUrl); } if (package.ProjectUrl != null) { Console.WriteLine("Project Url: {0}", package.ProjectUrl); } if (!String.IsNullOrEmpty(package.Tags)) { Console.WriteLine("Tags: {0}", package.Tags.Trim()); } if (package.DependencySets.Any()) { Console.WriteLine("Dependencies: {0}", String.Join(", ", package.DependencySets.SelectMany(d => d.Dependencies).Select(d => d.ToString()))); } else { Console.WriteLine("Dependencies: None"); } Console.WriteLine(); foreach (var file in package.GetFiles().OrderBy(p => p.Path)) { Console.WriteLine(NuGetResources.PackageCommandAddedFile, file.Path); } Console.WriteLine(); } internal void ExcludeFiles(ICollection<IPackageFile> packageFiles) { // Always exclude the nuspec file // Review: This exclusion should be done by the package builder because it knows which file would collide with the auto-generated // manifest file. var wildCards = _excludes.Concat(new[] { @"**\*" + Constants.ManifestExtension }); if (!NoDefaultExcludes) { // The user has not explicitly disabled default filtering. wildCards = wildCards.Concat(_defaultExcludes); } PathResolver.FilterPackageFiles(packageFiles, ResolvePath, wildCards); } private string ResolvePath(IPackageFile packageFile) { var physicalPackageFile = packageFile as PhysicalPackageFile; // For PhysicalPackageFiles, we want to filter by SourcePaths, the path on disk. The Path value maps to the TargetPath if (physicalPackageFile == null) { return packageFile.Path; } var path = physicalPackageFile.SourcePath; // Make sure that the basepath has a directory separator int index = path.IndexOf(BasePath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); if (index != -1) { // Since wildcards are going to be relative to the base path, remove the BasePath portion of the file's source path. // Also remove any leading path separator slashes path = path.Substring(index + BasePath.Length).TrimStart(Path.DirectorySeparatorChar); } return path; } private string GetOutputPath(PackageBuilder builder, bool symbols = false) { string version = String.IsNullOrEmpty(Version) ? builder.Version.ToString() : Version; // Output file is {id}.{version} string outputFile = builder.Id + "." + version; // If this is a source package then add .symbols.nupkg to the package file name if (symbols) { outputFile += SymbolsExtension; } else { outputFile += Constants.PackageExtension; } string outputDirectory = OutputDirectory ?? Directory.GetCurrentDirectory(); return Path.Combine(outputDirectory, outputFile); } private IPackage BuildPackage(string path) { string extension = Path.GetExtension(path); if (extension.Equals(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase)) { return BuildFromNuspec(path); } else { return BuildFromProjectFile(path); } } private IPackage BuildFromNuspec(string path) { PackageBuilder packageBuilder = CreatePackageBuilderFromNuspec(path); if (Symbols) { // remove source related files when building the lib package ExcludeFilesForLibPackage(packageBuilder.Files); if (!packageBuilder.Files.Any()) { throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageCommandNoFilesForLibPackage, path, CommandLineConstants.NuGetDocs)); } } IPackage package = BuildPackage(packageBuilder); if (Symbols) { BuildSymbolsPackage(path); } return package; } private void BuildSymbolsPackage(string path) { PackageBuilder symbolsBuilder = CreatePackageBuilderFromNuspec(path); // remove unnecessary files when building the symbols package ExcludeFilesForSymbolPackage(symbolsBuilder.Files); if (!symbolsBuilder.Files.Any()) { throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageCommandNoFilesForSymbolsPackage, path, CommandLineConstants.NuGetDocs)); } string outputPath = GetOutputPath(symbolsBuilder, symbols: true); BuildPackage(symbolsBuilder, outputPath); } internal static void ExcludeFilesForLibPackage(ICollection<IPackageFile> files) { PathResolver.FilterPackageFiles(files, file => file.Path, _libPackageExcludes); } internal static void ExcludeFilesForSymbolPackage(ICollection<IPackageFile> files) { PathResolver.FilterPackageFiles(files, file => file.Path, _symbolPackageExcludes); } private PackageBuilder CreatePackageBuilderFromNuspec(string path) { // Set the version property if the flag is set if (!String.IsNullOrEmpty(Version)) { Properties["version"] = Version; } // Initialize the property provider based on what was passed in using the properties flag var propertyProvider = new DictionaryPropertyProvider(Properties); if (String.IsNullOrEmpty(BasePath)) { return new PackageBuilder(path, propertyProvider, !ExcludeEmptyDirectories); } return new PackageBuilder(path, BasePath, propertyProvider, !ExcludeEmptyDirectories); } private IPackage BuildFromProjectFile(string path) { var factory = new ProjectFactory(path, Properties) { IsTool = Tool, Logger = Console, Build = Build, IncludeReferencedProjects = IncludeReferencedProjects }; // Add the additional Properties to the properties of the Project Factory foreach (var property in Properties) { if (factory.ProjectProperties.ContainsKey(property.Key)) { Console.WriteWarning(NuGetResources.Warning_DuplicatePropertyKey, property.Key); } factory.ProjectProperties[property.Key] = property.Value; } // Create a builder for the main package as well as the sources/symbols package PackageBuilder mainPackageBuilder = factory.CreateBuilder(BasePath); // Build the main package IPackage package = BuildPackage(mainPackageBuilder); // If we're excluding symbols then do nothing else if (!Symbols) { return package; } Console.WriteLine(); Console.WriteLine(NuGetResources.PackageCommandAttemptingToBuildSymbolsPackage, Path.GetFileName(path)); factory.IncludeSymbols = true; PackageBuilder symbolsBuilder = factory.CreateBuilder(BasePath); symbolsBuilder.Version = mainPackageBuilder.Version; // Get the file name for the sources package and build it string outputPath = GetOutputPath(symbolsBuilder, symbols: true); BuildPackage(symbolsBuilder, outputPath); // this is the real package, not the symbol package return package; } internal void AnalyzePackage(IPackage package) { IEnumerable<IPackageRule> packageRules = Rules; if (!String.IsNullOrEmpty(package.Version.SpecialVersion)) { // If a package contains a special token, we'll warn users if it does not strictly follow semver guidelines. packageRules = packageRules.Concat(new[] { new StrictSemanticVersionValidationRule() }); } IList<PackageIssue> issues = package.Validate(packageRules).OrderBy(p => p.Title, StringComparer.CurrentCulture).ToList(); if (issues.Count > 0) { Console.WriteLine(); Console.WriteWarning(NuGetResources.PackageCommandPackageIssueSummary, issues.Count, package.Id); foreach (var issue in issues) { PrintPackageIssue(issue); } } } private void PrintPackageIssue(PackageIssue issue) { Console.WriteLine(); Console.WriteWarning( prependWarningText: false, value: NuGetResources.PackageCommandIssueTitle, args: issue.Title); Console.WriteWarning( prependWarningText: false, value: NuGetResources.PackageCommandIssueDescription, args: issue.Description); if (!String.IsNullOrEmpty(issue.Solution)) { Console.WriteWarning( prependWarningText: false, value: NuGetResources.PackageCommandIssueSolution, args: issue.Solution); } } private string GetInputFile() { IEnumerable<string> files = Arguments.Any() ? Arguments : Directory.GetFiles(Directory.GetCurrentDirectory()); return GetInputFile(files); } internal static string GetInputFile(IEnumerable<string> files) { var candidates = files.Where(file => _allowedExtensions.Contains(Path.GetExtension(file))) .ToList(); switch (candidates.Count) { case 1: return candidates.Single(); case 2: // Remove all nuspec files candidates.RemoveAll(file => Path.GetExtension(file).Equals(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase)); if (candidates.Count == 1) { return candidates.Single(); } goto default; default: throw new CommandLineException(NuGetResources.PackageCommandSpecifyInputFileError); } } private class DictionaryPropertyProvider : IPropertyProvider { private readonly IDictionary<string, string> _properties; public DictionaryPropertyProvider(IDictionary<string, string> properties) { _properties = properties; } public dynamic GetPropertyValue(string propertyName) { string value; if (_properties.TryGetValue(propertyName, out value)) { return value; } return null; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Diagnostics { public partial class Process : IDisposable { /// <summary> /// Puts a Process component in state to interact with operating system processes that run in a /// special mode by enabling the native property SeDebugPrivilege on the current thread. /// </summary> public static void EnterDebugMode() { // Nop. } /// <summary> /// Takes a Process component out of the state that lets it interact with operating system processes /// that run in a special mode. /// </summary> public static void LeaveDebugMode() { // Nop. } /// <summary>Stops the associated process immediately.</summary> public void Kill() { EnsureState(State.HaveId); int errno = Interop.libc.kill(_processId, Interop.libc.Signals.SIGKILL); if (errno != 0) { throw new Win32Exception(errno); // same exception as on Windows } } /// <summary>Discards any information about the associated process.</summary> private void RefreshCore() { // Nop. No additional state to reset. } /// <summary>Additional logic invoked when the Process is closed.</summary> private void CloseCore() { if (_waitStateHolder != null) { _waitStateHolder.Dispose(); _waitStateHolder = null; } } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit. /// </summary> private bool WaitForExitCore(int milliseconds) { bool exited = GetWaitState().WaitForExit(milliseconds); Debug.Assert(exited || milliseconds != Timeout.Infinite); if (exited && milliseconds == Timeout.Infinite) // if we have a hard timeout, we cannot wait for the streams { if (_output != null) { _output.WaitUtilEOF(); } if (_error != null) { _error.WaitUtilEOF(); } } return exited; } /// <summary>Gets the main module for the associated process.</summary> public ProcessModule MainModule { get { ProcessModuleCollection pmc = Modules; return pmc.Count > 0 ? pmc[0] : null; } } /// <summary>Checks whether the process has exited and updates state accordingly.</summary> private void UpdateHasExited() { int? exitCode; _exited = GetWaitState().GetExited(out exitCode); if (_exited && exitCode != null) { _exitCode = exitCode.Value; } } /// <summary>Gets the time that the associated process exited.</summary> private DateTime ExitTimeCore { get { return GetWaitState().ExitTime; } } /// <summary> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </summary> private bool PriorityBoostEnabledCore { get { return false; } //Nop set { } // Nop } /// <summary> /// Gets or sets the overall priority category for the associated process. /// </summary> private ProcessPriorityClass PriorityClassCore { // This mapping is relatively arbitrary. 0 is normal based on the man page, // and the other values above and below are simply distributed evenly. get { EnsureState(State.HaveId); int pri = 0; int errno = Interop.libc.getpriority(Interop.libc.PriorityWhich.PRIO_PROCESS, _processId, out pri); if (errno != 0) { throw new Win32Exception(errno); // match Windows exception } Debug.Assert(pri >= -20 && pri <= 20); return pri < -15 ? ProcessPriorityClass.RealTime : pri < -10 ? ProcessPriorityClass.High : pri < -5 ? ProcessPriorityClass.AboveNormal : pri == 0 ? ProcessPriorityClass.Normal : pri <= 10 ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Idle; } set { int pri; switch (value) { case ProcessPriorityClass.RealTime: pri = -19; break; case ProcessPriorityClass.High: pri = -11; break; case ProcessPriorityClass.AboveNormal: pri = -6; break; case ProcessPriorityClass.Normal: pri = 0; break; case ProcessPriorityClass.BelowNormal: pri = 10; break; case ProcessPriorityClass.Idle: pri = 19; break; default: throw new Win32Exception(); // match Windows exception } int result = Interop.libc.setpriority(Interop.libc.PriorityWhich.PRIO_PROCESS, _processId, pri); if (result == -1) { throw new Win32Exception(); // match Windows exception } } } /// <summary>Gets the ID of the current process.</summary> private static int GetCurrentProcessId() { return Interop.libc.getpid(); } /// <summary> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle GetProcessHandle() { if (_haveProcessHandle) { if (GetWaitState().HasExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); } return _processHandle; } EnsureState(State.HaveId | State.IsLocal); return new SafeProcessHandle(_processId); } /// <summary>Starts the process using the supplied start info.</summary> /// <param name="startInfo">The start info with which to start the process.</param> private bool StartCore(ProcessStartInfo startInfo) { // Resolve the path to the specified file name string filename = ResolvePath(startInfo.FileName); // Parse argv, envp, and cwd out of the ProcessStartInfo string[] argv = CreateArgv(startInfo); string[] envp = CreateEnvp(startInfo); string cwd = !string.IsNullOrWhiteSpace(startInfo.WorkingDirectory) ? startInfo.WorkingDirectory : null; // Invoke the shim fork/execve routine. It will create pipes for all requested // redirects, fork a child process, map the pipe ends onto the appropriate stdin/stdout/stderr // descriptors, and execve to execute the requested process. The shim implementation // is used to fork/execve as executing managed code in a forked process is not safe (only // the calling thread will transfer, thread IDs aren't stable across the fork, etc.) int childPid, stdinFd, stdoutFd, stderrFd; if (Interop.Sys.ForkAndExecProcess( filename, argv, envp, cwd, startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError, out childPid, out stdinFd, out stdoutFd, out stderrFd) != 0) { throw new Win32Exception(); } // Store the child's information into this Process object. Debug.Assert(childPid >= 0); SetProcessHandle(new SafeProcessHandle(childPid)); SetProcessId(childPid); // Configure the parent's ends of the redirection streams. if (startInfo.RedirectStandardInput) { Debug.Assert(stdinFd >= 0); _standardInput = new StreamWriter(OpenStream(stdinFd, FileAccess.Write), Encoding.UTF8, StreamBufferSize) { AutoFlush = true }; } if (startInfo.RedirectStandardOutput) { Debug.Assert(stdoutFd >= 0); _standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read), startInfo.StandardOutputEncoding ?? Encoding.UTF8, true, StreamBufferSize); } if (startInfo.RedirectStandardError) { Debug.Assert(stderrFd >= 0); _standardError = new StreamReader(OpenStream(stderrFd, FileAccess.Read), startInfo.StandardErrorEncoding ?? Encoding.UTF8, true, StreamBufferSize); } return true; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Finalizable holder for the underlying shared wait state object.</summary> private ProcessWaitState.Holder _waitStateHolder; /// <summary>Size to use for redirect streams and stream readers/writers.</summary> private const int StreamBufferSize = 4096; /// <summary>Converts the filename and arguments information from a ProcessStartInfo into an argv array.</summary> /// <param name="psi">The ProcessStartInfo.</param> /// <returns>The argv array.</returns> private static string[] CreateArgv(ProcessStartInfo psi) { string argv0 = psi.FileName; // pass filename (instead of resolved path) as argv[0], to match what caller supplied if (string.IsNullOrEmpty(psi.Arguments)) { return new string[] { argv0 }; } else { var argvList = new List<string>(); argvList.Add(argv0); ParseArgumentsIntoList(psi.Arguments, argvList); return argvList.ToArray(); } } /// <summary>Converts the environment variables information from a ProcessStartInfo into an envp array.</summary> /// <param name="psi">The ProcessStartInfo.</param> /// <returns>The envp array.</returns> private static string[] CreateEnvp(ProcessStartInfo psi) { var envp = new string[psi.Environment.Count]; int index = 0; foreach (var pair in psi.Environment) { envp[index++] = pair.Key + "=" + pair.Value; } return envp; } /// <summary>Resolves a path to the filename passed to ProcessStartInfo.</summary> /// <param name="filename">The filename.</param> /// <returns>The resolved path.</returns> private static string ResolvePath(string filename) { // Follow the same resolution that Windows uses with CreateProcess: // 1. First try the exact path provided // 2. Then try the file relative to the executable directory // 3. Then try the file relative to the current directory // 4. then try the file in each of the directories specified in PATH // Windows does additional Windows-specific steps between 3 and 4, // and we ignore those here. // If the filename is a complete path, use it, regardless of whether it exists. if (Path.IsPathRooted(filename)) { // In this case, it doesn't matter whether the file exists or not; // it's what the caller asked for, so it's what they'll get return filename; } // Then check the executable's directory string path = GetExePath(); if (path != null) { try { path = Path.Combine(Path.GetDirectoryName(path), filename); if (File.Exists(path)) { return path; } } catch (ArgumentException) { } // ignore any errors in data that may come from the exe path } // Then check the current directory path = Path.Combine(Directory.GetCurrentDirectory(), filename); if (File.Exists(path)) { return path; } // Then check each directory listed in the PATH environment variables string pathEnvVar = Environment.GetEnvironmentVariable("PATH"); if (pathEnvVar != null) { var pathParser = new StringParser(pathEnvVar, ':', skipEmpty: true); while (pathParser.MoveNext()) { string subPath = pathParser.ExtractCurrent(); path = Path.Combine(subPath, filename); if (File.Exists(path)) { return path; } } } // Could not find the file throw new Win32Exception(Interop.Error.ENOENT.Info().RawErrno); } /// <summary>Convert a number of "jiffies", or ticks, to a TimeSpan.</summary> /// <param name="ticks">The number of ticks.</param> /// <returns>The equivalent TimeSpan.</returns> internal static TimeSpan TicksToTimeSpan(double ticks) { // Look up the number of ticks per second in the system's configuration, // then use that to convert to a TimeSpan int ticksPerSecond = Interop.libc.sysconf(Interop.libc.SysConfNames._SC_CLK_TCK); if (ticksPerSecond <= 0) { throw new Win32Exception(); } return TimeSpan.FromSeconds(ticks / (double)ticksPerSecond); } /// <summary>Opens a stream around the specified file descriptor and with the specified access.</summary> /// <param name="fd">The file descriptor.</param> /// <param name="access">The access mode.</param> /// <returns>The opened stream.</returns> private static FileStream OpenStream(int fd, FileAccess access) { Debug.Assert(fd >= 0); return new FileStream( new SafeFileHandle((IntPtr)fd, ownsHandle: true), access, StreamBufferSize, isAsync: false); } /// <summary>Parses a command-line argument string into a list of arguments.</summary> /// <param name="arguments">The argument string.</param> /// <param name="results">The list into which the component arguments should be stored.</param> private static void ParseArgumentsIntoList(string arguments, List<string> results) { var currentArgument = new StringBuilder(); bool inQuotes = false; // Iterate through all of the characters in the argument string for (int i = 0; i < arguments.Length; i++) { char c = arguments[i]; // If this is an escaped double-quote, just add a '"' to the current // argument and then skip past it in the input. if (c == '\\' && i < arguments.Length - 1 && arguments[i + 1] == '"') { currentArgument.Append('"'); i++; continue; } // If this is a double quote, track whether we're inside of quotes or not. // Anything within quotes will be treated as a single argument, even if // it contains spaces. if (c == '"') { inQuotes = !inQuotes; continue; } // If this is a space and we're not in quotes, we're done with the current // argument, and if we've built up any characters in the current argument, // it should be added to the results and then reset for the next one. if (c == ' ' && !inQuotes) { if (currentArgument.Length > 0) { results.Add(currentArgument.ToString()); currentArgument.Clear(); } continue; } // Nothing special; add the character to the current argument. currentArgument.Append(c); } // If we reach the end of the string and we still have anything in our current // argument buffer, treat it as an argument to be added to the results. if (currentArgument.Length > 0) { results.Add(currentArgument.ToString()); } } /// <summary>Gets the wait state for this Process object.</summary> private ProcessWaitState GetWaitState() { if (_waitStateHolder == null) { EnsureState(State.HaveId); _waitStateHolder = new ProcessWaitState.Holder(_processId); } return _waitStateHolder._state; } } }
/* * Qa full api * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: all * * 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.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace HostMe.Sdk.Model { /// <summary> /// UpdateWaitingItem /// </summary> [DataContract] public partial class UpdateWaitingItem : IEquatable<UpdateWaitingItem>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="UpdateWaitingItem" /> class. /// </summary> /// <param name="GroupSize">GroupSize.</param> /// <param name="ExpectedTimeMinutes">ExpectedTimeMinutes.</param> /// <param name="EstimatedTurnOverTime">EstimatedTurnOverTime.</param> /// <param name="CustomerName">CustomerName.</param> /// <param name="Phone">Phone.</param> /// <param name="Areas">Areas.</param> /// <param name="InternalNotes">InternalNotes.</param> /// <param name="SpecialRequests">SpecialRequests.</param> /// <param name="AboutGuestNotes">AboutGuestNotes.</param> /// <param name="Email">Email.</param> /// <param name="TableNumber">TableNumber.</param> /// <param name="HighChair">HighChair.</param> /// <param name="Stroller">Stroller.</param> /// <param name="Party">Party.</param> /// <param name="Booth">Booth.</param> /// <param name="HighTop">HighTop.</param> /// <param name="Table">Table.</param> /// <param name="AutoSeat">AutoSeat.</param> /// <param name="PartyTypes">PartyTypes.</param> /// <param name="CustomerProfile">CustomerProfile.</param> public UpdateWaitingItem(int? GroupSize = null, int? ExpectedTimeMinutes = null, int? EstimatedTurnOverTime = null, string CustomerName = null, string Phone = null, string Areas = null, string InternalNotes = null, string SpecialRequests = null, string AboutGuestNotes = null, string Email = null, string TableNumber = null, bool? HighChair = null, bool? Stroller = null, bool? Party = null, bool? Booth = null, bool? HighTop = null, bool? Table = null, bool? AutoSeat = null, List<string> PartyTypes = null, ProfileData CustomerProfile = null) { this.GroupSize = GroupSize; this.ExpectedTimeMinutes = ExpectedTimeMinutes; this.EstimatedTurnOverTime = EstimatedTurnOverTime; this.CustomerName = CustomerName; this.Phone = Phone; this.Areas = Areas; this.InternalNotes = InternalNotes; this.SpecialRequests = SpecialRequests; this.AboutGuestNotes = AboutGuestNotes; this.Email = Email; this.TableNumber = TableNumber; this.HighChair = HighChair; this.Stroller = Stroller; this.Party = Party; this.Booth = Booth; this.HighTop = HighTop; this.Table = Table; this.AutoSeat = AutoSeat; this.PartyTypes = PartyTypes; this.CustomerProfile = CustomerProfile; } /// <summary> /// Gets or Sets GroupSize /// </summary> [DataMember(Name="groupSize", EmitDefaultValue=true)] public int? GroupSize { get; set; } /// <summary> /// Gets or Sets ExpectedTimeMinutes /// </summary> [DataMember(Name="expectedTimeMinutes", EmitDefaultValue=true)] public int? ExpectedTimeMinutes { get; set; } /// <summary> /// Gets or Sets EstimatedTurnOverTime /// </summary> [DataMember(Name="estimatedTurnOverTime", EmitDefaultValue=true)] public int? EstimatedTurnOverTime { get; set; } /// <summary> /// Gets or Sets CustomerName /// </summary> [DataMember(Name="customerName", EmitDefaultValue=true)] public string CustomerName { get; set; } /// <summary> /// Gets or Sets Phone /// </summary> [DataMember(Name="phone", EmitDefaultValue=true)] public string Phone { get; set; } /// <summary> /// Gets or Sets Areas /// </summary> [DataMember(Name="areas", EmitDefaultValue=true)] public string Areas { get; set; } /// <summary> /// Gets or Sets InternalNotes /// </summary> [DataMember(Name="internalNotes", EmitDefaultValue=true)] public string InternalNotes { get; set; } /// <summary> /// Gets or Sets SpecialRequests /// </summary> [DataMember(Name="specialRequests", EmitDefaultValue=true)] public string SpecialRequests { get; set; } /// <summary> /// Gets or Sets AboutGuestNotes /// </summary> [DataMember(Name="aboutGuestNotes", EmitDefaultValue=true)] public string AboutGuestNotes { get; set; } /// <summary> /// Gets or Sets Email /// </summary> [DataMember(Name="email", EmitDefaultValue=true)] public string Email { get; set; } /// <summary> /// Gets or Sets TableNumber /// </summary> [DataMember(Name="tableNumber", EmitDefaultValue=true)] public string TableNumber { get; set; } /// <summary> /// Gets or Sets HighChair /// </summary> [DataMember(Name="highChair", EmitDefaultValue=true)] public bool? HighChair { get; set; } /// <summary> /// Gets or Sets Stroller /// </summary> [DataMember(Name="stroller", EmitDefaultValue=true)] public bool? Stroller { get; set; } /// <summary> /// Gets or Sets Party /// </summary> [DataMember(Name="party", EmitDefaultValue=true)] public bool? Party { get; set; } /// <summary> /// Gets or Sets Booth /// </summary> [DataMember(Name="booth", EmitDefaultValue=true)] public bool? Booth { get; set; } /// <summary> /// Gets or Sets HighTop /// </summary> [DataMember(Name="highTop", EmitDefaultValue=true)] public bool? HighTop { get; set; } /// <summary> /// Gets or Sets Table /// </summary> [DataMember(Name="table", EmitDefaultValue=true)] public bool? Table { get; set; } /// <summary> /// Gets or Sets AutoSeat /// </summary> [DataMember(Name="autoSeat", EmitDefaultValue=true)] public bool? AutoSeat { get; set; } /// <summary> /// Gets or Sets PartyTypes /// </summary> [DataMember(Name="partyTypes", EmitDefaultValue=true)] public List<string> PartyTypes { get; set; } /// <summary> /// Gets or Sets CustomerProfile /// </summary> [DataMember(Name="customerProfile", EmitDefaultValue=true)] public ProfileData CustomerProfile { 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 UpdateWaitingItem {\n"); sb.Append(" GroupSize: ").Append(GroupSize).Append("\n"); sb.Append(" ExpectedTimeMinutes: ").Append(ExpectedTimeMinutes).Append("\n"); sb.Append(" EstimatedTurnOverTime: ").Append(EstimatedTurnOverTime).Append("\n"); sb.Append(" CustomerName: ").Append(CustomerName).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" Areas: ").Append(Areas).Append("\n"); sb.Append(" InternalNotes: ").Append(InternalNotes).Append("\n"); sb.Append(" SpecialRequests: ").Append(SpecialRequests).Append("\n"); sb.Append(" AboutGuestNotes: ").Append(AboutGuestNotes).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" TableNumber: ").Append(TableNumber).Append("\n"); sb.Append(" HighChair: ").Append(HighChair).Append("\n"); sb.Append(" Stroller: ").Append(Stroller).Append("\n"); sb.Append(" Party: ").Append(Party).Append("\n"); sb.Append(" Booth: ").Append(Booth).Append("\n"); sb.Append(" HighTop: ").Append(HighTop).Append("\n"); sb.Append(" Table: ").Append(Table).Append("\n"); sb.Append(" AutoSeat: ").Append(AutoSeat).Append("\n"); sb.Append(" PartyTypes: ").Append(PartyTypes).Append("\n"); sb.Append(" CustomerProfile: ").Append(CustomerProfile).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 UpdateWaitingItem); } /// <summary> /// Returns true if UpdateWaitingItem instances are equal /// </summary> /// <param name="other">Instance of UpdateWaitingItem to be compared</param> /// <returns>Boolean</returns> public bool Equals(UpdateWaitingItem other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.GroupSize == other.GroupSize || this.GroupSize != null && this.GroupSize.Equals(other.GroupSize) ) && ( this.ExpectedTimeMinutes == other.ExpectedTimeMinutes || this.ExpectedTimeMinutes != null && this.ExpectedTimeMinutes.Equals(other.ExpectedTimeMinutes) ) && ( this.EstimatedTurnOverTime == other.EstimatedTurnOverTime || this.EstimatedTurnOverTime != null && this.EstimatedTurnOverTime.Equals(other.EstimatedTurnOverTime) ) && ( this.CustomerName == other.CustomerName || this.CustomerName != null && this.CustomerName.Equals(other.CustomerName) ) && ( this.Phone == other.Phone || this.Phone != null && this.Phone.Equals(other.Phone) ) && ( this.Areas == other.Areas || this.Areas != null && this.Areas.Equals(other.Areas) ) && ( this.InternalNotes == other.InternalNotes || this.InternalNotes != null && this.InternalNotes.Equals(other.InternalNotes) ) && ( this.SpecialRequests == other.SpecialRequests || this.SpecialRequests != null && this.SpecialRequests.Equals(other.SpecialRequests) ) && ( this.AboutGuestNotes == other.AboutGuestNotes || this.AboutGuestNotes != null && this.AboutGuestNotes.Equals(other.AboutGuestNotes) ) && ( this.Email == other.Email || this.Email != null && this.Email.Equals(other.Email) ) && ( this.TableNumber == other.TableNumber || this.TableNumber != null && this.TableNumber.Equals(other.TableNumber) ) && ( this.HighChair == other.HighChair || this.HighChair != null && this.HighChair.Equals(other.HighChair) ) && ( this.Stroller == other.Stroller || this.Stroller != null && this.Stroller.Equals(other.Stroller) ) && ( this.Party == other.Party || this.Party != null && this.Party.Equals(other.Party) ) && ( this.Booth == other.Booth || this.Booth != null && this.Booth.Equals(other.Booth) ) && ( this.HighTop == other.HighTop || this.HighTop != null && this.HighTop.Equals(other.HighTop) ) && ( this.Table == other.Table || this.Table != null && this.Table.Equals(other.Table) ) && ( this.AutoSeat == other.AutoSeat || this.AutoSeat != null && this.AutoSeat.Equals(other.AutoSeat) ) && ( this.PartyTypes == other.PartyTypes || this.PartyTypes != null && this.PartyTypes.SequenceEqual(other.PartyTypes) ) && ( this.CustomerProfile == other.CustomerProfile || this.CustomerProfile != null && this.CustomerProfile.Equals(other.CustomerProfile) ); } /// <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.GroupSize != null) hash = hash * 59 + this.GroupSize.GetHashCode(); if (this.ExpectedTimeMinutes != null) hash = hash * 59 + this.ExpectedTimeMinutes.GetHashCode(); if (this.EstimatedTurnOverTime != null) hash = hash * 59 + this.EstimatedTurnOverTime.GetHashCode(); if (this.CustomerName != null) hash = hash * 59 + this.CustomerName.GetHashCode(); if (this.Phone != null) hash = hash * 59 + this.Phone.GetHashCode(); if (this.Areas != null) hash = hash * 59 + this.Areas.GetHashCode(); if (this.InternalNotes != null) hash = hash * 59 + this.InternalNotes.GetHashCode(); if (this.SpecialRequests != null) hash = hash * 59 + this.SpecialRequests.GetHashCode(); if (this.AboutGuestNotes != null) hash = hash * 59 + this.AboutGuestNotes.GetHashCode(); if (this.Email != null) hash = hash * 59 + this.Email.GetHashCode(); if (this.TableNumber != null) hash = hash * 59 + this.TableNumber.GetHashCode(); if (this.HighChair != null) hash = hash * 59 + this.HighChair.GetHashCode(); if (this.Stroller != null) hash = hash * 59 + this.Stroller.GetHashCode(); if (this.Party != null) hash = hash * 59 + this.Party.GetHashCode(); if (this.Booth != null) hash = hash * 59 + this.Booth.GetHashCode(); if (this.HighTop != null) hash = hash * 59 + this.HighTop.GetHashCode(); if (this.Table != null) hash = hash * 59 + this.Table.GetHashCode(); if (this.AutoSeat != null) hash = hash * 59 + this.AutoSeat.GetHashCode(); if (this.PartyTypes != null) hash = hash * 59 + this.PartyTypes.GetHashCode(); if (this.CustomerProfile != null) hash = hash * 59 + this.CustomerProfile.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using MLAPI.Configuration; using MLAPI.Exceptions; using MLAPI.Hashing; using MLAPI.Logging; using MLAPI.Messaging; using MLAPI.Serialization.Pooled; using MLAPI.Spawning; using MLAPI.Transports; using UnityEngine; namespace MLAPI { /// <summary> /// A component used to identify that a GameObject in the network /// </summary> [AddComponentMenu("MLAPI/NetworkObject", -99)] [DisallowMultipleComponent] public sealed class NetworkObject : MonoBehaviour { private void OnValidate() { // Set this so the hash can be serialized on Scene objects. For prefabs, they are generated at runtime. ValidateHash(); } internal void ValidateHash() { if (string.IsNullOrEmpty(PrefabHashGenerator)) { PrefabHashGenerator = gameObject.name; } PrefabHash = PrefabHashGenerator.GetStableHash64(); } /// <summary> /// Gets the NetworkManager that owns this NetworkObject instance /// </summary> public NetworkManager NetworkManager => NetworkManager.Singleton; /// <summary> /// Gets the unique Id of this object that is synced across the network /// </summary> public ulong NetworkObjectId { get; internal set; } /// <summary> /// Gets the ClientId of the owner of this NetworkObject /// </summary> public ulong OwnerClientId { get { if (OwnerClientIdInternal == null) { return NetworkManager.Singleton != null ? NetworkManager.Singleton.ServerClientId : 0; } else { return OwnerClientIdInternal.Value; } } internal set { if (NetworkManager.Singleton != null && value == NetworkManager.Singleton.ServerClientId) { OwnerClientIdInternal = null; } else { OwnerClientIdInternal = value; } } } internal ulong? OwnerClientIdInternal = null; /// <summary> /// InstanceId is the id that is unique to the object and scene for a scene object when UsePrefabSync is false. /// If UsePrefabSync is true or if it's used on non scene objects, this has no effect. /// Should not be set manually /// </summary> [HideInInspector] [SerializeField] public ulong NetworkInstanceId; /// <summary> /// The Prefab unique hash. This should not be set my the user but rather changed by editing the PrefabHashGenerator. /// It has to be the same for all instances of a prefab /// </summary> [HideInInspector] [SerializeField] public ulong PrefabHash; /// <summary> /// The generator used to change the PrefabHash. This should be set the same for all instances of a prefab. /// It has to be unique in relation to other prefabs /// </summary> [SerializeField] public string PrefabHashGenerator; /// <summary> /// If true, the object will always be replicated as root on clients and the parent will be ignored. /// </summary> public bool AlwaysReplicateAsRoot; /// <summary> /// Gets if this object is a player object /// </summary> public bool IsPlayerObject { get; internal set; } /// <summary> /// Gets if the object is the the personal clients player object /// </summary> public bool IsLocalPlayer => NetworkManager.Singleton != null && IsPlayerObject && OwnerClientId == NetworkManager.Singleton.LocalClientId; /// <summary> /// Gets if the object is owned by the local player or if the object is the local player object /// </summary> public bool IsOwner => NetworkManager.Singleton != null && OwnerClientId == NetworkManager.Singleton.LocalClientId; /// <summary> /// Gets Whether or not the object is owned by anyone /// </summary> public bool IsOwnedByServer => NetworkManager.Singleton != null && OwnerClientId == NetworkManager.Singleton.ServerClientId; /// <summary> /// Gets if the object has yet been spawned across the network /// </summary> public bool IsSpawned { get; internal set; } /// <summary> /// Gets if the object is a SceneObject, null if it's not yet spawned but is a scene object. /// </summary> public bool? IsSceneObject { get; internal set; } /// <summary> /// Gets whether or not the object should be automatically removed when the scene is unloaded. /// </summary> public bool DestroyWithScene { get; internal set; } /// <summary> /// Delegate type for checking visibility /// </summary> /// <param name="clientId">The clientId to check visibility for</param> public delegate bool VisibilityDelegate(ulong clientId); /// <summary> /// Delegate invoked when the MLAPI needs to know if the object should be visible to a client, if null it will assume true /// </summary> public VisibilityDelegate CheckObjectVisibility = null; /// <summary> /// Delegate type for checking spawn options /// </summary> /// <param name="clientId">The clientId to check spawn options for</param> public delegate bool SpawnDelegate(ulong clientId); /// <summary> /// Delegate invoked when the MLAPI needs to know if it should include the transform when spawning the object, if null it will assume true /// </summary> public SpawnDelegate IncludeTransformWhenSpawning = null; /// <summary> /// Whether or not to destroy this object if it's owner is destroyed. /// If false, the objects ownership will be given to the server. /// </summary> public bool DontDestroyWithOwner; internal readonly HashSet<ulong> m_Observers = new HashSet<ulong>(); /// <summary> /// Returns Observers enumerator /// </summary> /// <returns>Observers enumerator</returns> public HashSet<ulong>.Enumerator GetObservers() { if (!IsSpawned) { throw new SpawnStateException("Object is not spawned"); } return m_Observers.GetEnumerator(); } /// <summary> /// Whether or not this object is visible to a specific client /// </summary> /// <param name="clientId">The clientId of the client</param> /// <returns>True if the client knows about the object</returns> public bool IsNetworkVisibleTo(ulong clientId) { if (!IsSpawned) { throw new SpawnStateException("Object is not spawned"); } return m_Observers.Contains(clientId); } /// <summary> /// Shows a previously hidden object to a client /// </summary> /// <param name="clientId">The client to show the object to</param> /// <param name="payload">An optional payload to send as part of the spawn</param> public void NetworkShow(ulong clientId, Stream payload = null) { if (!IsSpawned) { throw new SpawnStateException("Object is not spawned"); } if (!NetworkManager.Singleton.IsServer) { throw new NotServerException("Only server can change visibility"); } if (m_Observers.Contains(clientId)) { throw new VisibilityChangeException("The object is already visible"); } // Send spawn call m_Observers.Add(clientId); NetworkSpawnManager.SendSpawnCallForObject(clientId, this, payload); } /// <summary> /// Shows a list of previously hidden objects to a client /// </summary> /// <param name="networkObjects">The objects to show</param> /// <param name="clientId">The client to show the objects to</param> /// <param name="payload">An optional payload to send as part of the spawns</param> public static void NetworkShow(List<NetworkObject> networkObjects, ulong clientId, Stream payload = null) { if (!NetworkManager.Singleton.IsServer) { throw new NotServerException("Only server can change visibility"); } // Do the safety loop first to prevent putting the MLAPI in an invalid state. for (int i = 0; i < networkObjects.Count; i++) { if (!networkObjects[i].IsSpawned) { throw new SpawnStateException("Object is not spawned"); } if (networkObjects[i].m_Observers.Contains(clientId)) { throw new VisibilityChangeException($"{nameof(NetworkObject)} with NetworkId: {networkObjects[i].NetworkObjectId} is already visible"); } } using (var buffer = PooledNetworkBuffer.Get()) using (var writer = PooledNetworkWriter.Get(buffer)) { writer.WriteUInt16Packed((ushort)networkObjects.Count); for (int i = 0; i < networkObjects.Count; i++) { // Send spawn call networkObjects[i].m_Observers.Add(clientId); NetworkSpawnManager.WriteSpawnCallForObject(buffer, clientId, networkObjects[i], payload); } InternalMessageSender.Send(clientId, NetworkConstants.ADD_OBJECTS, NetworkChannel.Internal, buffer); } } /// <summary> /// Hides a object from a specific client /// </summary> /// <param name="clientId">The client to hide the object for</param> public void NetworkHide(ulong clientId) { if (!IsSpawned) { throw new SpawnStateException("Object is not spawned"); } if (!NetworkManager.Singleton.IsServer) { throw new NotServerException("Only server can change visibility"); } if (!m_Observers.Contains(clientId)) { throw new VisibilityChangeException("The object is already hidden"); } if (clientId == NetworkManager.Singleton.ServerClientId) { throw new VisibilityChangeException("Cannot hide an object from the server"); } // Send destroy call m_Observers.Remove(clientId); using (var buffer = PooledNetworkBuffer.Get()) using (var writer = PooledNetworkWriter.Get(buffer)) { writer.WriteUInt64Packed(NetworkObjectId); InternalMessageSender.Send(clientId, NetworkConstants.DESTROY_OBJECT, NetworkChannel.Internal, buffer); } } /// <summary> /// Hides a list of objects from a client /// </summary> /// <param name="networkObjects">The objects to hide</param> /// <param name="clientId">The client to hide the objects from</param> public static void NetworkHide(List<NetworkObject> networkObjects, ulong clientId) { if (!NetworkManager.Singleton.IsServer) { throw new NotServerException("Only server can change visibility"); } if (clientId == NetworkManager.Singleton.ServerClientId) { throw new VisibilityChangeException("Cannot hide an object from the server"); } // Do the safety loop first to prevent putting the MLAPI in an invalid state. for (int i = 0; i < networkObjects.Count; i++) { if (!networkObjects[i].IsSpawned) { throw new SpawnStateException("Object is not spawned"); } if (!networkObjects[i].m_Observers.Contains(clientId)) { throw new VisibilityChangeException($"{nameof(NetworkObject)} with {nameof(NetworkObjectId)}: {networkObjects[i].NetworkObjectId} is already hidden"); } } using (var buffer = PooledNetworkBuffer.Get()) using (var writer = PooledNetworkWriter.Get(buffer)) { writer.WriteUInt16Packed((ushort)networkObjects.Count); for (int i = 0; i < networkObjects.Count; i++) { // Send destroy call networkObjects[i].m_Observers.Remove(clientId); writer.WriteUInt64Packed(networkObjects[i].NetworkObjectId); } InternalMessageSender.Send(clientId, NetworkConstants.DESTROY_OBJECTS, NetworkChannel.Internal, buffer); } } private void OnDestroy() { if (NetworkManager.Singleton != null) { NetworkSpawnManager.OnDestroyObject(NetworkObjectId, false); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SpawnInternal(Stream spawnPayload, bool destroyWithScene , ulong? ownerClientId, bool playerObject) { if (!NetworkManager.Singleton.IsListening) { throw new NotListeningException($"{nameof(NetworkManager)} isn't listening, start a server or host before spawning objects."); } if (!NetworkManager.Singleton.IsServer) { throw new NotServerException($"Only server can spawn {nameof(NetworkObject)}s"); } if (spawnPayload != null) spawnPayload.Position = 0; NetworkSpawnManager.SpawnNetworkObjectLocally(this, NetworkSpawnManager.GetNetworkObjectId(), false, playerObject, ownerClientId, spawnPayload, spawnPayload != null, spawnPayload == null ? 0 : (int)spawnPayload.Length, false, destroyWithScene); for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++) { if (m_Observers.Contains(NetworkManager.Singleton.ConnectedClientsList[i].ClientId)) { NetworkSpawnManager.SendSpawnCallForObject(NetworkManager.Singleton.ConnectedClientsList[i].ClientId, this, spawnPayload); } } } /// <summary> /// Spawns this GameObject across the network. Can only be called from the Server /// </summary> /// <param name="spawnPayload">The writer containing the spawn payload</param> /// <param name="destroyWithScene">Should the object be destroyd when the scene is changed</param> public void Spawn(Stream spawnPayload = null, bool destroyWithScene = false) { SpawnInternal(spawnPayload, destroyWithScene, null, false); } /// <summary> /// Spawns an object across the network with a given owner. Can only be called from server /// </summary> /// <param name="clientId">The clientId to own the object</param> /// <param name="spawnPayload">The writer containing the spawn payload</param> /// <param name="destroyWithScene">Should the object be destroyd when the scene is changed</param> public void SpawnWithOwnership(ulong clientId, Stream spawnPayload = null, bool destroyWithScene = false) { SpawnInternal(spawnPayload, destroyWithScene, clientId, false); } /// <summary> /// Spawns an object across the network and makes it the player object for the given client /// </summary> /// <param name="clientId">The clientId whos player object this is</param> /// <param name="spawnPayload">The writer containing the spawn payload</param> /// <param name="destroyWithScene">Should the object be destroyd when the scene is changed</param> public void SpawnAsPlayerObject(ulong clientId, Stream spawnPayload = null, bool destroyWithScene = false) { SpawnInternal(spawnPayload, destroyWithScene, clientId, true); } /// <summary> /// Despawns this GameObject and destroys it for other clients. This should be used if the object should be kept on the server /// </summary> public void Despawn(bool destroy = false) { NetworkSpawnManager.DespawnObject(this, destroy); } /// <summary> /// Removes all ownership of an object from any client. Can only be called from server /// </summary> public void RemoveOwnership() { NetworkSpawnManager.RemoveOwnership(this); } /// <summary> /// Changes the owner of the object. Can only be called from server /// </summary> /// <param name="newOwnerClientId">The new owner clientId</param> public void ChangeOwnership(ulong newOwnerClientId) { NetworkSpawnManager.ChangeOwnership(this, newOwnerClientId); } internal void InvokeBehaviourOnLostOwnership() { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { ChildNetworkBehaviours[i].OnLostOwnership(); } } internal void InvokeBehaviourOnGainedOwnership() { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { ChildNetworkBehaviours[i].OnGainedOwnership(); } } internal void ResetNetworkStartInvoked() { if (ChildNetworkBehaviours != null) { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { ChildNetworkBehaviours[i].NetworkStartInvoked = false; } } } internal void InvokeBehaviourNetworkSpawn(Stream stream) { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { //We check if we are it's NetworkObject owner incase a NetworkObject exists as a child of our NetworkObject if (!ChildNetworkBehaviours[i].NetworkStartInvoked) { if (!ChildNetworkBehaviours[i].InternalNetworkStartInvoked) { ChildNetworkBehaviours[i].InternalNetworkStart(); ChildNetworkBehaviours[i].InternalNetworkStartInvoked = true; } ChildNetworkBehaviours[i].NetworkStart(stream); ChildNetworkBehaviours[i].NetworkStartInvoked = true; } } } private List<NetworkBehaviour> m_ChildNetworkBehaviours; internal List<NetworkBehaviour> ChildNetworkBehaviours { get { if (m_ChildNetworkBehaviours != null) { return m_ChildNetworkBehaviours; } m_ChildNetworkBehaviours = new List<NetworkBehaviour>(); var networkBehaviours = GetComponentsInChildren<NetworkBehaviour>(true); for (int i = 0; i < networkBehaviours.Length; i++) { if (networkBehaviours[i].NetworkObject == this) { m_ChildNetworkBehaviours.Add(networkBehaviours[i]); } } return m_ChildNetworkBehaviours; } } internal void WriteNetworkVariableData(Stream stream, ulong clientId) { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { ChildNetworkBehaviours[i].InitializeVariables(); NetworkBehaviour.WriteNetworkVariableData(ChildNetworkBehaviours[i].NetworkVariableFields, stream, clientId); } } internal void SetNetworkVariableData(Stream stream) { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { ChildNetworkBehaviours[i].InitializeVariables(); NetworkBehaviour.SetNetworkVariableData(ChildNetworkBehaviours[i].NetworkVariableFields, stream); } } internal ushort GetNetworkBehaviourOrderIndex(NetworkBehaviour instance) { for (ushort i = 0; i < ChildNetworkBehaviours.Count; i++) { if (ChildNetworkBehaviours[i] == instance) { return i; } } return 0; } internal NetworkBehaviour GetNetworkBehaviourAtOrderIndex(ushort index) { if (index >= ChildNetworkBehaviours.Count) { if (NetworkLog.CurrentLogLevel <= LogLevel.Error) { NetworkLog.LogError($"Behaviour index was out of bounds. Did you mess up the order of your {nameof(NetworkBehaviour)}s?"); } return null; } return ChildNetworkBehaviours[index]; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace WebApplication.Data.Migrations { public partial class CreateIdentitySchema : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), PasswordHash = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), SecurityStamp = table.Column<string>(nullable: true), TwoFactorEnabled = table.Column<bool>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_UserId", table: "AspNetUserRoles", column: "UserId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Linq.Expressions; using System.Numerics; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Reflection; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime.Binding { using Ast = Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; partial class PythonBinder : DefaultBinder { private PythonContext/*!*/ _context; private SlotCache/*!*/ _typeMembers = new SlotCache(); private SlotCache/*!*/ _resolvedMembers = new SlotCache(); private Dictionary<Type/*!*/, IList<Type/*!*/>/*!*/>/*!*/ _dlrExtensionTypes; private bool _registeredInterfaceExtensions; // true if someone has registered extensions for interfaces [MultiRuntimeAware] private static readonly Dictionary<Type/*!*/, ExtensionTypeInfo/*!*/>/*!*/ _sysTypes = MakeSystemTypes(); public PythonBinder(PythonContext/*!*/ pythonContext, CodeContext context) { ContractUtils.RequiresNotNull(pythonContext, "pythonContext"); _dlrExtensionTypes = MakeExtensionTypes(); _context = pythonContext; if (context != null) { context.LanguageContext.DomainManager.AssemblyLoaded += new EventHandler<AssemblyLoadedEventArgs>(DomainManager_AssemblyLoaded); foreach (Assembly asm in pythonContext.DomainManager.GetLoadedAssemblyList()) { DomainManager_AssemblyLoaded(this, new AssemblyLoadedEventArgs(asm)); } } } public PythonBinder(PythonBinder binder) { _context = binder._context; _typeMembers = binder._typeMembers; _resolvedMembers = binder._resolvedMembers; _dlrExtensionTypes = binder._dlrExtensionTypes; _registeredInterfaceExtensions = binder._registeredInterfaceExtensions; } public override Expression/*!*/ ConvertExpression(Expression/*!*/ expr, Type/*!*/ toType, ConversionResultKind kind, OverloadResolverFactory factory) { ContractUtils.RequiresNotNull(expr, "expr"); ContractUtils.RequiresNotNull(toType, "toType"); Type exprType = expr.Type; if (toType == typeof(object)) { if (exprType.IsValueType) { return AstUtils.Convert(expr, toType); } else { return expr; } } if (toType.IsAssignableFrom(exprType)) { // remove the unboxing expression if we're going be boxing again if (exprType.IsValueType && !toType.IsValueType && expr.NodeType == ExpressionType.Unbox) { return ((UnaryExpression)expr).Operand; } return expr; } Type visType = Context.Binder.PrivateBinding ? toType : CompilerHelpers.GetVisibleType(toType); if (exprType == typeof(PythonType) && visType == typeof(Type)) { return AstUtils.Convert(expr, visType); // use the implicit conversion } return Binders.Convert( ((PythonOverloadResolverFactory)factory)._codeContext, _context, visType, visType == typeof(char) ? ConversionResultKind.ImplicitCast : kind, expr ); } internal static MethodInfo GetGenericConvertMethod(Type toType) { if (toType.IsValueType) { if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Nullable<>)) { return typeof(Converter).GetMethod("ConvertToNullableType"); } else { return typeof(Converter).GetMethod("ConvertToValueType"); } } else { return typeof(Converter).GetMethod("ConvertToReferenceType"); } } internal static MethodInfo GetFastConvertMethod(Type toType) { if (toType == typeof(char)) { return typeof(Converter).GetMethod("ConvertToChar"); } else if (toType == typeof(int)) { return typeof(Converter).GetMethod("ConvertToInt32"); } else if (toType == typeof(string)) { return typeof(Converter).GetMethod("ConvertToString"); } else if (toType == typeof(long)) { return typeof(Converter).GetMethod("ConvertToInt64"); } else if (toType == typeof(double)) { return typeof(Converter).GetMethod("ConvertToDouble"); } else if (toType == typeof(bool)) { return typeof(Converter).GetMethod("ConvertToBoolean"); } else if (toType == typeof(BigInteger)) { return typeof(Converter).GetMethod("ConvertToBigInteger"); } else if (toType == typeof(Complex)) { return typeof(Converter).GetMethod("ConvertToComplex"); } else if (toType == typeof(IEnumerable)) { return typeof(Converter).GetMethod("ConvertToIEnumerable"); } else if (toType == typeof(float)) { return typeof(Converter).GetMethod("ConvertToSingle"); } else if (toType == typeof(byte)) { return typeof(Converter).GetMethod("ConvertToByte"); } else if (toType == typeof(sbyte)) { return typeof(Converter).GetMethod("ConvertToSByte"); } else if (toType == typeof(short)) { return typeof(Converter).GetMethod("ConvertToInt16"); } else if (toType == typeof(uint)) { return typeof(Converter).GetMethod("ConvertToUInt32"); } else if (toType == typeof(ulong)) { return typeof(Converter).GetMethod("ConvertToUInt64"); } else if (toType == typeof(ushort)) { return typeof(Converter).GetMethod("ConvertToUInt16"); } else if (toType == typeof(Type)) { return typeof(Converter).GetMethod("ConvertToType"); } else { return null; } } public override object Convert(object obj, Type toType) { return Converter.Convert(obj, toType); } public override bool CanConvertFrom(Type fromType, Type toType, bool toNotNullable, NarrowingLevel level) { return Converter.CanConvertFrom(fromType, toType, level); } public override Candidate PreferConvert(Type t1, Type t2) { return Converter.PreferConvert(t1, t2); } public override bool PrivateBinding { get { return _context.DomainManager.Configuration.PrivateBinding; } } public override ErrorInfo MakeSetValueTypeFieldError(FieldTracker field, DynamicMetaObject instance, DynamicMetaObject value) { // allow the set but emit a warning return ErrorInfo.FromValueNoError( Expression.Block( Expression.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.Warn)), Expression.Constant(_context.SharedContext), Expression.Constant(PythonExceptions.RuntimeWarning), Expression.Constant(ReflectedField.UpdateValueTypeFieldWarning), Expression.Constant( new object[] { field.Name, field.DeclaringType.Name } ) ), Expression.Assign( Expression.Field( AstUtils.Convert( instance.Expression, field.DeclaringType ), field.Field ), ConvertExpression( value.Expression, field.FieldType, ConversionResultKind.ExplicitCast, new PythonOverloadResolverFactory( this, Expression.Constant(_context.SharedContext) ) ) ) ) ); } public override ErrorInfo MakeConversionError(Type toType, Expression value) { return ErrorInfo.FromException( Ast.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.TypeErrorForTypeMismatch)), AstUtils.Constant(DynamicHelpers.GetPythonTypeFromType(toType).Name), AstUtils.Convert(value, typeof(object)) ) ); } public override ErrorInfo/*!*/ MakeNonPublicMemberGetError(OverloadResolverFactory resolverFactory, MemberTracker member, Type type, DynamicMetaObject instance) { if (PrivateBinding) { return base.MakeNonPublicMemberGetError(resolverFactory, member, type, instance); } return ErrorInfo.FromValue( BindingHelpers.TypeErrorForProtectedMember(type, member.Name) ); } public override ErrorInfo/*!*/ MakeStaticAssignFromDerivedTypeError(Type accessingType, DynamicMetaObject instance, MemberTracker info, DynamicMetaObject assignedValue, OverloadResolverFactory factory) { return MakeMissingMemberError(accessingType, instance, info.Name); } public override ErrorInfo/*!*/ MakeStaticPropertyInstanceAccessError(PropertyTracker/*!*/ tracker, bool isAssignment, IList<DynamicMetaObject>/*!*/ parameters) { ContractUtils.RequiresNotNull(tracker, "tracker"); ContractUtils.RequiresNotNull(parameters, "parameters"); if (isAssignment) { return ErrorInfo.FromException( Ast.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.StaticAssignmentFromInstanceError)), AstUtils.Constant(tracker), AstUtils.Constant(isAssignment) ) ); } return ErrorInfo.FromValue( Ast.Property( null, tracker.GetGetMethod(DomainManager.Configuration.PrivateBinding) ) ); } #region .NET member binding public override string GetTypeName(Type t) { return DynamicHelpers.GetPythonTypeFromType(t).Name; } public override MemberGroup/*!*/ GetMember(MemberRequestKind actionKind, Type type, string name) { MemberGroup mg; if (!_resolvedMembers.TryGetCachedMember(type, name, actionKind == MemberRequestKind.Get, out mg)) { mg = PythonTypeInfo.GetMemberAll( this, actionKind, type, name); _resolvedMembers.CacheSlot(type, actionKind == MemberRequestKind.Get, name, PythonTypeOps.GetSlot(mg, name, PrivateBinding), mg); } return mg ?? MemberGroup.EmptyGroup; } public override ErrorInfo/*!*/ MakeEventValidation(MemberGroup/*!*/ members, DynamicMetaObject eventObject, DynamicMetaObject/*!*/ value, OverloadResolverFactory/*!*/ factory) { EventTracker ev = (EventTracker)members[0]; return ErrorInfo.FromValueNoError( Ast.Block( Ast.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.SlotTrySetValue)), ((PythonOverloadResolverFactory)factory)._codeContext, AstUtils.Constant(PythonTypeOps.GetReflectedEvent(ev)), eventObject != null ? AstUtils.Convert(eventObject.Expression, typeof(object)) : AstUtils.Constant(null), AstUtils.Constant(null, typeof(PythonType)), AstUtils.Convert(value.Expression, typeof(object)) ), Ast.Constant(null) ) ); } public override ErrorInfo MakeMissingMemberError(Type type, DynamicMetaObject self, string name) { string typeName; if (typeof(TypeTracker).IsAssignableFrom(type)) { typeName = "type"; } else { typeName = NameConverter.GetTypeName(type); } return ErrorInfo.FromException( Ast.New( typeof(MissingMemberException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(String.Format("'{0}' object has no attribute '{1}'", typeName, name)) ) ); } public override ErrorInfo MakeMissingMemberErrorForAssign(Type type, DynamicMetaObject self, string name) { if (self != null) { return MakeMissingMemberError(type, self, name); } return ErrorInfo.FromException( Ast.New( typeof(TypeErrorException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(String.Format("can't set attributes of built-in/extension type '{0}'", NameConverter.GetTypeName(type))) ) ); } public override ErrorInfo MakeMissingMemberErrorForAssignReadOnlyProperty(Type type, DynamicMetaObject self, string name) { return ErrorInfo.FromException( Ast.New( typeof(MissingMemberException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(String.Format("can't assign to read-only property {0} of type '{1}'", name, NameConverter.GetTypeName(type))) ) ); } public override ErrorInfo MakeMissingMemberErrorForDelete(Type type, DynamicMetaObject self, string name) { return MakeMissingMemberErrorForAssign(type, self, name); } /// <summary> /// Provides a way for the binder to provide a custom error message when lookup fails. Just /// doing this for the time being until we get a more robust error return mechanism. /// </summary> public override ErrorInfo MakeReadOnlyMemberError(Type type, string name) { return ErrorInfo.FromException( Ast.New( typeof(MissingMemberException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant( String.Format("attribute '{0}' of '{1}' object is read-only", name, NameConverter.GetTypeName(type) ) ) ) ); } /// <summary> /// Provides a way for the binder to provide a custom error message when lookup fails. Just /// doing this for the time being until we get a more robust error return mechanism. /// </summary> public override ErrorInfo MakeUndeletableMemberError(Type type, string name) { return ErrorInfo.FromException( Ast.New( typeof(MissingMemberException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant( String.Format("cannot delete attribute '{0}' of builtin type '{1}'", name, NameConverter.GetTypeName(type) ) ) ) ); } #endregion internal IList<Type> GetExtensionTypesInternal(Type t) { List<Type> res = new List<Type>(base.GetExtensionTypes(t)); AddExtensionTypes(t, res); return res.ToArray(); } public override bool IncludeExtensionMember(MemberInfo member) { return !member.DeclaringType.IsDefined(typeof(PythonHiddenBaseClassAttribute), false); } public override IList<Type> GetExtensionTypes(Type t) { List<Type> list = new List<Type>(); // Python includes the types themselves so we can use extension properties w/ CodeContext list.Add(t); list.AddRange(base.GetExtensionTypes(t)); AddExtensionTypes(t, list); return list; } private void AddExtensionTypes(Type t, List<Type> list) { ExtensionTypeInfo extType; if (_sysTypes.TryGetValue(t, out extType)) { list.Add(extType.ExtensionType); } IList<Type> userExtensions; lock (_dlrExtensionTypes) { if (_dlrExtensionTypes.TryGetValue(t, out userExtensions)) { list.AddRange(userExtensions); } if (_registeredInterfaceExtensions) { foreach (Type ifaceType in t.GetInterfaces()) { IList<Type> extTypes; if (_dlrExtensionTypes.TryGetValue(ifaceType, out extTypes)) { list.AddRange(extTypes); } } } if (t.IsGenericType) { // search for generic extensions, e.g. ListOfTOps<T> for List<T>, // we then make a new generic type out of the extension type. Type typeDef = t.GetGenericTypeDefinition(); Type[] args = t.GetGenericArguments(); if (_dlrExtensionTypes.TryGetValue(typeDef, out userExtensions)) { foreach (Type genExtType in userExtensions) { list.Add(genExtType.MakeGenericType(args)); } } } } } public bool HasExtensionTypes(Type t) { return _dlrExtensionTypes.ContainsKey(t); } public override DynamicMetaObject ReturnMemberTracker(Type type, MemberTracker memberTracker) { var res = ReturnMemberTracker(type, memberTracker, PrivateBinding); return res ?? base.ReturnMemberTracker(type, memberTracker); } private static DynamicMetaObject ReturnMemberTracker(Type type, MemberTracker memberTracker, bool privateBinding) { switch (memberTracker.MemberType) { case TrackerTypes.TypeGroup: return new DynamicMetaObject(AstUtils.Constant(memberTracker), BindingRestrictions.Empty, memberTracker); case TrackerTypes.Type: return ReturnTypeTracker((TypeTracker)memberTracker); case TrackerTypes.Bound: return new DynamicMetaObject(ReturnBoundTracker((BoundMemberTracker)memberTracker, privateBinding), BindingRestrictions.Empty); case TrackerTypes.Property: return new DynamicMetaObject(ReturnPropertyTracker((PropertyTracker)memberTracker, privateBinding), BindingRestrictions.Empty);; case TrackerTypes.Event: return new DynamicMetaObject(Ast.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.MakeBoundEvent)), AstUtils.Constant(PythonTypeOps.GetReflectedEvent((EventTracker)memberTracker)), AstUtils.Constant(null), AstUtils.Constant(type) ), BindingRestrictions.Empty);; case TrackerTypes.Field: return new DynamicMetaObject(ReturnFieldTracker((FieldTracker)memberTracker), BindingRestrictions.Empty);; case TrackerTypes.MethodGroup: return new DynamicMetaObject(ReturnMethodGroup((MethodGroup)memberTracker), BindingRestrictions.Empty); ; case TrackerTypes.Constructor: MethodBase[] ctors = PythonTypeOps.GetConstructors(type, privateBinding, true); object val; if (PythonTypeOps.IsDefaultNew(ctors)) { if (IsPythonType(type)) { val = InstanceOps.New; } else { val = InstanceOps.NewCls; } } else { val = PythonTypeOps.GetConstructor(type, InstanceOps.NonDefaultNewInst, ctors); } return new DynamicMetaObject(AstUtils.Constant(val), BindingRestrictions.Empty, val); case TrackerTypes.Custom: return new DynamicMetaObject( AstUtils.Constant(((PythonCustomTracker)memberTracker).GetSlot(), typeof(PythonTypeSlot)), BindingRestrictions.Empty, ((PythonCustomTracker)memberTracker).GetSlot() ); } return null; } /// <summary> /// Gets the PythonBinder associated with tihs CodeContext /// </summary> public static PythonBinder/*!*/ GetBinder(CodeContext/*!*/ context) { return (PythonBinder)context.LanguageContext.Binder; } /// <summary> /// Performs .NET member resolution. This looks within the given type and also /// includes any extension members. Base classes and their extension members are /// not searched. /// </summary> public bool TryLookupSlot(CodeContext/*!*/ context, PythonType/*!*/ type, string name, out PythonTypeSlot slot) { Debug.Assert(type.IsSystemType); return TryLookupProtectedSlot(context, type, name, out slot); } /// <summary> /// Performs .NET member resolution. This looks within the given type and also /// includes any extension members. Base classes and their extension members are /// not searched. /// /// This version allows PythonType's for protected member resolution. It shouldn't /// be called externally for other purposes. /// </summary> internal bool TryLookupProtectedSlot(CodeContext/*!*/ context, PythonType/*!*/ type, string name, out PythonTypeSlot slot) { Type curType = type.UnderlyingSystemType; if (!_typeMembers.TryGetCachedSlot(curType, true, name, out slot)) { MemberGroup mg = PythonTypeInfo.GetMember( this, MemberRequestKind.Get, curType, name); slot = PythonTypeOps.GetSlot(mg, name, PrivateBinding); _typeMembers.CacheSlot(curType, true, name, slot, mg); } if (slot != null && (slot.IsAlwaysVisible || PythonOps.IsClsVisible(context))) { return true; } slot = null; return false; } /// <summary> /// Performs .NET member resolution. This looks the type and any base types /// for members. It also searches for extension members in the type and any base types. /// </summary> public bool TryResolveSlot(CodeContext/*!*/ context, PythonType/*!*/ type, PythonType/*!*/ owner, string name, out PythonTypeSlot slot) { Type curType = type.UnderlyingSystemType; if (!_resolvedMembers.TryGetCachedSlot(curType, true, name, out slot)) { MemberGroup mg = PythonTypeInfo.GetMemberAll( this, MemberRequestKind.Get, curType, name); slot = PythonTypeOps.GetSlot(mg, name, PrivateBinding); _resolvedMembers.CacheSlot(curType, true, name, slot, mg); } if (slot != null && (slot.IsAlwaysVisible || PythonOps.IsClsVisible(context))) { return true; } slot = null; return false; } /// <summary> /// Gets the member names which are defined in this type and any extension members. /// /// This search does not include members in any subtypes or their extension members. /// </summary> public void LookupMembers(CodeContext/*!*/ context, PythonType/*!*/ type, PythonDictionary/*!*/ memberNames) { if (!_typeMembers.IsFullyCached(type.UnderlyingSystemType, true)) { Dictionary<string, KeyValuePair<PythonTypeSlot, MemberGroup>> members = new Dictionary<string, KeyValuePair<PythonTypeSlot, MemberGroup>>(); foreach (ResolvedMember rm in PythonTypeInfo.GetMembers( this, MemberRequestKind.Get, type.UnderlyingSystemType)) { if (!members.ContainsKey(rm.Name)) { members[rm.Name] = new KeyValuePair<PythonTypeSlot, MemberGroup>( PythonTypeOps.GetSlot(rm.Member, rm.Name, PrivateBinding), rm.Member ); } } _typeMembers.CacheAll(type.UnderlyingSystemType, true, members); } foreach (KeyValuePair<string, PythonTypeSlot> kvp in _typeMembers.GetAllMembers(type.UnderlyingSystemType, true)) { PythonTypeSlot slot = kvp.Value; string name = kvp.Key; if (slot.IsAlwaysVisible || PythonOps.IsClsVisible(context)) { memberNames[name] = slot; } } } /// <summary> /// Gets the member names which are defined in the type and any subtypes. /// /// This search includes members in the type and any subtypes as well as extension /// types of the type and its subtypes. /// </summary> public void ResolveMemberNames(CodeContext/*!*/ context, PythonType/*!*/ type, PythonType/*!*/ owner, Dictionary<string, string>/*!*/ memberNames) { if (!_resolvedMembers.IsFullyCached(type.UnderlyingSystemType, true)) { Dictionary<string, KeyValuePair<PythonTypeSlot, MemberGroup>> members = new Dictionary<string, KeyValuePair<PythonTypeSlot, MemberGroup>>(); foreach (ResolvedMember rm in PythonTypeInfo.GetMembersAll( this, MemberRequestKind.Get, type.UnderlyingSystemType)) { if (!members.ContainsKey(rm.Name)) { members[rm.Name] = new KeyValuePair<PythonTypeSlot, MemberGroup>( PythonTypeOps.GetSlot(rm.Member, rm.Name, PrivateBinding), rm.Member ); } } _resolvedMembers.CacheAll(type.UnderlyingSystemType, true, members); } foreach (KeyValuePair<string, PythonTypeSlot> kvp in _resolvedMembers.GetAllMembers(type.UnderlyingSystemType, true)) { PythonTypeSlot slot = kvp.Value; string name = kvp.Key; if (slot.IsAlwaysVisible || PythonOps.IsClsVisible(context)) { memberNames[name] = name; } } } private static Expression ReturnFieldTracker(FieldTracker fieldTracker) { return AstUtils.Constant(PythonTypeOps.GetReflectedField(fieldTracker.Field)); } private static Expression ReturnMethodGroup(MethodGroup methodGroup) { return AstUtils.Constant(PythonTypeOps.GetFinalSlotForFunction(GetBuiltinFunction(methodGroup))); } private static Expression ReturnBoundTracker(BoundMemberTracker boundMemberTracker, bool privateBinding) { MemberTracker boundTo = boundMemberTracker.BoundTo; switch (boundTo.MemberType) { case TrackerTypes.Property: PropertyTracker pt = (PropertyTracker)boundTo; Debug.Assert(pt.GetIndexParameters().Length > 0); return Ast.New( typeof(ReflectedIndexer).GetConstructor(new Type[] { typeof(ReflectedIndexer), typeof(object) }), AstUtils.Constant(new ReflectedIndexer(((ReflectedPropertyTracker)pt).Property, NameType.Property, privateBinding)), boundMemberTracker.Instance.Expression ); case TrackerTypes.Event: return Ast.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.MakeBoundEvent)), AstUtils.Constant(PythonTypeOps.GetReflectedEvent((EventTracker)boundMemberTracker.BoundTo)), boundMemberTracker.Instance.Expression, AstUtils.Constant(boundMemberTracker.DeclaringType) ); case TrackerTypes.MethodGroup: return Ast.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.MakeBoundBuiltinFunction)), AstUtils.Constant(GetBuiltinFunction((MethodGroup)boundTo)), AstUtils.Convert( boundMemberTracker.Instance.Expression, typeof(object) ) ); } throw new NotImplementedException(); } private static BuiltinFunction GetBuiltinFunction(MethodGroup mg) { MethodBase[] methods = new MethodBase[mg.Methods.Count]; for (int i = 0; i < mg.Methods.Count; i++) { methods[i] = mg.Methods[i].Method; } return PythonTypeOps.GetBuiltinFunction( mg.DeclaringType, mg.Methods[0].Name, (PythonTypeOps.GetMethodFunctionType(mg.DeclaringType, methods) & (~FunctionType.FunctionMethodMask)) | (mg.ContainsInstance ? FunctionType.Method : FunctionType.None) | (mg.ContainsStatic ? FunctionType.Function : FunctionType.None), mg.GetMethodBases() ); } private static Expression ReturnPropertyTracker(PropertyTracker propertyTracker, bool privateBinding) { return AstUtils.Constant(PythonTypeOps.GetReflectedProperty(propertyTracker, new MemberGroup(propertyTracker), privateBinding)); } private static DynamicMetaObject ReturnTypeTracker(TypeTracker memberTracker) { // all non-group types get exposed as PythonType's object value = DynamicHelpers.GetPythonTypeFromType(memberTracker.Type); return new DynamicMetaObject(Ast.Constant(value), BindingRestrictions.Empty, value); } internal ScriptDomainManager/*!*/ DomainManager { get { return _context.DomainManager; } } private class ExtensionTypeInfo { public Type ExtensionType; public string PythonName; public ExtensionTypeInfo(Type extensionType, string pythonName) { ExtensionType = extensionType; PythonName = pythonName; } } internal static void AssertNotExtensionType(Type t) { foreach (ExtensionTypeInfo typeinfo in _sysTypes.Values) { Debug.Assert(typeinfo.ExtensionType != t); } Debug.Assert(t != typeof(InstanceOps)); } /// <summary> /// Creates the initial table of extension types. These are standard extension that we apply /// to well known .NET types to make working with them better. Being added to this table does /// not make a type a Python type though so that it's members are generally accessible w/o an /// import clr and their type is not re-named. /// </summary> private static Dictionary<Type/*!*/, IList<Type/*!*/>/*!*/>/*!*/ MakeExtensionTypes() { Dictionary<Type, IList<Type>> res = new Dictionary<Type, IList<Type>>(); #if FEATURE_DBNULL res[typeof(DBNull)] = new Type[] { typeof(DBNullOps) }; #endif res[typeof(List<>)] = new Type[] { typeof(ListOfTOps<>) }; res[typeof(Dictionary<,>)] = new Type[] { typeof(DictionaryOfTOps<,>) }; res[typeof(Array)] = new Type[] { typeof(ArrayOps) }; res[typeof(Assembly)] = new Type[] { typeof(PythonAssemblyOps) }; res[typeof(Enum)] = new Type[] { typeof(EnumOps) }; res[typeof(Delegate)] = new Type[] { typeof(DelegateOps) }; res[typeof(Byte)] = new Type[] { typeof(ByteOps) }; res[typeof(SByte)] = new Type[] { typeof(SByteOps) }; res[typeof(Int16)] = new Type[] { typeof(Int16Ops) }; res[typeof(UInt16)] = new Type[] { typeof(UInt16Ops) }; res[typeof(UInt32)] = new Type[] { typeof(UInt32Ops) }; res[typeof(Int64)] = new Type[] { typeof(Int64Ops) }; res[typeof(UInt64)] = new Type[] { typeof(UInt64Ops) }; res[typeof(char)] = new Type[] { typeof(CharOps) }; res[typeof(decimal)] = new Type[] { typeof(DecimalOps) }; res[typeof(float)] = new Type[] { typeof(SingleOps) }; return res; } /// <summary> /// Creates a table of standard .NET types which are also standard Python types. These types have a standard /// set of extension types which are shared between all runtimes. /// </summary> private static Dictionary<Type/*!*/, ExtensionTypeInfo/*!*/>/*!*/ MakeSystemTypes() { Dictionary<Type/*!*/, ExtensionTypeInfo/*!*/> res = new Dictionary<Type, ExtensionTypeInfo>(); // Native CLR types res[typeof(object)] = new ExtensionTypeInfo(typeof(ObjectOps), "object"); res[typeof(string)] = new ExtensionTypeInfo(typeof(StringOps), "str"); res[typeof(int)] = new ExtensionTypeInfo(typeof(Int32Ops), "int"); res[typeof(bool)] = new ExtensionTypeInfo(typeof(BoolOps), "bool"); res[typeof(double)] = new ExtensionTypeInfo(typeof(DoubleOps), "float"); res[typeof(ValueType)] = new ExtensionTypeInfo(typeof(ValueType), "ValueType"); // just hiding it's methods in the inheritance hierarchy // MS.Math types res[typeof(BigInteger)] = new ExtensionTypeInfo(typeof(BigIntegerOps), "long"); res[typeof(Complex)] = new ExtensionTypeInfo(typeof(ComplexOps), "complex"); // DLR types res[typeof(DynamicNull)] = new ExtensionTypeInfo(typeof(NoneTypeOps), "NoneType"); res[typeof(IDictionary<object, object>)] = new ExtensionTypeInfo(typeof(DictionaryOps), "dict"); res[typeof(NamespaceTracker)] = new ExtensionTypeInfo(typeof(NamespaceTrackerOps), "namespace#"); res[typeof(TypeGroup)] = new ExtensionTypeInfo(typeof(TypeGroupOps), "type-collision"); res[typeof(TypeTracker)] = new ExtensionTypeInfo(typeof(TypeTrackerOps), "type-collision"); return res; } internal static string GetTypeNameInternal(Type t) { ExtensionTypeInfo extInfo; if (_sysTypes.TryGetValue(t, out extInfo)) { return extInfo.PythonName; } var attr = t.GetCustomAttributes<PythonTypeAttribute>(false).FirstOrDefault(); if (attr != null && attr.Name != null) { return attr.Name; } return t.Name; } public static bool IsExtendedType(Type/*!*/ t) { Debug.Assert(t != null); return _sysTypes.ContainsKey(t); } public static bool IsPythonType(Type/*!*/ t) { Debug.Assert(t != null); return _sysTypes.ContainsKey(t) || t.IsDefined(typeof(PythonTypeAttribute), false); } /// <summary> /// Event handler for when our domain manager has an assembly loaded by the user hosting the script /// runtime. Here we can gather any information regarding extension methods. /// /// Currently DLR-style extension methods become immediately available w/o an explicit import step. /// </summary> private void DomainManager_AssemblyLoaded(object sender, AssemblyLoadedEventArgs e) { Assembly asm = e.Assembly; var attrs = asm.GetCustomAttributes<ExtensionTypeAttribute>(); if (attrs.Any()) { lock (_dlrExtensionTypes) { foreach (ExtensionTypeAttribute attr in attrs) { if (attr.Extends.IsInterface) { _registeredInterfaceExtensions = true; } IList<Type> typeList; if (!_dlrExtensionTypes.TryGetValue(attr.Extends, out typeList)) { _dlrExtensionTypes[attr.Extends] = typeList = new List<Type>(); } else if (typeList.IsReadOnly) { _dlrExtensionTypes[attr.Extends] = typeList = new List<Type>(typeList); } // don't add extension types twice even if we receive multiple assembly loads if (!typeList.Contains(attr.ExtensionType)) { typeList.Add(attr.ExtensionType); } } } } TopNamespaceTracker.PublishComTypes(asm); // Add it to the references tuple if we // loaded a new assembly. ClrModule.ReferencesList rl = _context.ReferencedAssemblies; lock (rl) { rl.Add(asm); } #if FEATURE_REFEMIT // load any compiled code that has been cached... LoadScriptCode(_context, asm); #endif // load any Python modules _context.LoadBuiltins(_context.BuiltinModules, asm, true); // load any cached new types NewTypeMaker.LoadNewTypes(asm); } #if FEATURE_REFEMIT private static void LoadScriptCode(PythonContext/*!*/ pc, Assembly/*!*/ asm) { ScriptCode[] codes = SavableScriptCode.LoadFromAssembly(pc.DomainManager, asm); foreach (ScriptCode sc in codes) { pc.GetCompiledLoader().AddScriptCode(sc); } } #endif internal PythonContext/*!*/ Context { get { return _context; } } /// <summary> /// Provides a cache from Type/name -> PythonTypeSlot and also allows access to /// all members (and remembering whether all members are cached). /// </summary> private class SlotCache { private Dictionary<CachedInfoKey/*!*/, SlotCacheInfo/*!*/> _cachedInfos; /// <summary> /// Writes to a cache the result of a type lookup. Null values are allowed for the slots and they indicate that /// the value does not exist. /// </summary> public void CacheSlot(Type/*!*/ type, bool isGetMember, string/*!*/ name, PythonTypeSlot slot, MemberGroup/*!*/ memberGroup) { Debug.Assert(type != null); Debug.Assert(name != null); EnsureInfo(); lock (_cachedInfos) { SlotCacheInfo slots = GetSlotForType(type, isGetMember); if (slots.ResolvedAll && slot == null && memberGroup.Count == 0) { // nothing to cache, and we know we don't need to cache non-hits. return; } slots.Members[name] = new KeyValuePair<PythonTypeSlot, MemberGroup>(slot, memberGroup); } } /// <summary> /// Looks up a cached type slot for the specified member and type. This may return true and return a null slot - that indicates /// that a cached result for a member which doesn't exist has been stored. Otherwise it returns true if a slot is found or /// false if it is not. /// </summary> public bool TryGetCachedSlot(Type/*!*/ type, bool isGetMember, string/*!*/ name, out PythonTypeSlot slot) { Debug.Assert(type != null); Debug.Assert(name != null); if (_cachedInfos != null) { lock (_cachedInfos) { SlotCacheInfo slots; if (_cachedInfos.TryGetValue(new CachedInfoKey(type, isGetMember), out slots) && (slots.TryGetSlot(name, out slot) || slots.ResolvedAll)) { return true; } } } slot = null; return false; } /// <summary> /// Looks up a cached member group for the specified member and type. This may return true and return a null group - that indicates /// that a cached result for a member which doesn't exist has been stored. Otherwise it returns true if a group is found or /// false if it is not. /// </summary> public bool TryGetCachedMember(Type/*!*/ type, string/*!*/ name, bool getMemberAction, out MemberGroup/*!*/ group) { Debug.Assert(type != null); Debug.Assert(name != null); if (_cachedInfos != null) { lock (_cachedInfos) { SlotCacheInfo slots; if (_cachedInfos.TryGetValue(new CachedInfoKey(type, getMemberAction), out slots) && (slots.TryGetMember(name, out group) || (getMemberAction && slots.ResolvedAll))) { return true; } } } group = MemberGroup.EmptyGroup; return false; } /// <summary> /// Checks to see if all members have been populated for the provided type. /// </summary> public bool IsFullyCached(Type/*!*/ type, bool isGetMember) { if (_cachedInfos != null) { lock (_cachedInfos) { SlotCacheInfo info; if (_cachedInfos.TryGetValue(new CachedInfoKey(type, isGetMember), out info)) { return info.ResolvedAll; } } } return false; } /// <summary> /// Populates the type with all the provided members and marks the type /// as being fully cached. /// /// The dictionary is used for the internal storage and should not be modified after /// providing it to the cache. /// </summary> public void CacheAll(Type/*!*/ type, bool isGetMember, Dictionary<string/*!*/, KeyValuePair<PythonTypeSlot/*!*/, MemberGroup/*!*/>> members) { Debug.Assert(type != null); EnsureInfo(); lock (_cachedInfos) { SlotCacheInfo slots = GetSlotForType(type, isGetMember); slots.Members = members; slots.ResolvedAll = true; } } /// <summary> /// Returns an enumerable object which provides access to all the members of the provided type. /// /// The caller must check that the type is fully cached and populate the cache if it isn't before /// calling this method. /// </summary> public IEnumerable<KeyValuePair<string/*!*/, PythonTypeSlot/*!*/>>/*!*/ GetAllMembers(Type/*!*/ type, bool isGetMember) { Debug.Assert(type != null); SlotCacheInfo info = GetSlotForType(type, isGetMember); Debug.Assert(info.ResolvedAll); foreach (KeyValuePair<string, PythonTypeSlot> slot in info.GetAllSlots()) { if (slot.Value != null) { yield return slot; } } } private SlotCacheInfo/*!*/ GetSlotForType(Type/*!*/ type, bool isGetMember) { SlotCacheInfo slots; var key = new CachedInfoKey(type, isGetMember); if (!_cachedInfos.TryGetValue(key, out slots)) { _cachedInfos[key] = slots = new SlotCacheInfo(); } return slots; } class CachedInfoKey : IEquatable<CachedInfoKey> { public readonly Type Type; public readonly bool IsGetMember; public CachedInfoKey(Type type, bool isGetMember) { Type = type; IsGetMember = isGetMember; } #region IEquatable<CachedInfoKey> Members public bool Equals(CachedInfoKey other) { return other.Type == Type && other.IsGetMember == IsGetMember; } #endregion public override bool Equals(object obj) { if (obj is CachedInfoKey other) { return Equals(other); } return false; } public override int GetHashCode() { return Type.GetHashCode() ^ (IsGetMember ? -1 : 0); } } private void EnsureInfo() { if (_cachedInfos == null) { Interlocked.CompareExchange(ref _cachedInfos, new Dictionary<CachedInfoKey/*!*/, SlotCacheInfo>(), null); } } private class SlotCacheInfo { public SlotCacheInfo() { Members = new Dictionary<string/*!*/, KeyValuePair<PythonTypeSlot, MemberGroup/*!*/>>(StringComparer.Ordinal); } public bool TryGetSlot(string/*!*/ name, out PythonTypeSlot slot) { Debug.Assert(name != null); KeyValuePair<PythonTypeSlot, MemberGroup> kvp; if (Members.TryGetValue(name, out kvp)) { slot = kvp.Key; return true; } slot = null; return false; } public bool TryGetMember(string/*!*/ name, out MemberGroup/*!*/ group) { Debug.Assert(name != null); KeyValuePair<PythonTypeSlot, MemberGroup> kvp; if (Members.TryGetValue(name, out kvp)) { group = kvp.Value; return true; } group = MemberGroup.EmptyGroup; return false; } public IEnumerable<KeyValuePair<string/*!*/, PythonTypeSlot>>/*!*/ GetAllSlots() { foreach (KeyValuePair<string, KeyValuePair<PythonTypeSlot, MemberGroup>> kvp in Members) { yield return new KeyValuePair<string, PythonTypeSlot>(kvp.Key, kvp.Value.Key); } } public Dictionary<string/*!*/, KeyValuePair<PythonTypeSlot, MemberGroup/*!*/>>/*!*/ Members; public bool ResolvedAll; } } } }
// 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.IO; using System.Net.Mime; using System.Runtime.ExceptionServices; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace System.Net.Mail { internal class SmtpTransport { internal const int DefaultPort = 25; private readonly ISmtpAuthenticationModule[] _authenticationModules; private SmtpConnection _connection; private readonly SmtpClient _client; private ICredentialsByHost _credentials; private readonly List<SmtpFailedRecipientException> _failedRecipientExceptions = new List<SmtpFailedRecipientException>(); private bool _identityRequired; private bool _shouldAbort; private bool _enableSsl = false; private X509CertificateCollection _clientCertificates = null; internal SmtpTransport(SmtpClient client) : this(client, SmtpAuthenticationManager.GetModules()) { } internal SmtpTransport(SmtpClient client, ISmtpAuthenticationModule[] authenticationModules) { _client = client; if (authenticationModules == null) { throw new ArgumentNullException(nameof(authenticationModules)); } _authenticationModules = authenticationModules; } internal ICredentialsByHost Credentials { get { return _credentials; } set { _credentials = value; } } internal bool IdentityRequired { get { return _identityRequired; } set { _identityRequired = value; } } internal bool IsConnected { get { return _connection != null && _connection.IsConnected; } } internal bool EnableSsl { get { return _enableSsl; } set { _enableSsl = value; } } internal X509CertificateCollection ClientCertificates { get { if (_clientCertificates == null) { _clientCertificates = new X509CertificateCollection(); } return _clientCertificates; } } internal bool ServerSupportsEai { get { return _connection != null && _connection.ServerSupportsEai; } } internal void GetConnection(string host, int port) { try { lock (this) { _connection = new SmtpConnection(this, _client, _credentials, _authenticationModules); if (_shouldAbort) { _connection.Abort(); } _shouldAbort = false; } if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _connection); if (EnableSsl) { _connection.EnableSsl = true; _connection.ClientCertificates = ClientCertificates; } _connection.GetConnection(host, port); } finally { } } internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); IAsyncResult result = null; try { _connection = new SmtpConnection(this, _client, _credentials, _authenticationModules); if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _connection); if (EnableSsl) { _connection.EnableSsl = true; _connection.ClientCertificates = ClientCertificates; } result = _connection.BeginGetConnection(outerResult, callback, state, host, port); } catch (Exception innerException) { throw new SmtpException(SR.MailHostNotFound, innerException); } if (NetEventSource.IsEnabled) { NetEventSource.Info(this, "Sync completion"); NetEventSource.Exit(this); } return result; } internal void EndGetConnection(IAsyncResult result) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); try { _connection.EndGetConnection(result); } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } } internal IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify, bool allowUnicode, AsyncCallback callback, object state) { if (sender == null) { throw new ArgumentNullException(nameof(sender)); } if (recipients == null) { throw new ArgumentNullException(nameof(recipients)); } SendMailAsyncResult result = new SendMailAsyncResult(_connection, sender, recipients, allowUnicode, _connection.DSNEnabled ? deliveryNotify : null, callback, state); result.Send(); return result; } internal void ReleaseConnection() { if (_connection != null) { _connection.ReleaseConnection(); } } internal void Abort() { lock (this) { if (_connection != null) { _connection.Abort(); } else { _shouldAbort = true; } } } internal MailWriter EndSendMail(IAsyncResult result) { try { return SendMailAsyncResult.End(result); } finally { } } internal MailWriter SendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify, bool allowUnicode, out SmtpFailedRecipientException exception) { if (sender == null) { throw new ArgumentNullException(nameof(sender)); } if (recipients == null) { throw new ArgumentNullException(nameof(recipients)); } MailCommand.Send(_connection, SmtpCommands.Mail, sender, allowUnicode); _failedRecipientExceptions.Clear(); exception = null; string response; foreach (MailAddress address in recipients) { string smtpAddress = address.GetSmtpAddress(allowUnicode); string to = smtpAddress + (_connection.DSNEnabled ? deliveryNotify : string.Empty); if (!RecipientCommand.Send(_connection, to, out response)) { _failedRecipientExceptions.Add( new SmtpFailedRecipientException(_connection.Reader.StatusCode, smtpAddress, response)); } } if (_failedRecipientExceptions.Count > 0) { if (_failedRecipientExceptions.Count == 1) { exception = _failedRecipientExceptions[0]; } else { exception = new SmtpFailedRecipientsException(_failedRecipientExceptions, _failedRecipientExceptions.Count == recipients.Count); } if (_failedRecipientExceptions.Count == recipients.Count) { exception.fatal = true; throw exception; } } DataCommand.Send(_connection); return new MailWriter(_connection.GetClosableStream(), encodeForTransport: true); } } internal class SendMailAsyncResult : LazyAsyncResult { private readonly SmtpConnection _connection; private readonly MailAddress _from; private readonly string _deliveryNotify; private static readonly AsyncCallback s_sendMailFromCompleted = new AsyncCallback(SendMailFromCompleted); private static readonly AsyncCallback s_sendToCollectionCompleted = new AsyncCallback(SendToCollectionCompleted); private static readonly AsyncCallback s_sendDataCompleted = new AsyncCallback(SendDataCompleted); private readonly List<SmtpFailedRecipientException> _failedRecipientExceptions = new List<SmtpFailedRecipientException>(); private Stream _stream; private readonly MailAddressCollection _toCollection; private int _toIndex; private readonly bool _allowUnicode; internal SendMailAsyncResult(SmtpConnection connection, MailAddress from, MailAddressCollection toCollection, bool allowUnicode, string deliveryNotify, AsyncCallback callback, object state) : base(null, state, callback) { _toCollection = toCollection; _connection = connection; _from = from; _deliveryNotify = deliveryNotify; _allowUnicode = allowUnicode; } internal void Send() { SendMailFrom(); } internal static MailWriter End(IAsyncResult result) { SendMailAsyncResult thisPtr = (SendMailAsyncResult)result; object sendMailResult = thisPtr.InternalWaitForCompletion(); // Note the difference between the singular and plural FailedRecipient exceptions. // Only fail immediately if we couldn't send to any recipients. if ((sendMailResult is Exception e) && (!(sendMailResult is SmtpFailedRecipientException) || ((SmtpFailedRecipientException)sendMailResult).fatal)) { ExceptionDispatchInfo.Throw(e); } return new MailWriter(thisPtr._stream, encodeForTransport: true); } private void SendMailFrom() { IAsyncResult result = MailCommand.BeginSend(_connection, SmtpCommands.Mail, _from, _allowUnicode, s_sendMailFromCompleted, this); if (!result.CompletedSynchronously) { return; } MailCommand.EndSend(result); SendToCollection(); } private static void SendMailFromCompleted(IAsyncResult result) { if (!result.CompletedSynchronously) { SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState; try { MailCommand.EndSend(result); thisPtr.SendToCollection(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private void SendToCollection() { while (_toIndex < _toCollection.Count) { MultiAsyncResult result = (MultiAsyncResult)RecipientCommand.BeginSend(_connection, _toCollection[_toIndex++].GetSmtpAddress(_allowUnicode) + _deliveryNotify, s_sendToCollectionCompleted, this); if (!result.CompletedSynchronously) { return; } string response; if (!RecipientCommand.EndSend(result, out response)) { _failedRecipientExceptions.Add(new SmtpFailedRecipientException(_connection.Reader.StatusCode, _toCollection[_toIndex - 1].GetSmtpAddress(_allowUnicode), response)); } } SendData(); } private static void SendToCollectionCompleted(IAsyncResult result) { if (!result.CompletedSynchronously) { SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState; try { string response; if (!RecipientCommand.EndSend(result, out response)) { thisPtr._failedRecipientExceptions.Add( new SmtpFailedRecipientException(thisPtr._connection.Reader.StatusCode, thisPtr._toCollection[thisPtr._toIndex - 1].GetSmtpAddress(thisPtr._allowUnicode), response)); if (thisPtr._failedRecipientExceptions.Count == thisPtr._toCollection.Count) { SmtpFailedRecipientException exception = null; if (thisPtr._toCollection.Count == 1) { exception = (SmtpFailedRecipientException)thisPtr._failedRecipientExceptions[0]; } else { exception = new SmtpFailedRecipientsException(thisPtr._failedRecipientExceptions, true); } exception.fatal = true; thisPtr.InvokeCallback(exception); return; } } thisPtr.SendToCollection(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private void SendData() { IAsyncResult result = DataCommand.BeginSend(_connection, s_sendDataCompleted, this); if (!result.CompletedSynchronously) { return; } DataCommand.EndSend(result); _stream = _connection.GetClosableStream(); if (_failedRecipientExceptions.Count > 1) { InvokeCallback(new SmtpFailedRecipientsException(_failedRecipientExceptions, _failedRecipientExceptions.Count == _toCollection.Count)); } else if (_failedRecipientExceptions.Count == 1) { InvokeCallback(_failedRecipientExceptions[0]); } else { InvokeCallback(); } } private static void SendDataCompleted(IAsyncResult result) { if (!result.CompletedSynchronously) { SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState; try { DataCommand.EndSend(result); thisPtr._stream = thisPtr._connection.GetClosableStream(); if (thisPtr._failedRecipientExceptions.Count > 1) { thisPtr.InvokeCallback(new SmtpFailedRecipientsException(thisPtr._failedRecipientExceptions, thisPtr._failedRecipientExceptions.Count == thisPtr._toCollection.Count)); } else if (thisPtr._failedRecipientExceptions.Count == 1) { thisPtr.InvokeCallback(thisPtr._failedRecipientExceptions[0]); } else { thisPtr.InvokeCallback(); } } catch (Exception e) { thisPtr.InvokeCallback(e); } } } // Return the list of non-terminal failures (some recipients failed but not others). internal SmtpFailedRecipientException GetFailedRecipientException() { if (_failedRecipientExceptions.Count == 1) { return (SmtpFailedRecipientException)_failedRecipientExceptions[0]; } else if (_failedRecipientExceptions.Count > 1) { // Aggregate exception, multiple failures return new SmtpFailedRecipientsException(_failedRecipientExceptions, false); } return null; } } }
using System; using System.Linq; using SFML.Graphics; using SFML.Window; namespace NetGore.Graphics.GUI { /// <summary> /// A control containing a checkbox and a line of text to label it /// </summary> public class CheckBox : Label { /// <summary> /// The name of this <see cref="Control"/> for when looking up the skin information. /// </summary> const string _controlSkinName = "CheckBox"; /// <summary> /// Amount of space added between the check box and text /// </summary> const float _textXAdjust = 2f; static readonly object _eventTickedOverSpriteChanged = new object(); static readonly object _eventTickedPressedSpriteChanged = new object(); static readonly object _eventTickedSpriteChanged = new object(); static readonly object _eventUntickedOverSpriteChanged = new object(); static readonly object _eventUntickedPressedSpriteChanged = new object(); static readonly object _eventUntickedSpriteChanged = new object(); static readonly object _eventValueChanged = new object(); CheckBoxState _state = CheckBoxState.None; ISprite _ticked; ISprite _tickedOver; ISprite _tickedPressed; ISprite _unticked; ISprite _untickedOver; ISprite _untickedPressed; bool _value = false; /// <summary> /// Initializes a new instance of the <see cref="Label"/> class. /// </summary> /// <param name="parent">Parent <see cref="Control"/> of this <see cref="Control"/>.</param> /// <param name="position">Position of the Control reletive to its parent.</param> /// <exception cref="NullReferenceException"><paramref name="parent"/> is null.</exception> public CheckBox(Control parent, Vector2 position) : base(parent, position) { HandleAutoResize(); } /// <summary> /// Initializes a new instance of the <see cref="Label"/> class. /// </summary> /// <param name="guiManager">The GUI manager this <see cref="Control"/> will be managed by.</param> /// <param name="position">Position of the Control reletive to its parent.</param> /// <exception cref="ArgumentNullException"><paramref name="guiManager"/> is null.</exception> public CheckBox(IGUIManager guiManager, Vector2 position) : base(guiManager, position) { HandleAutoResize(); } /// <summary> /// Notifies listeners when the <see cref="CheckBox.TickedOverSprite"/> changes. /// </summary> public event TypedEventHandler<Control> TickedOverSpriteChanged { add { Events.AddHandler(_eventTickedOverSpriteChanged, value); } remove { Events.RemoveHandler(_eventTickedOverSpriteChanged, value); } } /// <summary> /// Notifies listeners when the <see cref="CheckBox.TickedPressedSprite"/> changes. /// </summary> public event TypedEventHandler<Control> TickedPressedSpriteChanged { add { Events.AddHandler(_eventTickedPressedSpriteChanged, value); } remove { Events.RemoveHandler(_eventTickedPressedSpriteChanged, value); } } /// <summary> /// Notifies listeners when the <see cref="CheckBox.TickedSprite"/> changes. /// </summary> public event TypedEventHandler<Control> TickedSpriteChanged { add { Events.AddHandler(_eventTickedSpriteChanged, value); } remove { Events.RemoveHandler(_eventTickedSpriteChanged, value); } } /// <summary> /// Notifies listeners when the <see cref="CheckBox.UntickedOverSprite"/> changes. /// </summary> public event TypedEventHandler<Control> UntickedOverSpriteChanged { add { Events.AddHandler(_eventUntickedOverSpriteChanged, value); } remove { Events.RemoveHandler(_eventUntickedOverSpriteChanged, value); } } /// <summary> /// Notifies listeners when the <see cref="CheckBox.UntickedPressedSprite"/> changes. /// </summary> public event TypedEventHandler<Control> UntickedPressedSpriteChanged { add { Events.AddHandler(_eventUntickedPressedSpriteChanged, value); } remove { Events.RemoveHandler(_eventUntickedPressedSpriteChanged, value); } } /// <summary> /// Notifies listeners when the <see cref="CheckBox.UntickedSprite"/> changes. /// </summary> public event TypedEventHandler<Control> UntickedSpriteChanged { add { Events.AddHandler(_eventUntickedSpriteChanged, value); } remove { Events.RemoveHandler(_eventUntickedSpriteChanged, value); } } /// <summary> /// Notifies listeners when the <see cref="CheckBox.Value"/> changes. /// </summary> public event TypedEventHandler<Control> ValueChanged { add { Events.AddHandler(_eventValueChanged, value); } remove { Events.RemoveHandler(_eventValueChanged, value); } } /// <summary> /// Gets or sets the Sprite used for a ticked checkbox with the mouse over it /// </summary> public ISprite TickedOverSprite { get { return _ticked; } set { if (_tickedOver == value) return; _tickedOver = value; InvokeTickedOverSpriteChanged(); } } /// <summary> /// Gets or sets the Sprite used for a ticked checkbox being pressed /// </summary> public ISprite TickedPressedSprite { get { return _ticked; } set { if (_ticked == value) return; _ticked = value; InvokeTickedPressedSpriteChanged(); } } /// <summary> /// Gets or sets the Sprite used for a ticked checkbox /// </summary> public ISprite TickedSprite { get { return _ticked; } set { if (_ticked == value) return; _ticked = value; InvokeTickedSpriteChanged(); } } /// <summary> /// Gets or sets the Sprite used for an unticked checkbox with the mouse over it /// </summary> public ISprite UntickedOverSprite { get { return _untickedOver; } set { if (_untickedOver == value) return; _untickedOver = value; InvokeUntickedOverSpriteChanged(); } } /// <summary> /// Gets or sets the Sprite used for an unticked checkbox being pressed /// </summary> public ISprite UntickedPressedSprite { get { return _untickedPressed; } set { if (_untickedPressed == value) return; _untickedPressed = value; InvokeUntickedPressedSpriteChanged(); } } /// <summary> /// Gets or sets the Sprite used for an unticked checkbox /// </summary> public ISprite UntickedSprite { get { return _unticked; } set { if (_unticked == value) return; _unticked = value; InvokeUntickedSpriteChanged(); } } /// <summary> /// Gets or sets if the <see cref="CheckBox"/> is ticked. /// </summary> [SyncValue] public bool Value { get { return _value; } set { if (_value == value) return; _value = value; InvokeValueChanged(); } } /// <summary> /// Draws the control. /// </summary> /// <param name="spriteBatch"><see cref="ISpriteBatch"/> to draw to.</param> protected override void DrawControl(ISpriteBatch spriteBatch) { // Draw the border Border.Draw(spriteBatch, this); // Find the sprite based on the state and value ISprite sprite; if (Value) { if (_state == CheckBoxState.Pressed) sprite = _tickedPressed; else if (_state == CheckBoxState.Over) sprite = _tickedOver; else sprite = _ticked; if (sprite == null) sprite = _ticked; } else { if (_state == CheckBoxState.Pressed) sprite = _untickedPressed; else if (_state == CheckBoxState.Over) sprite = _untickedOver; else sprite = _unticked; if (sprite == null) sprite = _unticked; } // Validate the sprite if (sprite == null) return; // Find the text offset var textOffset = new Vector2(sprite.Source.Width + _textXAdjust, 0); // Draw the checkbox if (sprite.Texture != null) spriteBatch.Draw(sprite.Texture, ScreenPosition, sprite.Source, Color.White); // Draw the text DrawText(spriteBatch, textOffset); } /// <summary> /// Handles control resizing. /// </summary> void HandleAutoResize() { // Start with the size of the text var textSize = Font.MeasureString(Text); // Add the width of checkbox textSize.X += Math.Max(_unticked.Source.Width, _ticked.Source.Width); // Set the height to the largest of either the text or checkbox textSize.Y = Math.Max(textSize.Y, Math.Max(_unticked.Source.Height, _ticked.Source.Height)); // Add the space between the checkbox and text textSize.X += _textXAdjust; // Set the new size Size = textSize; } /// <summary> /// Invokes the corresponding virtual method and event for the given event. Use this instead of invoking /// the virtual method and event directly to ensure that the event is invoked correctly. /// </summary> void InvokeTickedOverSpriteChanged() { OnTickedOverSpriteChanged(); var handler = Events[_eventTickedOverSpriteChanged] as TypedEventHandler<Control>; if (handler != null) handler(this, EventArgs.Empty); } /// <summary> /// Invokes the corresponding virtual method and event for the given event. Use this instead of invoking /// the virtual method and event directly to ensure that the event is invoked correctly. /// </summary> void InvokeTickedPressedSpriteChanged() { OnTickedPressedSpriteChanged(); var handler = Events[_eventTickedPressedSpriteChanged] as TypedEventHandler<Control>; if (handler != null) handler(this, EventArgs.Empty); } /// <summary> /// Invokes the corresponding virtual method and event for the given event. Use this instead of invoking /// the virtual method and event directly to ensure that the event is invoked correctly. /// </summary> void InvokeTickedSpriteChanged() { OnTickedSpriteChanged(); var handler = Events[_eventTickedSpriteChanged] as TypedEventHandler<Control>; if (handler != null) handler(this, EventArgs.Empty); } /// <summary> /// Invokes the corresponding virtual method and event for the given event. Use this instead of invoking /// the virtual method and event directly to ensure that the event is invoked correctly. /// </summary> void InvokeUntickedOverSpriteChanged() { OnUntickedOverSpriteChanged(); var handler = Events[_eventUntickedOverSpriteChanged] as TypedEventHandler<Control>; if (handler != null) handler(this, EventArgs.Empty); } /// <summary> /// Invokes the corresponding virtual method and event for the given event. Use this instead of invoking /// the virtual method and event directly to ensure that the event is invoked correctly. /// </summary> void InvokeUntickedPressedSpriteChanged() { OnUntickedPressedSpriteChanged(); var handler = Events[_eventUntickedPressedSpriteChanged] as TypedEventHandler<Control>; if (handler != null) handler(this, EventArgs.Empty); } /// <summary> /// Invokes the corresponding virtual method and event for the given event. Use this instead of invoking /// the virtual method and event directly to ensure that the event is invoked correctly. /// </summary> void InvokeUntickedSpriteChanged() { OnUntickedSpriteChanged(); var handler = Events[_eventUntickedSpriteChanged] as TypedEventHandler<Control>; if (handler != null) handler(this, EventArgs.Empty); } /// <summary> /// Invokes the corresponding virtual method and event for the given event. Use this instead of invoking /// the virtual method and event directly to ensure that the event is invoked correctly. /// </summary> void InvokeValueChanged() { OnValueChanged(); var handler = Events[_eventValueChanged] as TypedEventHandler<Control>; if (handler != null) handler(this, EventArgs.Empty); } /// <summary> /// When overridden in the derived class, loads the skinning information for the <see cref="Control"/> /// from the given <paramref name="skinManager"/>. /// </summary> /// <param name="skinManager">The <see cref="ISkinManager"/> to load the skinning information from.</param> public override void LoadSkin(ISkinManager skinManager) { base.LoadSkin(skinManager); _ticked = skinManager.GetControlSprite(_controlSkinName, "Ticked"); _tickedOver = skinManager.GetControlSprite(_controlSkinName, "TickedMouseOver"); _tickedPressed = skinManager.GetControlSprite(_controlSkinName, "TickedPressed"); _unticked = skinManager.GetControlSprite(_controlSkinName, "Unticked"); _untickedOver = skinManager.GetControlSprite(_controlSkinName, "UntickedMouseOver"); _untickedPressed = skinManager.GetControlSprite(_controlSkinName, "UntickedPressed"); } /// <summary> /// Handles when the <see cref="TextControl.Font"/> has changed. /// This is called immediately before <see cref="TextControl.FontChanged"/>. /// Override this method instead of using an event hook on <see cref="TextControl.FontChanged"/> when possible. /// </summary> protected override void OnFontChanged() { base.OnFontChanged(); HandleAutoResize(); } /// <summary> /// Handles when the <see cref="Control"/> has lost focus. /// This is called immediately before <see cref="Control.OnLostFocus"/>. /// Override this method instead of using an event hook on <see cref="Control.LostFocus"/> when possible. /// </summary> protected override void OnLostFocus() { base.OnLostFocus(); _state = CheckBoxState.None; } /// <summary> /// Handles when a mouse button has been pressed down on this <see cref="Control"/>. /// This is called immediately before <see cref="Control.OnMouseDown"/>. /// Override this method instead of using an event hook on <see cref="Control.MouseDown"/> when possible. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); if (e.Button == Mouse.Button.Left) { Value = !_value; _state = CheckBoxState.Pressed; } } /// <summary> /// Handles when the mouse has entered the area of the <see cref="Control"/>. /// This is called immediately before <see cref="Control.OnMouseEnter"/>. /// Override this method instead of using an event hook on <see cref="Control.MouseEnter"/> when possible. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseEnter(MouseMoveEventArgs e) { base.OnMouseEnter(e); _state = CheckBoxState.Over; } /// <summary> /// Handles when the mouse has left the area of the <see cref="Control"/>. /// This is called immediately before <see cref="Control.OnMouseLeave"/>. /// Override this method instead of using an event hook on <see cref="Control.MouseLeave"/> when possible. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseLeave(MouseMoveEventArgs e) { base.OnMouseLeave(e); _state = CheckBoxState.None; } /// <summary> /// Handles when the mouse has moved over the <see cref="Control"/>. /// This is called immediately before <see cref="Control.MouseMoved"/>. /// Override this method instead of using an event hook on <see cref="Control.MouseMoved"/> when possible. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseMoved(MouseMoveEventArgs e) { base.OnMouseMoved(e); _state = CheckBoxState.Over; } /// <summary> /// Handles when a mouse button has been raised on the <see cref="Control"/>. /// This is called immediately before <see cref="Control.OnMouseUp"/>. /// Override this method instead of using an event hook on <see cref="Control.MouseUp"/> when possible. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseUp(MouseButtonEventArgs e) { base.OnMouseUp(e); _state = CheckBoxState.Over; } /// <summary> /// Handles when the <see cref="TextControl.Text"/> has changed. /// This is called immediately before <see cref="TextControl.TextChanged"/>. /// Override this method instead of using an event hook on <see cref="TextControl.TextChanged"/> when possible. /// </summary> protected override void OnTextChanged() { base.OnTextChanged(); HandleAutoResize(); } /// <summary> /// Handles when the <see cref="CheckBox.TickedOverSprite"/> changes. /// This is called immediately before <see cref="CheckBox.TickedOverSpriteChanged"/>. /// Override this method instead of using an event hook on <see cref="CheckBox.TickedOverSpriteChanged"/> when possible. /// </summary> protected virtual void OnTickedOverSpriteChanged() { HandleAutoResize(); } /// <summary> /// Handles when the <see cref="CheckBox.TickedPressedSprite"/> changes. /// This is called immediately before <see cref="CheckBox.TickedPressedSpriteChanged"/>. /// Override this method instead of using an event hook on <see cref="CheckBox.TickedPressedSpriteChanged"/> when possible. /// </summary> protected virtual void OnTickedPressedSpriteChanged() { HandleAutoResize(); } /// <summary> /// Handles when the <see cref="CheckBox.TickedSprite"/> changes. /// This is called immediately before <see cref="CheckBox.TickedSpriteChanged"/>. /// Override this method instead of using an event hook on <see cref="CheckBox.TickedSpriteChanged"/> when possible. /// </summary> protected virtual void OnTickedSpriteChanged() { HandleAutoResize(); } /// <summary> /// Handles when the <see cref="CheckBox.UntickedOverSprite"/> changes. /// This is called immediately before <see cref="CheckBox.UntickedOverSpriteChanged"/>. /// Override this method instead of using an event hook on <see cref="CheckBox.UntickedOverSpriteChanged"/> when possible. /// </summary> protected virtual void OnUntickedOverSpriteChanged() { HandleAutoResize(); } /// <summary> /// Handles when the <see cref="CheckBox.UntickedPressedSprite"/> changes. /// This is called immediately before <see cref="CheckBox.UntickedPressedSpriteChanged"/>. /// Override this method instead of using an event hook on <see cref="CheckBox.UntickedPressedSpriteChanged"/> when possible. /// </summary> protected virtual void OnUntickedPressedSpriteChanged() { HandleAutoResize(); } /// <summary> /// Handles when the <see cref="CheckBox.UntickedSprite"/> changes. /// This is called immediately before <see cref="CheckBox.UntickedSpriteChanged"/>. /// Override this method instead of using an event hook on <see cref="CheckBox.UntickedSpriteChanged"/> when possible. /// </summary> protected virtual void OnUntickedSpriteChanged() { HandleAutoResize(); } /// <summary> /// Handles when the <see cref="CheckBox.Value"/> changes. /// This is called immediately before <see cref="CheckBox.ValueChanged"/>. /// Override this method instead of using an event hook on <see cref="CheckBox.ValueChanged"/> when possible. /// </summary> protected virtual void OnValueChanged() { } /// <summary> /// Sets the default values for the <see cref="Control"/>. This should always begin with a call to the /// base class's method to ensure that changes to settings are hierchical. /// </summary> protected override void SetDefaultValues() { base.SetDefaultValues(); CanFocus = true; } enum CheckBoxState { None, Over, Pressed } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using 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> /// RouteFilterRulesOperations operations. /// </summary> internal partial class RouteFilterRulesOperations : IServiceOperations<NetworkManagementClient>, IRouteFilterRulesOperations { /// <summary> /// Initializes a new instance of the RouteFilterRulesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RouteFilterRulesOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified rule from a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified rule from a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RouteFilterRule>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeFilterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeFilterName", routeFilterName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RouteFilterRule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_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; } /// <summary> /// Creates or updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the create or update route filter rule operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RouteFilterRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<RouteFilterRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the update route filter rule operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RouteFilterRule>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<RouteFilterRule> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all RouteFilterRules in a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeFilterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeFilterName", routeFilterName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByRouteFilter", 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.Network/routeFilters/{routeFilterName}/routeFilterRules").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteFilterRule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilterRule>>(_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; } /// <summary> /// Deletes the specified rule from a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeFilterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeFilterName", routeFilterName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", 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.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _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 != 202 && (int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the create or update route filter rule operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RouteFilterRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeFilterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (routeFilterRuleParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterRuleParameters"); } if (routeFilterRuleParameters != null) { routeFilterRuleParameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (routeFilterRuleParameters == null) { routeFilterRuleParameters = new RouteFilterRule(); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeFilterName", routeFilterName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("routeFilterRuleParameters", routeFilterRuleParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", 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.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; if(routeFilterRuleParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterRuleParameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RouteFilterRule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_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; } /// <summary> /// Updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the update route filter rule operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RouteFilterRule>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeFilterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (routeFilterRuleParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterRuleParameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (routeFilterRuleParameters == null) { routeFilterRuleParameters = new PatchRouteFilterRule(); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeFilterName", routeFilterName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("routeFilterRuleParameters", routeFilterRuleParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", 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.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(routeFilterRuleParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterRuleParameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RouteFilterRule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_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; } /// <summary> /// Gets all RouteFilterRules in a route filter. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByRouteFilterNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteFilterRule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilterRule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; /// <summary> /// Convert.ToString(System.Int64,System.IFormatProvider) /// </summary> public class ConvertToString20 { public static int Main() { ConvertToString20 testObj = new ConvertToString20(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Int64,System.IFormatProvider)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Verify value is a random Int64 and IFormatProvider is a null reference... "; string c_TEST_ID = "P001"; Int64 intValue = TestLibrary.Generator.GetInt64(-55); IFormatProvider provider = null; String actualValue = intValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n Int64 value is " + intValue; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify value is a random Int64 and IFormatProvider is en-US CultureInfo... "; string c_TEST_ID = "P002"; Int64 intValue = TestLibrary.Generator.GetInt64(-55); IFormatProvider provider = new CultureInfo("en-US"); String actualValue = intValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n Int64 value is " + intValue; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string c_TEST_DESC = "PosTest3: Verify value is a random Int64 and IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P003"; Int64 intValue = TestLibrary.Generator.GetInt64(-55); IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = intValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n Int64 value is " + intValue; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string c_TEST_DESC = "PosTest4: Verify value is -64465641235 and IFormatProvider is user-defined NumberFormatInfo... "; string c_TEST_ID = "P004"; Int64 intValue = -465641235; NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); numberFormatInfo.NegativeSign = "minus "; numberFormatInfo.NumberDecimalSeparator = " point "; String actualValue = "minus 465641235"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, numberFormatInfo); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n Int64 value is " + intValue; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string c_TEST_DESC = "PosTest5: Verify value is Int64.MaxValue and IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P005"; Int64 intValue = Int64.MaxValue; IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = "9223372036854775807"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; string c_TEST_DESC = "PosTest6: Verify value is Int64.MinValue and IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P006"; Int64 intValue = Int64.MinValue; IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = "-9223372036854775808"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion }
#region File Description //----------------------------------------------------------------------------- // Board.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using System.Diagnostics; #endregion namespace Pickture { /// <summary> /// A puzzle board. /// </summary> class Board { #region Fields // Board dimensions int width; int height; bool twoSided; // Board layout List<Chip> chips = new List<Chip>(); Chip[,] layout; Matrix[,] boardPositionMatrices; const float ChipSpacing = 1.0f; int emptyX; int emptyY; // Rendering properties Camera camera; Lighting lighting = new Lighting(); LightingEffect lightingEffect = new LightingEffect(); Model chipModel; Matrix[] chipTransforms; PictureSet currentPictureSet = null; PictureSet nextPictureSet = null; // Controls animating between textures float textureRotationTime = 0.0f; float textureRotationDuration = 2.5f; // Controls animated chip shifting List<Chip> shiftingChips = new List<Chip>(); int shiftX; int shiftY; float currentShiftTime; const float ShiftDuration = 0.1f; #endregion #region Properties public int Width { get { return width; } } public int Height { get { return height; } } public bool TwoSided { get { return twoSided; } } public IEnumerable<Chip> Chips { get { return chips; } } public Chip GetChip(int x, int y) { return layout[x, y]; } public int EmptyX { get { return emptyX; } } public int EmptyY { get { return emptyY; } } public Camera Camera { get { return this.camera; } } public LightingEffect LightingEffect { get { return lightingEffect; } } public PictureSet CurrentPictureSet { get { return currentPictureSet; } } public PictureSet NextPictureSet { get { return nextPictureSet; } } public bool IsShifting { get { return shiftingChips.Count > 0; } } public int ShiftX { get { return shiftX; } } public int ShiftY { get { return shiftY; } } #endregion #region Initialization public Board(int sizeX, int sizeY, bool twoSided) { this.twoSided = twoSided; this.width = sizeX; this.height = sizeY; camera = new Camera((float)Math.Max(sizeX, sizeY) * 400.0f / 5.0f); nextPictureSet = PictureDatabase.GetNextPictureSet(twoSided ? 2 : 1); this.layout = new Chip[Width, Height]; this.boardPositionMatrices = new Matrix[Width, Height]; // Create all the chips for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { Chip chip = new Chip(); chips.Add(chip); chip.XPosition = x; chip.YPosition = y; layout[x, y] = chip; Vector2 chipTexCoordFactor = new Vector2(1.0f / Width, 1.0f / Height); chip.TexCoordScale = chipTexCoordFactor; chip.TexCoordTranslationFront = new Vector2((x * chipTexCoordFactor.X), ((Height - 1) - y) * chipTexCoordFactor.Y); chip.TexCoordTranslationBack = new Vector2(((Width - 1) - x) * chipTexCoordFactor.X, ((Height - 1) - y) * chipTexCoordFactor.Y); } } // Remove one random chip emptyX = RandomHelper.Random.Next(0, Width); emptyY = RandomHelper.Random.Next(0, Height); Chip removed = layout[emptyX, emptyY]; chips.Remove(removed); layout[emptyX, emptyY] = null; } public void LoadContent() { chipModel = Pickture.Instance.Content.Load<Model>("Models/Chip"); // Cache the chip transforms chipTransforms = new Matrix[chipModel.Bones.Count]; chipModel.CopyAbsoluteBoneTransformsTo(chipTransforms); // Now that we have the chip model, we can get its size // The size comes from mesh[0]'s bounding sphere radius which must be // transformed by the mesh's bone. Here, we simply scale by the X or Y // scale, whichever is larger. We don't care about the Z scale because // the chips are only placed in the XY plane. float sphereScale = Math.Max(chipTransforms[0].M11, chipTransforms[0].M22); float chipSize = chipModel.Meshes[0].BoundingSphere.Radius * sphereScale * ChipSpacing; // For each board location for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { // We use the chip size to determine the transformation matrix // for a chip at that location Vector3 chipPos = new Vector3( (Width - 1) * -0.5f, (Height - 1) * -0.5f, 0.0f); chipPos += new Vector3(x, y, 0.0f); chipPos *= chipSize; boardPositionMatrices[x, y] = Matrix.CreateTranslation(chipPos); } } if (currentPictureSet != null) currentPictureSet.Load(); if (nextPictureSet != null) nextPictureSet.Load(); lightingEffect.LoadContent(); } public void UnloadContent() { // Don't unload the current picture set, the completed screen may use it if (nextPictureSet != null) nextPictureSet.Unload(); } #endregion #region Board interaction /// <summary> /// Determines if the puzzle has been completely solved. /// </summary> /// <returns>True when all of the chips are in the correct location with the /// correct orientation. Otherwise, returns false.</returns> public bool IsPuzzleComplete() { for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { Chip chip = layout[x, y]; if (chip != null) { if (chip.XPosition != x || chip.YPosition != y) { return false; } if (!chip.HorizontalRotationCorrect || !chip.VerticalRotationCorrect) { return false; } } } } return true; } /// <summary> /// Shifts a chip and all the chips inbetween towards the empty space. /// </summary> /// <param name="fromX">The X position of the chip to be shifted.</param> /// <param name="fromY">The Y position of the chip to be shifted.</param> public void Shift(int fromX, int fromY) { // If an animated shift is already in progress, do not shift again if (IsShifting) return; // Determine the shift direction shiftX = Math.Sign(emptyX - fromX); shiftY = Math.Sign(emptyY - fromY); // Shifts can only occur along axis aligned unit vectors if (Math.Abs(shiftX) + Math.Abs(shiftY) == 1) { currentShiftTime = 0.0f; Audio.Play("Shift Chip"); // Loop from the empty space to the shift origin, shifting each chip // along the way, until the origin is now the empty space while (emptyX != fromX || emptyY != fromY) { int nextEmptyX = emptyX - shiftX; int nextEmptyY = emptyY - shiftY; // Shift the current chip Chip chip = layout[nextEmptyX, nextEmptyY]; layout[emptyX, emptyY] = chip; // Include this chip for shifting animation shiftingChips.Add(chip); emptyX = nextEmptyX; emptyY = nextEmptyY; } // Now this chip at the shift origin is the empty space layout[fromX, fromY] = null; } } #endregion #region Update and Draw public void Update(GameTime gameTime) { this.camera.Update(gameTime); this.lighting.Update(gameTime, camera); // When there is a "next picture set" animate a cross fade to it if (nextPictureSet != null) { textureRotationTime += (float)gameTime.ElapsedRealTime.TotalSeconds; if (textureRotationTime >= textureRotationDuration) { // The current textures are no longer needed if (currentPictureSet != null) currentPictureSet.Unload(); // because the next texture set are now current currentPictureSet = nextPictureSet; nextPictureSet = null; textureRotationTime = 0.0f; } } if (IsShifting) { // Animate shift time currentShiftTime += (float)gameTime.ElapsedGameTime.TotalSeconds; if (currentShiftTime > ShiftDuration) { // Stop shifting shiftingChips.Clear(); shiftX = 0; shiftY = 0; } } // Update all chips foreach (Chip chip in chips) chip.Update(gameTime); } public void Draw() { lightingEffect.LightPos.SetValue(this.lighting.Position); lightingEffect.CameraPos.SetValue(this.camera.Position); DrawHelper.SetState(); // For each board location for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { Chip chip = layout[x, y]; // Nothing to draw for the empty space if (chip == null) continue; // Determine the base transformation matrix for this chip. Only // translation is accounted for here, orientation is added by the // chip itself in its Draw method. Matrix transform; if (shiftingChips.Contains(chip)) { // When a chip is shifted, it is put in its new location in the // layout, but its rendered location is linearly interpolated // back to its previous location. Matrix.Lerp(ref boardPositionMatrices[x - shiftX, y - shiftY], ref boardPositionMatrices[x, y], currentShiftTime / ShiftDuration, out transform); } else { transform = boardPositionMatrices[x, y]; } chip.Draw(this, chipModel, transform, chipTransforms); } } } #endregion } }
/* * Copyright 2014 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ //// TODO: //// [O] Contracts //// [O] Documentation //// [ ] Performance: NameTable could make in AtomEntry.ReadXmlAsync and //// AtomFeed.ReadXmlAsync significantly faster. //// [ ] Synchronization: AtomFeed.ReadXmlAsync and AtomEntry.ReadXmlAsync can //// be called more than once. (In practice these methods are never called //// move than once.) namespace Splunk.Client { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.Contracts; using System.Dynamic; using System.Globalization; using System.IO; using System.Text; using System.Threading.Tasks; using System.Xml; /// <summary> /// Provides an object representation of an individual entry in a Splunk Atom /// Feed response. /// <para> /// <para><b>References:</b></para> /// <list type="number"> /// <item><description> /// <a href="http://goo.gl/TDthxd">REST API Reference Manual: Accessing /// Splunk resources</a>. /// </description></item> /// <item><description> /// <a href="http://goo.gl/YVTE9l">REST API Reference Manual: Atom Feed /// responses</a>. /// </description></item> /// </list> /// </para> /// </summary> public sealed class AtomEntry { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="AtomEntry"/> class. /// </summary> public AtomEntry() { } #endregion #region Properties /// <summary> /// Gets the owner of the resource represented by the current /// <see cref="AtomEntry"/>, as defined in the access control list. /// </summary> /// <remarks> /// This value can be <c>"system"</c>, <c>"nobody"</c> or some specific user /// name. Refer to <a href="http://goo.gl/iTpzO0">Access control lists for /// Splunk objects</a> in the section on /// <a href= "http://goo.gl/TDthxd">Accessing Splunk resources</a>. /// </remarks> /// <value> /// Owner of the resource represented by the current <see cref= "AtomEntry"/>. /// </value> public string Author { get; private set; } /// <summary> /// Gets a dynamic object representing the content of the resource /// represented by the current <see cref="AtomEntry"/>. /// </summary> /// <remarks> /// Splunk typically returns content as dictionaries with key/value pairs /// that list properties of the entry. However, content can be returned as a /// list of values or as plain text. /// </remarks> /// <value> /// A dynamic object representing the content of the resource represented by /// the current <see cref="AtomEntry"/>. /// </value> public dynamic Content { get; private set; } /// <summary> /// Gets the Splunk management URI for accessing the resource represented by /// the current <see cref="AtomEntry"/>. /// </summary> /// <value> /// The Splunk management URI for accessing the resource represented by the /// current <see cref="AtomEntry"/>. /// </value> public Uri Id { get; private set; } /// <summary> /// Gets the links. /// </summary> /// <value> /// The links. /// </value> public IReadOnlyDictionary<string, Uri> Links { get; private set; } /// <summary> /// Gets the Date/Time of the published. /// </summary> /// <value> /// The published. /// </value> public DateTime Published { get; private set; } /// <summary> /// Gets the human readable name for the current <see cref="AtomEntry"/>. /// </summary> /// <remarks> /// This value varies depending on the endpoint used to access the current /// <see cref="AtomEntry"/>. /// </remarks> /// <value> /// The human readable name for the current <see cref="AtomEntry"/>. /// </value> public string Title { get; private set; } /// <summary> /// Gets the date and time the current <see cref="AtomEntry"/> was last /// updated in Splunk. /// </summary> /// <value> /// The date and time the current <see cref="AtomEntry"/> was last updated in /// Splunk. /// </value> public DateTime Updated { get; private set; } #endregion #region Methods /// <summary> /// Asynchronously reads XML data into the current <see cref="AtomEntry"/>. /// </summary> /// <exception cref="InvalidDataException"> /// Thrown when an Invalid Data error condition occurs. /// </exception> /// <param name="reader"> /// The reader from which to read. /// </param> /// <returns> /// A <see cref="Task"/> representing the operation. /// </returns> public async Task ReadXmlAsync(XmlReader reader) { Contract.Requires<ArgumentNullException>(reader != null, "reader"); this.Author = null; this.Content = null; this.Id = null; this.Links = null; this.Published = DateTime.MinValue; this.Title = null; this.Updated = DateTime.MinValue; reader.Requires(await reader.MoveToDocumentElementAsync("entry").ConfigureAwait(false)); Dictionary<string, Uri> links = null; await reader.ReadAsync().ConfigureAwait(false); while (reader.NodeType == XmlNodeType.Element) { string name = reader.Name; switch (name) { case "title": this.Title = await reader.ReadElementContentAsync(StringConverter.Instance).ConfigureAwait(false); break; case "id": this.Id = await reader.ReadElementContentAsync(UriConverter.Instance).ConfigureAwait(false); break; case "author": await reader.ReadAsync().ConfigureAwait(false); reader.EnsureMarkup(XmlNodeType.Element, "name"); this.Author = await reader.ReadElementContentAsync(StringConverter.Instance).ConfigureAwait(false); reader.EnsureMarkup(XmlNodeType.EndElement, "author"); await reader.ReadAsync().ConfigureAwait(false); break; case "published": this.Published = await reader.ReadElementContentAsync(DateTimeConverter.Instance).ConfigureAwait(false); break; case "updated": this.Updated = await reader.ReadElementContentAsync(DateTimeConverter.Instance).ConfigureAwait(false); break; case "link": if (links == null) { links = new Dictionary<string, Uri>(); } var href = reader.GetRequiredAttribute("href"); var rel = reader.GetRequiredAttribute("rel"); links[rel] = UriConverter.Instance.Convert(href); await reader.ReadAsync().ConfigureAwait(false); break; case "content": this.Content = await ParsePropertyValueAsync(reader, 0).ConfigureAwait(false); break; default: throw new InvalidDataException(); // TODO: Diagnostics : unexpected start tag } } reader.EnsureMarkup(XmlNodeType.EndElement, "entry"); await reader.ReadAsync().ConfigureAwait(false); if (links != null) { this.Links = new ReadOnlyDictionary<string, Uri>(links); } } /// <summary> /// Gets a string representation for the current <see cref="AtomEntry"/>. /// </summary> /// <returns> /// A string representation of the current <see cref="AtomEntry"/>. /// </returns> /// <seealso cref="M:System.Object.ToString()"/> public override string ToString() { var text= string.Format(CultureInfo.CurrentCulture, "AtomEntry(Title={0}, Author={1}, Id={2}, Published={3}, Updated={4})", this.Title, this.Author, this.Id, this.Published, this.Updated); return text; } #endregion #region Privates static string NormalizePropertyName(string name) { Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(name)); var builder = new StringBuilder(name.Length); int index = 0; // Leading underscores distinguish some names while (name[index] == '_') { builder.Append('_'); if (++index >= name.Length) { return builder.ToString(); } } for (; ; ) { // We squeeze out dashes, dots, and all but the leading underscores while (name[index] == '_' || name[index] == '.' || name[index] == '-') { if (++index >= name.Length) { return builder.ToString(); } } // We capitalize the first character following [_.-] builder.Append(char.ToUpper(name[index])); if (++index >= name.Length) { return builder.ToString(); } // We don't alter the case of subsequent characters following [_.-] while (!(name[index] == '_' || name[index] == '.' || name[index] == '-')) { builder.Append(name[index]); if (++index >= name.Length) { return builder.ToString(); } } } } static async Task<dynamic> ParseDictionaryAsync(XmlReader reader, int level) { var value = (IDictionary<string, dynamic>)new ExpandoObject(); if (!reader.IsEmptyElement) { await reader.ReadAsync().ConfigureAwait(false); while (reader.NodeType == XmlNodeType.Element && reader.Name == "s:key") { string name = reader.GetAttribute("name"); // TODO: Include a domain-specific name translation capability (?) if (level == 0) { switch (name) { case "action.email.subject.alert": name = "action.email.subject_alert"; break; case "action.email.subject.report": name = "action.email.subject_report"; break; case "action.email": case "action.populate_lookup": case "action.rss": case "action.script": case "action.summary_index": case "alert.suppress": case "auto_summarize": name += ".IsEnabled"; break; case "alert_comparator": name = "alert.comparator"; break; case "alert_condition": name = "alert.condition"; break; case "alert_threshold": name = "alert.threshold"; break; case "alert_type": name = "alert.type"; break; case "coldPath.maxDataSizeMB": name = "coldPath_maxDataSizeMB"; break; case "display.visualizations.charting.chart": name += ".Type"; break; case "homePath.maxDataSizeMB": name = "homePath_maxDataSizeMB"; break; case "update.checksum.type": name = "update.checksum_type"; break; } } string[] names = name.Split(':', '.'); var dictionary = value; string propertyName; dynamic propertyValue; for (int i = 0; i < names.Length - 1; i++) { propertyName = NormalizePropertyName(names[i]); if (dictionary.TryGetValue(propertyName, out propertyValue)) { if (!(propertyValue is ExpandoObject)) { throw new InvalidDataException(); // TODO: Diagnostics : conversion error } } else { propertyValue = new ExpandoObject(); dictionary.Add(propertyName, propertyValue); } dictionary = (IDictionary<string, object>)propertyValue; } propertyName = NormalizePropertyName(names[names.Length - 1]); propertyValue = await ParsePropertyValueAsync(reader, level + 1).ConfigureAwait(false); dictionary.Add(propertyName, propertyValue); } reader.EnsureMarkup(XmlNodeType.EndElement, "s:dict"); } await reader.ReadAsync().ConfigureAwait(false); return value; // TODO: what's the type seen by dynamic? } static async Task<ReadOnlyCollection<dynamic>> ParseListAsync(XmlReader reader, int level) { List<dynamic> value = new List<dynamic>(); if (!reader.IsEmptyElement) { await reader.ReadAsync().ConfigureAwait(false); while (reader.NodeType == XmlNodeType.Element && reader.Name == "s:item") { value.Add(await ParsePropertyValueAsync(reader, level + 1).ConfigureAwait(false)); } reader.EnsureMarkup(XmlNodeType.EndElement, "s:list"); } await reader.ReadAsync().ConfigureAwait(false); return new ReadOnlyCollection<dynamic>(value); } static async Task<dynamic> ParsePropertyValueAsync(XmlReader reader, int level) { if (reader.IsEmptyElement) { await reader.ReadAsync().ConfigureAwait(false); return null; } string name = reader.Name; dynamic value; await reader.ReadAsync().ConfigureAwait(false); switch (reader.NodeType) { default: value = await reader.ReadContentAsStringAsync().ConfigureAwait(false); break; case XmlNodeType.Element: // TODO: rewrite switch (reader.Name) { case "s:dict": value = await ParseDictionaryAsync(reader, level).ConfigureAwait(false); break; case "s:list": value = await ParseListAsync(reader, level).ConfigureAwait(false); break; default: throw new InvalidDataException(); // TODO: Diagnostics : unexpected start tag } break; case XmlNodeType.EndElement: reader.EnsureMarkup(XmlNodeType.EndElement, name); value = null; break; } reader.EnsureMarkup(XmlNodeType.EndElement, name); await reader.ReadAsync().ConfigureAwait(false); return value; } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="MessageQueueInstaller.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Messaging { using System.ComponentModel; using System.Diagnostics; using System; using System.Configuration.Install; using System.Collections; using Microsoft.Win32; /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller"]/*' /> /// <devdoc> /// <para>Allows you to install and configure a queue that your /// application needs in order to run. This class is called by the installation /// utility, installutil.exe, when installing a <see cref='System.Messaging.MessageQueue'/> /// .</para> /// <note type="rnotes"> /// Do we install the /// backend queue resource or some MessageQueue object. I.e. is this creating a /// new backend queue resource? Do we need to say anthing about checking for Path /// existence? /// </note> /// </devdoc> public class MessageQueueInstaller : ComponentInstaller { private bool authenticate = false; private short basePriority = (short)0; private Guid category = Guid.Empty; private System.Messaging.EncryptionRequired encryptionRequired = System.Messaging.EncryptionRequired.Optional; private string label = String.Empty; private long maximumJournalSize = UInt32.MaxValue; private long maximumQueueSize = UInt32.MaxValue; private string multicastAddress = String.Empty; private string path = String.Empty; private bool transactional = false; private bool useJournalQueue = false; private AccessControlList permissions = null; private UninstallAction uninstallAction = System.Configuration.Install.UninstallAction.Remove; /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.MessageQueueInstaller"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public MessageQueueInstaller() : base() { } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.MessageQueueInstaller1"]/*' /> /// <devdoc> /// </devdoc> public MessageQueueInstaller(MessageQueue componentToCopy) : base() { InternalCopyFromComponent(componentToCopy); } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.Authenticate"]/*' /> /// <devdoc> /// <para> Indicates whether the queue to be installed only accepts authenticated messages.</para> /// </devdoc> [DefaultValue(false)] public bool Authenticate { get { return authenticate; } set { authenticate = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.BasePriority"]/*' /> /// <devdoc> /// <para> /// Indicates the base priority used /// to route a public queue's messages over the network.</para> /// </devdoc> [DefaultValue(0)] public short BasePriority { get { return basePriority; } set { basePriority = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.Category"]/*' /> /// <devdoc> /// <para> /// Indicates an implementation-specific queue type.</para> /// <note type="rnotes"> /// Wording. Shorter /// ("Indicates the queue's type") better here? /// </note> /// </devdoc> [TypeConverterAttribute("System.ComponentModel.GuidConverter, " + AssemblyRef.System)] public Guid Category { get { return category; } set { category = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.EncryptionRequired"]/*' /> /// <devdoc> /// <para> Indicates whether the queue only accepts private /// (encrypted) messages.</para> /// </devdoc> [DefaultValue(EncryptionRequired.Optional)] public EncryptionRequired EncryptionRequired { get { return encryptionRequired; } set { if (!ValidationUtility.ValidateEncryptionRequired(value)) throw new InvalidEnumArgumentException("value", (int)value, typeof(EncryptionRequired)); encryptionRequired = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.Label"]/*' /> /// <devdoc> /// <para>Indicates a description of the queue.</para> /// </devdoc> [DefaultValue("")] public string Label { get { return label; } set { if (value == null) throw new ArgumentNullException("value"); label = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.MaximumJournalSize"]/*' /> /// <devdoc> /// <para>Indicates the maximum size of the journal associated with the queue.</para> /// </devdoc> [TypeConverterAttribute(typeof(System.Messaging.Design.SizeConverter))] public long MaximumJournalSize { get { return maximumJournalSize; } set { if (value < 0) throw new ArgumentException(Res.GetString(Res.InvalidMaxJournalSize)); maximumJournalSize = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.MaximumQueueSize"]/*' /> /// <devdoc> /// <para> Indicates the the maximum size of the queue.</para> /// </devdoc> [TypeConverterAttribute(typeof(System.Messaging.Design.SizeConverter))] public long MaximumQueueSize { get { return maximumQueueSize; } set { if (value < 0) throw new ArgumentException(Res.GetString(Res.InvalidMaxQueueSize)); maximumQueueSize = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.MulticastAddress"]/*' /> /// <devdoc> /// <para>Gets or sets the IP multicast address associated with the queue.</para> /// </devdoc> [DefaultValue("")] public string MulticastAddress { get { if (!MessageQueue.Msmq3OrNewer) //this feature is unavailable on win2k throw new PlatformNotSupportedException(Res.GetString(Res.PlatformNotSupported)); return multicastAddress; } set { if (value == null) throw new ArgumentNullException("value"); if (!MessageQueue.Msmq3OrNewer) //this feature is unavailable on win2k throw new PlatformNotSupportedException(Res.GetString(Res.PlatformNotSupported)); multicastAddress = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.Path"]/*' /> /// <devdoc> /// <para> /// Indicates the /// location of /// the queue that /// will /// be referenced by this object. .</para> /// </devdoc> [Editor("System.Messaging.Design.QueuePathEditor", "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), DefaultValue(""), TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign)] public string Path { get { return path; } set { if (!MessageQueue.ValidatePath(value, true)) throw new ArgumentException(Res.GetString(Res.PathSyntax)); if (value == null) throw new ArgumentNullException("value"); this.path = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.Permissions"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public AccessControlList Permissions { get { return permissions; } set { permissions = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.Transactional"]/*' /> /// <devdoc> /// If a queue is transactional, it can only accept messages that are sent as part /// of a transaction. However, messages can be retrieved from a local transaction /// queue with or without using a transaction. /// </devdoc> [DefaultValue(false)] public bool Transactional { get { return transactional; } set { transactional = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.UninstallAction"]/*' /> /// <devdoc> /// <para>Indicates what the installer does with the queue at uninstall time: remove it, restore it /// to its pre-installation state, or leave it in its current installed state.</para> /// </devdoc> [DefaultValue(UninstallAction.Remove)] public UninstallAction UninstallAction { get { return uninstallAction; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] set { if (!Enum.IsDefined(typeof(UninstallAction), value)) throw new InvalidEnumArgumentException("value", (int)value, typeof(UninstallAction)); uninstallAction = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.UseJournalQueue"]/*' /> /// <devdoc> /// <para>Indicates whether messages retrieved from the queue are also copied to the /// associated journal queue.</para> /// </devdoc> [DefaultValue(false)] public bool UseJournalQueue { get { return useJournalQueue; } set { useJournalQueue = value; } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.Commit"]/*' /> /// <devdoc> /// <para>Completes the installation process by committing <see cref='System.Messaging.MessageQueue'/> /// installation information that was written to the registry by the <see cref='System.Messaging.MessageQueueInstaller.Install'/> /// method. This method is meant to be used by installation tools, which /// process the appropriate methods automatically.</para> /// </devdoc> public override void Commit(IDictionary savedState) { base.Commit(savedState); Context.LogMessage(Res.GetString(Res.ClearingQueue, Path)); // make sure the queue is empty // we don't do this in Install because it can't be undone. MessageQueue queue = new MessageQueue(path); queue.Purge(); } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.CopyFromComponent"]/*' /> /// <devdoc> /// <para>Copies the property values of a <see cref='System.Messaging.MessageQueue'/> /// component to this <see cref='System.Messaging.MessageQueueInstaller'/> /// . </para> /// </devdoc> public override void CopyFromComponent(IComponent component) { InternalCopyFromComponent(component); } private void InternalCopyFromComponent(IComponent component) { MessageQueue queue = component as MessageQueue; if (queue == null) throw new ArgumentException(Res.GetString(Res.NotAMessageQueue)); if (queue.Path != null && queue.Path != string.Empty) Path = queue.Path; else throw new ArgumentException(Res.GetString(Res.IncompleteMQ)); } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.Install"]/*' /> /// <devdoc> /// <para>Writes message queue information to the registry. This method is meant to be /// used by installation tools, which process the appropriate methods /// automatically</para> /// </devdoc> public override void Install(IDictionary stateSaver) { base.Install(stateSaver); Context.LogMessage(Res.GetString(Res.CreatingQueue, Path)); bool exists = MessageQueue.Exists(path); stateSaver["Exists"] = exists; MessageQueue queue = null; if (!exists) queue = MessageQueue.Create(Path, Transactional); else { // it exists. If it's got the right transactional property, we're OK. // Otherwise we have to recreate. queue = new MessageQueue(Path); // save off the properties for rollback stateSaver["Authenticate"] = queue.Authenticate; stateSaver["BasePriority"] = queue.BasePriority; stateSaver["Category"] = queue.Category; stateSaver["EncryptionRequired"] = queue.EncryptionRequired; stateSaver["Label"] = queue.Label; stateSaver["MaximumJournalSize"] = queue.MaximumJournalSize; stateSaver["MaximumQueueSize"] = queue.MaximumQueueSize; stateSaver["Path"] = queue.Path; stateSaver["Transactional"] = queue.Transactional; stateSaver["UseJournalQueue"] = queue.UseJournalQueue; if (MessageQueue.Msmq3OrNewer) //this feature is unavailable on win2k stateSaver["MulticastAddress"] = queue.MulticastAddress; if (queue.Transactional != Transactional) { // Messages won't be kept. MessageQueue.Delete(Path); queue = MessageQueue.Create(Path, Transactional); } } // now change all the properties to how we want them. queue.Authenticate = Authenticate; queue.BasePriority = BasePriority; queue.Category = Category; queue.EncryptionRequired = EncryptionRequired; queue.Label = Label; queue.MaximumJournalSize = MaximumJournalSize; queue.MaximumQueueSize = MaximumQueueSize; queue.UseJournalQueue = UseJournalQueue; if (MessageQueue.Msmq3OrNewer) //this feature is unavailable on win2k queue.MulticastAddress = MulticastAddress; if (permissions != null) queue.SetPermissions(permissions); } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.IsEquivalentInstaller"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override bool IsEquivalentInstaller(ComponentInstaller otherInstaller) { MessageQueueInstaller other = otherInstaller as MessageQueueInstaller; if (other == null) return false; return other.Path == Path; } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.RestoreQueue"]/*' /> /// <devdoc> /// Called by Rollback and Uninstall to restore a queue to its state prior to Install /// </devdoc> private void RestoreQueue(IDictionary state) { bool exists = false; if (state != null && state["Exists"] != null) exists = (bool)state["Exists"]; else // this can only happen at uninstall - the user might have deleted the .InstallState // file since Install ran. It's probably best to leave things the way they are. return; if (exists) { Context.LogMessage(Res.GetString(Res.RestoringQueue, Path)); // the queue existed before install. Restore the properties MessageQueue queue = null; // first, restore the queue with the right Transactional property if (!MessageQueue.Exists(Path)) { // weird, but possible: the queue used to exist, but it doesn't now. // put it back queue = MessageQueue.Create(Path, (bool)state["Transactional"]); } else { queue = new MessageQueue(Path); if (queue.Transactional != (bool)state["Transactional"]) { // the transactional property doesn't match. Recreate so it does MessageQueue.Delete(Path); queue = MessageQueue.Create(Path, (bool)state["Transactional"]); } } // now change all the other properties to how they were. queue.Authenticate = (bool)state["Authenticate"]; queue.BasePriority = (short)state["BasePriority"]; queue.Category = (Guid)state["Category"]; queue.EncryptionRequired = (EncryptionRequired)state["EncryptionRequired"]; queue.Label = (string)state["Label"]; queue.MaximumJournalSize = (long)state["MaximumJournalSize"]; queue.MaximumQueueSize = (long)state["MaximumQueueSize"]; if (MessageQueue.Msmq3OrNewer) //this feature is unavailable on win2k queue.MulticastAddress = (string)state["MulticastAddress"]; queue.UseJournalQueue = (bool)state["UseJournalQueue"]; queue.ResetPermissions(); } else { Context.LogMessage(Res.GetString(Res.RemovingQueue, Path)); // it wasn't there before install, so let's make sure it still isn't if (MessageQueue.Exists(path)) MessageQueue.Delete(path); } } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.Rollback"]/*' /> /// <devdoc> /// <para> Rolls back queue information that was written to the registry /// by the installation procedure. This method is meant to be used by installation /// tools, which process the appropriate methods automatically.</para> /// </devdoc> public override void Rollback(IDictionary savedState) { base.Rollback(savedState); RestoreQueue(savedState); } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.ShouldSerializeCategory"]/*' /> /// <devdoc> /// <para>Indicates whether the value of the Category property should be persisted in /// generated code.</para> /// <note type="rnotes"> /// The similar /// "ShouldSerializeServicesDependedOn" in ServiceInstaller had dev comments that /// indicated "persisted in code-gen". Is generated code the operative issue /// here also? /// </note> /// </devdoc> private bool ShouldSerializeCategory() { return !Category.Equals(Guid.Empty); } /// <include file='doc\MessageQueueInstaller.uex' path='docs/doc[@for="MessageQueueInstaller.Uninstall"]/*' /> /// <devdoc> /// <para>Uninstalls the queue by removing information concerning it from the registry. /// If the <see cref='System.Messaging.MessageQueueInstaller.UninstallAction'/> is <see langword='Remove'/>, /// Uninstall also deletes the queue associated with the <see cref='System.Messaging.MessageQueue'/>. </para> /// </devdoc> public override void Uninstall(IDictionary savedState) { base.Uninstall(savedState); if (UninstallAction == UninstallAction.Remove) { Context.LogMessage(Res.GetString(Res.DeletingQueue, Path)); if (MessageQueue.Exists(Path)) MessageQueue.Delete(Path); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Data.SqlTypes; using System.Globalization; using System.Text; using System.Reflection; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public class AdapterTest { private char[] _appendNewLineIndentBuffer = new char[0]; // data value and server consts private const string MagicName = "Magic"; private string _tempTable; private string _tempKey; // data type private decimal _c_numeric_val; private long _c_bigint_val; private byte[] _c_unique_val; private Guid _c_guid_val; private byte[] _c_varbinary_val; private byte[] _c_binary_val; private decimal _c_money_val; private decimal _c_smallmoney_val; private DateTime _c_datetime_val; private DateTime _c_smalldatetime_val; private string _c_nvarchar_val; private string _c_nchar_val; private string _c_varchar_val; private string _c_char_val; private int _c_int_val; private short _c_smallint_val; private byte _c_tinyint_val; private bool _c_bit_val; private double _c_float_val; private float _c_real_val; private object[] _values; public AdapterTest() { // create random name for temp tables _tempTable = Environment.MachineName + "_" + Guid.NewGuid().ToString(); _tempTable = _tempTable.Replace('-', '_'); _tempKey = "employee_id_key_" + Environment.TickCount.ToString() + Guid.NewGuid().ToString(); _tempKey = _tempKey.Replace('-', '_'); InitDataValues(); } [CheckConnStrSetupFact] public void SimpleFillTest() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country FROM Employees", conn)) { DataSet employeesSet = new DataSet(); DataTestUtility.AssertEqualsWithDescription(0, employeesSet.Tables.Count, "Unexpected tables count before fill."); adapter.Fill(employeesSet, "Employees"); DataTestUtility.AssertEqualsWithDescription(1, employeesSet.Tables.Count, "Unexpected tables count after fill."); DataTestUtility.AssertEqualsWithDescription("Employees", employeesSet.Tables[0].TableName, "Unexpected table name."); DataTestUtility.AssertEqualsWithDescription(9, employeesSet.Tables["Employees"].Columns.Count, "Unexpected columns count."); employeesSet.Tables["Employees"].Columns.Remove("LastName"); employeesSet.Tables["Employees"].Columns.Remove("FirstName"); employeesSet.Tables["Employees"].Columns.Remove("Title"); DataTestUtility.AssertEqualsWithDescription(6, employeesSet.Tables["Employees"].Columns.Count, "Unexpected columns count after column removal."); } } [CheckConnStrSetupFact] public void PrepUnprepTest() { // share the connection using (SqlCommand cmd = new SqlCommand("select * from shippers", new SqlConnection(DataTestUtility.TcpConnStr))) using (SqlDataAdapter sqlAdapter = new SqlDataAdapter()) { cmd.Connection.Open(); DataSet dataSet = new DataSet(); sqlAdapter.TableMappings.Add("Table", "shippers"); cmd.CommandText = "Select * from shippers"; sqlAdapter.SelectCommand = cmd; sqlAdapter.Fill(dataSet); DataTestUtility.AssertEqualsWithDescription( 3, dataSet.Tables[0].Rows.Count, "Exec1: Unexpected number of shipper rows."); dataSet.Reset(); sqlAdapter.Fill(dataSet); DataTestUtility.AssertEqualsWithDescription( 3, dataSet.Tables[0].Rows.Count, "Exec2: Unexpected number of shipper rows."); dataSet.Reset(); cmd.CommandText = "select * from shippers where shipperId < 3"; sqlAdapter.Fill(dataSet); DataTestUtility.AssertEqualsWithDescription( 2, dataSet.Tables[0].Rows.Count, "Exec3: Unexpected number of shipper rows."); dataSet.Reset(); sqlAdapter.Fill(dataSet); DataTestUtility.AssertEqualsWithDescription( 2, dataSet.Tables[0].Rows.Count, "Exec4: Unexpected number of shipper rows."); cmd.CommandText = "select * from shippers"; cmd.Prepare(); int i = 0; using (SqlDataReader reader = cmd.ExecuteReader()) { DataTestUtility.AssertEqualsWithDescription(3, reader.FieldCount, "Unexpected FieldCount."); while (reader.Read()) { i++; } } DataTestUtility.AssertEqualsWithDescription(3, i, "Unexpected read count."); cmd.CommandText = "select * from orders where orderid < @p1"; cmd.Parameters.AddWithValue("@p1", 10250); using (SqlDataReader reader = cmd.ExecuteReader()) { DataTestUtility.AssertEqualsWithDescription(14, reader.FieldCount, "Unexpected FieldCount."); i = 0; while (reader.Read()) { i++; } } DataTestUtility.AssertEqualsWithDescription(2, i, "Unexpected read count."); cmd.Parameters["@p1"].Value = 10249; using (SqlDataReader reader = cmd.ExecuteReader()) { DataTestUtility.AssertEqualsWithDescription(14, reader.FieldCount, "Unexpected FieldCount."); i = 0; while (reader.Read()) { i++; } } DataTestUtility.AssertEqualsWithDescription(1, i, "Unexpected read count."); } } [CheckConnStrSetupFact] public void SqlVariantTest() { try { ExecuteNonQueryCommand("CREATE TABLE shiloh_types (c0_bigint bigint, c1_variant sql_variant)"); // good test for null values and unicode strings using (SqlCommand cmd = new SqlCommand(null, new SqlConnection(DataTestUtility.TcpConnStr))) using (SqlDataAdapter sqlAdapter = new SqlDataAdapter()) { cmd.Connection.Open(); // the ORDER BY clause tests that we correctly ignore the ORDER token cmd.CommandText = "select * from shiloh_types"; sqlAdapter.SelectCommand = cmd; sqlAdapter.TableMappings.Add("Shiloh_Types", "rowset"); // insert sqlAdapter.InsertCommand = new SqlCommand() { CommandText = "INSERT INTO Shiloh_Types(c0_bigint, c1_variant) " + "VALUES (@bigint, @variant)" }; SqlParameter p = sqlAdapter.InsertCommand.Parameters.Add(new SqlParameter("@bigint", SqlDbType.BigInt)); p.SourceColumn = "c0_bigint"; p = sqlAdapter.InsertCommand.Parameters.Add(new SqlParameter("@variant", SqlDbType.Variant)); p.SourceColumn = "c1_variant"; sqlAdapter.InsertCommand.Connection = cmd.Connection; DataSet dataSet = new DataSet(); sqlAdapter.FillSchema(dataSet, SchemaType.Mapped, "Shiloh_Types"); DataRow datarow = null; for (int i = 0; i < _values.Length; i++) { // add each variant type datarow = dataSet.Tables[0].NewRow(); datarow.ItemArray = new object[] { 1, _values[i] }; datarow.Table.Rows.Add(datarow); } sqlAdapter.Update(dataSet, "Shiloh_Types"); // now reload and make sure we got the values we wrote out dataSet.Reset(); sqlAdapter.Fill(dataSet, "Shiloh_Types"); DataColumnCollection cols = dataSet.Tables[0].Columns; DataRowCollection rows = dataSet.Tables[0].Rows; Assert.True(rows.Count == _values.Length, "FAILED: SqlVariant didn't update all the rows!"); for (int i = 0; i < rows.Count; i++) { DataRow row = rows[i]; object value = row[1]; if (_values[i].GetType() == typeof(byte[]) || _values[i].GetType() == typeof(Guid)) { byte[] bsrc; byte[] bdst; if (_values[i].GetType() == typeof(Guid)) { bsrc = ((Guid)value).ToByteArray(); bdst = ((Guid)(_values[i])).ToByteArray(); } else { bsrc = (byte[])value; bdst = (byte[])_values[i]; } Assert.True(ByteArraysEqual(bsrc, bdst), "FAILED: Byte arrays are unequal"); } else if (_values[i].GetType() == typeof(bool)) { Assert.True(Convert.ToBoolean(value) == (bool)_values[i], "FAILED: " + DBConvertToString(value) + " is not equal to " + DBConvertToString(_values[i])); } else { Assert.True(value.Equals(_values[i]), "FAILED: " + DBConvertToString(value) + " is not equal to " + DBConvertToString(_values[i])); } } } } finally { ExecuteNonQueryCommand("DROP TABLE shiloh_types"); } } [CheckConnStrSetupFact] public void ParameterTest_AllTypes() { string spCreateAllTypes = "CREATE PROCEDURE sp_alltypes " + "@Cnumeric numeric(10,2) OUTPUT, " + "@Cunique uniqueidentifier OUTPUT, " + "@Cnvarchar nvarchar(10) OUTPUT, " + "@Cnchar nchar(10) OUTPUT, " + "@Cbit bit OUTPUT, " + "@Ctinyint tinyint OUTPUT, " + "@Cvarbinary varbinary(16) OUTPUT, " + "@Cbinary binary(16) OUTPUT, " + "@Cchar char(10) OUTPUT, " + "@Cmoney money OUTPUT, " + "@Csmallmoney smallmoney OUTPUT, " + "@Cint int OUTPUT, " + "@Csmallint smallint OUTPUT, " + "@Cfloat float OUTPUT, " + "@Creal real OUTPUT, " + "@Cdatetime datetime OUTPUT, " + "@Csmalldatetime smalldatetime OUTPUT, " + "@Cvarchar varchar(10) OUTPUT " + "AS SELECT " + "@Cnumeric=@Cnumeric, " + "@Cunique=@Cunique, " + "@Cnvarchar=@Cnvarchar, " + "@Cnchar=@Cnchar, " + "@Cbit=@Cbit, " + "@Ctinyint=@Ctinyint, " + "@Cvarbinary=@Cvarbinary, " + "@Cbinary=@Cbinary, " + "@Cchar=@Cchar, " + "@Cmoney=@Cmoney, " + "@Csmallmoney=@Csmallmoney, " + "@Cint=@Cint, " + "@Csmallint=@Csmallint, " + "@Cfloat=@Cfloat, " + "@Creal=@Creal, " + "@Cdatetime=@Cdatetime, " + "@Csmalldatetime=@Csmalldatetime, " + "@Cvarchar=@Cvarchar " + "RETURN(42)"; string spDropAllTypes = "DROP PROCEDURE sp_alltypes"; bool dropSP = false; try { ExecuteNonQueryCommand(spCreateAllTypes); dropSP = true; using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand cmd = new SqlCommand("sp_allTypes", conn)) using (SqlDataAdapter sqlAdapter = new SqlDataAdapter()) { conn.Open(); SqlParameter param = cmd.Parameters.Add(new SqlParameter("@Cnumeric", SqlDbType.Decimal)); param.Precision = 10; param.Scale = 2; param.Direction = ParameterDirection.InputOutput; cmd.Parameters[0].Value = _c_numeric_val; param = cmd.Parameters.Add(new SqlParameter("@Cunique", SqlDbType.UniqueIdentifier)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[1].Value = _c_guid_val; cmd.Parameters.Add(new SqlParameter("@Cnvarchar", SqlDbType.NVarChar, 10)); cmd.Parameters[2].Direction = ParameterDirection.InputOutput; cmd.Parameters[2].Value = _c_nvarchar_val; cmd.Parameters.Add(new SqlParameter("@Cnchar", SqlDbType.NChar, 10)); cmd.Parameters[3].Direction = ParameterDirection.InputOutput; cmd.Parameters[3].Value = _c_nchar_val; param = cmd.Parameters.Add(new SqlParameter("@Cbit", SqlDbType.Bit)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[4].Value = _c_bit_val; param = cmd.Parameters.Add(new SqlParameter("@Ctinyint", SqlDbType.TinyInt)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[5].Value = _c_tinyint_val; cmd.Parameters.Add(new SqlParameter("@Cvarbinary", SqlDbType.VarBinary, 16)); cmd.Parameters[6].Direction = ParameterDirection.InputOutput; cmd.Parameters[6].Value = _c_varbinary_val; cmd.Parameters.Add(new SqlParameter("@Cbinary", SqlDbType.Binary, 16)); cmd.Parameters[7].Direction = ParameterDirection.InputOutput; cmd.Parameters[7].Value = _c_binary_val; cmd.Parameters.Add(new SqlParameter("@Cchar", SqlDbType.Char, 10)); cmd.Parameters[8].Direction = ParameterDirection.InputOutput; cmd.Parameters[8].Value = _c_char_val; param = cmd.Parameters.Add(new SqlParameter("@Cmoney", SqlDbType.Money)); param.Direction = ParameterDirection.InputOutput; param.Scale = 4; cmd.Parameters[9].Value = _c_money_val; param = cmd.Parameters.Add(new SqlParameter("@Csmallmoney", SqlDbType.SmallMoney)); param.Direction = ParameterDirection.InputOutput; param.Scale = 4; cmd.Parameters[10].Value = _c_smallmoney_val; param = cmd.Parameters.Add(new SqlParameter("@Cint", SqlDbType.Int)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[11].Value = _c_int_val; param = cmd.Parameters.Add(new SqlParameter("@Csmallint", SqlDbType.SmallInt)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[12].Value = _c_smallint_val; param = cmd.Parameters.Add(new SqlParameter("@Cfloat", SqlDbType.Float)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[13].Value = _c_float_val; param = cmd.Parameters.Add(new SqlParameter("@Creal", SqlDbType.Real)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[14].Value = _c_real_val; param = cmd.Parameters.Add(new SqlParameter("@Cdatetime", SqlDbType.DateTime)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[15].Value = _c_datetime_val; param = cmd.Parameters.Add(new SqlParameter("@Csmalldatetime", SqlDbType.SmallDateTime)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[16].Value = _c_smalldatetime_val; param = cmd.Parameters.Add(new SqlParameter("@Cvarchar", SqlDbType.VarChar, 10)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[17].Value = _c_varchar_val; param = cmd.Parameters.Add(new SqlParameter("@return", SqlDbType.Int)); param.Direction = ParameterDirection.ReturnValue; cmd.Parameters[18].Value = 17; // will be overwritten cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); string[] expectedStringValues = { "@Cnumeric : Decimal<42424242.42>", null, "@Cnvarchar : String:10<1234567890>", "@Cnchar : String:10<1234567890>", "@Cbit : Boolean<True>", "@Ctinyint : Byte<255>", null, null, "@Cchar : String:10<1234567890>", null, null, "@Cint : Int32<-1>", "@Csmallint : Int16<-1>", "@Cfloat : Double<12345678.2>", "@Creal : Single<12345.1>", null, null, "@Cvarchar : String:10<1234567890>", "@return : Int32<42>" }; for (int i = 0; i < cmd.Parameters.Count; i++) { param = cmd.Parameters[i]; switch (param.SqlDbType) { case SqlDbType.Binary: Assert.True(ByteArraysEqual(_c_binary_val, (byte[])param.Value), "FAILED: sp_alltypes, Binary parameter"); break; case SqlDbType.VarBinary: Assert.True(ByteArraysEqual(_c_varbinary_val, (byte[])param.Value), "FAILED: sp_alltypes, VarBinary parameter"); break; case SqlDbType.UniqueIdentifier: DataTestUtility.AssertEqualsWithDescription(_c_guid_val, (Guid)param.Value, "FAILED: sp_alltypes, UniqueIdentifier parameter"); break; case SqlDbType.DateTime: Assert.True(0 == DateTime.Compare((DateTime)param.Value, _c_datetime_val), "FAILED: sp_alltypes, DateTime parameter"); break; case SqlDbType.SmallDateTime: Assert.True(0 == DateTime.Compare((DateTime)param.Value, _c_smalldatetime_val), "FAILED: sp_alltypes, SmallDateTime parameter"); break; case SqlDbType.Money: Assert.True( 0 == decimal.Compare((decimal)param.Value, _c_money_val), string.Format("FAILED: sp_alltypes, Money parameter. Expected: {0}. Actual: {1}.", _c_money_val, (decimal)param.Value)); break; case SqlDbType.SmallMoney: Assert.True( 0 == decimal.Compare((decimal)param.Value, _c_smallmoney_val), string.Format("FAILED: sp_alltypes, SmallMoney parameter. Expected: {0}. Actual: {1}.", _c_smallmoney_val, (decimal)param.Value)); break; default: string actualValue = param.ParameterName + " : " + DBConvertToString(cmd.Parameters[i].Value); DataTestUtility.AssertEqualsWithDescription(actualValue, expectedStringValues[i], "Unexpected parameter value."); break; } } } } finally { if (dropSP) { ExecuteNonQueryCommand(spDropAllTypes); } } } [CheckConnStrSetupFact] public void ParameterTest_InOut() { // input, output string spCreateInOut = "CREATE PROCEDURE sp_test @in int, @inout int OUTPUT, @out nvarchar(8) OUTPUT " + "AS SELECT @inout = (@in + @inout), @out = 'Success!' " + "SELECT * From shippers where ShipperID = @in " + "RETURN(42)"; string spDropInOut = "DROP PROCEDURE sp_test"; bool dropSP = false; try { ExecuteNonQueryCommand(spCreateInOut); dropSP = true; using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand cmd = new SqlCommand("sp_test", conn)) using (SqlDataAdapter sqlAdapter = new SqlDataAdapter()) { conn.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@in", SqlDbType.Int)); cmd.Parameters[0].Value = 2; SqlParameter param = cmd.Parameters.Add(new SqlParameter("@inout", SqlDbType.Int)); param.Direction = ParameterDirection.InputOutput; cmd.Parameters[1].Value = 1998; param = cmd.Parameters.Add(new SqlParameter("@out", SqlDbType.NVarChar, 8)); param.Direction = ParameterDirection.Output; param = cmd.Parameters.Add(new SqlParameter("@ret", SqlDbType.Int)); param.Direction = ParameterDirection.ReturnValue; DataSet dataSet = new DataSet(); sqlAdapter.TableMappings.Add("Table", "shipper"); sqlAdapter.SelectCommand = cmd; sqlAdapter.Fill(dataSet); // check our ouput and return value params Assert.True(VerifyOutputParams(cmd.Parameters), "FAILED: InputOutput parameter test with returned rows and bound return value!"); Assert.True(1 == dataSet.Tables[0].Rows.Count, "FAILED: Expected 1 row to be loaded in the dataSet!"); DataRow row = dataSet.Tables[0].Rows[0]; Assert.True((int)row["ShipperId"] == 2, "FAILED: ShipperId column should be 2, not " + DBConvertToString(row["ShipperId"])); // remember to reset params cmd.Parameters[0].Value = 2; cmd.Parameters[1].Value = 1998; cmd.Parameters[2].Value = Convert.DBNull; cmd.Parameters[3].Value = Convert.DBNull; // now exec the same thing without a data set cmd.ExecuteNonQuery(); // check our ouput and return value params Assert.True(VerifyOutputParams(cmd.Parameters), "FAILED: InputOutput parameter test with no returned rows and bound return value!"); // now unbind the return value cmd.Parameters.RemoveAt(3); // remember to reset input params cmd.Parameters[0].Value = 1; // use 1, just for the heck of it cmd.Parameters[1].Value = 1999; cmd.Parameters[2].Value = Convert.DBNull; dataSet.Reset(); sqlAdapter.Fill(dataSet); // verify the ouptut parameter Assert.True( ((int)cmd.Parameters[1].Value == 2000) && (0 == string.Compare(cmd.Parameters[2].Value.ToString(), "Success!", false, CultureInfo.InvariantCulture)), "FAILED: unbound return value case, output param is not correct!"); Assert.True(1 == dataSet.Tables[0].Rows.Count, "FAILED: Expected 1 row to be loaded in the dataSet!"); row = dataSet.Tables[0].Rows[0]; Assert.True((int)row["ShipperId"] == 1, "FAILED: ShipperId column should be 1, not " + DBConvertToString(row["ShipperId"])); } } finally { if (dropSP) { ExecuteNonQueryCommand(spDropInOut); } } } [CheckConnStrSetupFact] public void UpdateTest() { try { using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand cmd = conn.CreateCommand()) using (SqlDataAdapter adapter = new SqlDataAdapter()) using (SqlDataAdapter adapterVerify = new SqlDataAdapter()) { conn.Open(); cmd.CommandText = string.Format("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country into {0} from Employees where EmployeeID < 3", _tempTable); cmd.ExecuteNonQuery(); cmd.CommandText = "alter table " + _tempTable + " add constraint " + _tempKey + " primary key (EmployeeID)"; cmd.ExecuteNonQuery(); PrepareUpdateCommands(adapter, conn, _tempTable); adapter.SelectCommand = new SqlCommand(string.Format("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country from {0} where EmployeeID < 3", _tempTable), conn); adapterVerify.SelectCommand = new SqlCommand("SELECT LastName, FirstName FROM " + _tempTable + " where FirstName='" + MagicName + "'", conn); adapter.TableMappings.Add(_tempTable, "rowset"); adapterVerify.TableMappings.Add(_tempTable, "rowset"); DataSet dataSet = new DataSet(); VerifyFillSchemaResult(adapter.FillSchema(dataSet, SchemaType.Mapped, _tempTable), new string[] { "rowset" }); // FillSchema dataSet.Tables["rowset"].PrimaryKey = new DataColumn[] { dataSet.Tables["rowset"].Columns["EmployeeID"] }; adapter.Fill(dataSet, _tempTable); // Fill from Database Assert.True(dataSet.Tables[0].Rows.Count == 2, "FAILED: Fill after FillSchema should populate the dataSet with two rows!"); dataSet.AcceptChanges(); // Verify that set is empty DataSet dataSetVerify = new DataSet(); VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable); // Insert DataRow datarow = dataSet.Tables["rowset"].NewRow(); datarow.ItemArray = new object[] { "11", "The Original", MagicName, "Engineer", "One Microsoft Way", "Redmond", "WA", "98052", "USA" }; datarow.Table.Rows.Add(datarow); adapter.Update(dataSet, _tempTable); // Verify that set has one 'Magic' entry VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable); dataSet.AcceptChanges(); // Update datarow = dataSet.Tables["rowset"].Rows.Find("11"); datarow.BeginEdit(); datarow.ItemArray = new object[] { "11", "The New and Improved", MagicName, "reenignE", "Yaw Tfosorcim Eno", "Dnomder", "WA", "52098", "ASU" }; datarow.EndEdit(); adapter.Update(dataSet, _tempTable); // Verify that set has updated 'Magic' entry VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable); dataSet.AcceptChanges(); // Delete dataSet.Tables["rowset"].Rows.Find("11").Delete(); adapter.Update(dataSet, _tempTable); // Verify that set is empty VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable); dataSet.AcceptChanges(); } } finally { ExecuteNonQueryCommand("DROP TABLE " + _tempTable); } } // these next texts verify that 'bulk' operations work. If each command type modifies more than three rows, then we do a Prep/Exec instead of // adhoc ExecuteSql. [CheckConnStrSetupFact] public void BulkUpdateTest() { try { using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand temp = new SqlCommand("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country into " + _tempTable + " from Employees where EmployeeID < 3", conn)) using (SqlDataAdapter adapter = new SqlDataAdapter()) using (SqlDataAdapter adapterVerify = new SqlDataAdapter()) { conn.Open(); temp.ExecuteNonQuery(); temp.CommandText = "alter table " + _tempTable + " add constraint " + _tempKey + " primary key (EmployeeID)"; temp.ExecuteNonQuery(); PrepareUpdateCommands(adapter, conn, _tempTable); adapter.SelectCommand = new SqlCommand("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country FROM " + _tempTable + " WHERE EmployeeID < 3", conn); adapterVerify.SelectCommand = new SqlCommand("SELECT LastName, FirstName FROM " + _tempTable + " where FirstName='" + MagicName + "'", conn); adapter.TableMappings.Add(_tempTable, "rowset"); adapterVerify.TableMappings.Add(_tempTable, "rowset"); DataSet dataSet = new DataSet(); adapter.FillSchema(dataSet, SchemaType.Mapped, _tempTable); dataSet.Tables["rowset"].PrimaryKey = new DataColumn[] { dataSet.Tables["rowset"].Columns["EmployeeID"] }; adapter.Fill(dataSet, _tempTable); dataSet.AcceptChanges(); // Verify that set is empty DataSet dataSetVerify = new DataSet(); VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable); // Bulk Insert (10 records) DataRow datarow = null; const int cOps = 5; for (int i = 0; i < cOps * 2; i++) { datarow = dataSet.Tables["rowset"].NewRow(); string sid = "99999000" + i.ToString(); datarow.ItemArray = new object[] { sid, "Bulk Insert" + i.ToString(), MagicName, "Engineer", "One Microsoft Way", "Redmond", "WA", "98052", "USA" }; datarow.Table.Rows.Add(datarow); } adapter.Update(dataSet, _tempTable); // Verify that set has 10 'Magic' entries VerifyUpdateRow(adapterVerify, dataSetVerify, 10, _tempTable); dataSet.AcceptChanges(); // Bulk Update (first 5) for (int i = 0; i < cOps; i++) { string sid = "99999000" + i.ToString(); datarow = dataSet.Tables["rowset"].Rows.Find(sid); datarow.BeginEdit(); datarow.ItemArray = new object[] { sid, "Bulk Update" + i.ToString(), MagicName, "reenignE", "Yaw Tfosorcim Eno", "Dnomder", "WA", "52098", "ASU" }; datarow.EndEdit(); } // Bulk Delete (last 5) for (int i = cOps; i < cOps * 2; i++) { string sid = "99999000" + i.ToString(); dataSet.Tables["rowset"].Rows.Find(sid).Delete(); } // now update the dataSet with the insert and delete changes adapter.Update(dataSet, _tempTable); // Verify that set has 5 'Magic' updated entries VerifyUpdateRow(adapterVerify, dataSetVerify, 5, _tempTable); dataSet.AcceptChanges(); // clean up the remaining 5 rows for (int i = 0; i < cOps; i++) { string sid = "99999000" + i.ToString(); dataSet.Tables["rowset"].Rows.Find(sid).Delete(); } adapter.Update(dataSet, _tempTable); // Verify that set has no entries VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable); dataSet.AcceptChanges(); } } finally { ExecuteNonQueryCommand("DROP TABLE " + _tempTable); } } // Makes sure that we can refresh an identity column in the dataSet // for a newly inserted row [CheckConnStrSetupFact] public void UpdateRefreshTest() { string createIdentTable = "CREATE TABLE ident(id int IDENTITY," + "LastName nvarchar(50) NULL," + "Firstname nvarchar(50) NULL)"; string spCreateInsert = "CREATE PROCEDURE sp_insert" + _tempTable + "(@FirstName nvarchar(50), @LastName nvarchar(50), @id int OUTPUT) " + "AS INSERT INTO " + _tempTable + " (FirstName, LastName) " + "VALUES (@FirstName, @LastName); " + "SELECT @id=@@IDENTITY"; string spDropInsert = "DROP PROCEDURE sp_insert" + _tempTable; bool dropSP = false; try { using (SqlDataAdapter adapter = new SqlDataAdapter()) using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand cmd = new SqlCommand(null, conn)) using (SqlCommand temp = new SqlCommand("SELECT id, LastName, FirstName into " + _tempTable + " from ident", conn)) using (SqlCommand tableClean = new SqlCommand("", conn)) { ExecuteNonQueryCommand(createIdentTable); adapter.InsertCommand = new SqlCommand() { CommandText = "sp_insert" + _tempTable, CommandType = CommandType.StoredProcedure }; adapter.InsertCommand.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 50, "FirstName")); adapter.InsertCommand.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 50, "LastName")); SqlParameter param = adapter.InsertCommand.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)); param.SourceColumn = "id"; param.Direction = ParameterDirection.Output; adapter.InsertCommand.Parameters.Add(new SqlParameter("@badapple", SqlDbType.NVarChar, 50, "LastName")); adapter.RowUpdating += new SqlRowUpdatingEventHandler(RowUpdating_UpdateRefreshTest); adapter.RowUpdated += new SqlRowUpdatedEventHandler(RowUpdated_UpdateRefreshTest); adapter.InsertCommand.Connection = conn; conn.Open(); temp.ExecuteNonQuery(); // start clean tableClean.CommandText = "delete " + _tempTable; tableClean.ExecuteNonQuery(); tableClean.CommandText = spCreateInsert; tableClean.ExecuteNonQuery(); dropSP = true; DataSet ds = new DataSet(); adapter.TableMappings.Add("Table", _tempTable); cmd.CommandText = "select * from " + _tempTable; adapter.SelectCommand = cmd; adapter.Fill(ds, "Table"); // Insert DataRow row1 = ds.Tables[_tempTable].NewRow(); row1.ItemArray = new object[] { 0, "Bond", "James" }; row1.Table.Rows.Add(row1); DataRow row2 = ds.Tables[_tempTable].NewRow(); row2.ItemArray = new object[] { 0, "Lee", "Bruce" }; row2.Table.Rows.Add(row2); Assert.True((int)row1["id"] == 0 && (int)row2["id"] == 0, "FAILED: UpdateRefresh should not have values for identity columns"); adapter.Update(ds, "Table"); // should have values now int i1 = (int)row1["id"]; int i2 = (int)row2["id"]; Assert.True( (i1 != 0) && (i2 != 0) && (i2 == (i1 + 1)), string.Format("FAILED: UpdateRefresh, i2 should equal (i1 + 1). i1: {0}. i2: {1}.", i1, i2)); } } finally { if (dropSP) { ExecuteNonQueryCommand(spDropInsert); ExecuteNonQueryCommand("DROP TABLE " + _tempTable); } ExecuteNonQueryCommand("DROP TABLE ident"); } } [CheckConnStrSetupFact] public void UpdateNullTest() { string createTable = "CREATE TABLE varbin(cvarbin VARBINARY(7000), cimage IMAGE)"; string createSP = "CREATE PROCEDURE sp_insertvarbin (@val_cvarbin VARBINARY(7000), @val_cimage IMAGE)" + "AS INSERT INTO varbin (cvarbin, cimage)" + "VALUES (@val_cvarbin, @val_cimage)"; bool dropSP = false; try { ExecuteNonQueryCommand(createTable); ExecuteNonQueryCommand(createSP); dropSP = true; using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand cmdInsert = new SqlCommand("sp_insertvarbin", conn)) using (SqlCommand cmdSelect = new SqlCommand("select * from varbin", conn)) using (SqlCommand tableClean = new SqlCommand("delete varbin", conn)) using (SqlDataAdapter adapter = new SqlDataAdapter()) { conn.Open(); cmdInsert.CommandType = CommandType.StoredProcedure; SqlParameter p1 = cmdInsert.Parameters.Add(new SqlParameter("@val_cvarbin", SqlDbType.VarBinary, 7000)); SqlParameter p2 = cmdInsert.Parameters.Add(new SqlParameter("@val_cimage", SqlDbType.Image, 8000)); tableClean.ExecuteNonQuery(); p1.Value = Convert.DBNull; p2.Value = Convert.DBNull; int rowsAffected = cmdInsert.ExecuteNonQuery(); DataTestUtility.AssertEqualsWithDescription(1, rowsAffected, "Unexpected number of rows inserted."); DataSet ds = new DataSet(); adapter.SelectCommand = cmdSelect; adapter.Fill(ds, "goofy"); // should have 1 row in table (with two null entries) DataTestUtility.AssertEqualsWithDescription(1, ds.Tables[0].Rows.Count, "Unexpected rows count."); DataTestUtility.AssertEqualsWithDescription(DBNull.Value, ds.Tables[0].Rows[0][0], "Unexpected value."); DataTestUtility.AssertEqualsWithDescription(DBNull.Value, ds.Tables[0].Rows[0][1], "Unexpected value."); } } finally { if (dropSP) { ExecuteNonQueryCommand("DROP PROCEDURE sp_insertvarbin"); } ExecuteNonQueryCommand("DROP TABLE varbin"); } } [CheckConnStrSetupFact] public void UpdateOffsetTest() { string createTable = "CREATE TABLE varbin(cvarbin VARBINARY(7000), cimage IMAGE)"; string createSP = "CREATE PROCEDURE sp_insertvarbin (@val_cvarbin VARBINARY(7000), @val_cimage IMAGE)" + "AS INSERT INTO varbin (cvarbin, cimage)" + "VALUES (@val_cvarbin, @val_cimage)"; bool dropSP = false; try { ExecuteNonQueryCommand(createTable); ExecuteNonQueryCommand(createSP); dropSP = true; using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand cmdInsert = new SqlCommand("sp_insertvarbin", conn)) using (SqlCommand cmdSelect = new SqlCommand("select * from varbin", conn)) using (SqlCommand tableClean = new SqlCommand("delete varbin", conn)) using (SqlDataAdapter adapter = new SqlDataAdapter()) { conn.Open(); cmdInsert.CommandType = CommandType.StoredProcedure; SqlParameter p1 = cmdInsert.Parameters.Add(new SqlParameter("@val_cvarbin", SqlDbType.VarBinary, 7000)); SqlParameter p2 = cmdInsert.Parameters.Add(new SqlParameter("@val_cimage", SqlDbType.Image, 7000)); tableClean.ExecuteNonQuery(); byte[] b = new byte[7]; b[0] = 0x01; b[1] = 0x02; b[2] = 0x03; b[3] = 0x04; b[4] = 0x05; b[5] = 0x06; b[6] = 0x07; p1.Value = b; p1.Size = 4; p2.Value = b; p2.Size = 3; p2.Offset = 4; int rowsAffected = cmdInsert.ExecuteNonQuery(); DataSet ds = new DataSet(); adapter.SelectCommand = cmdSelect; adapter.Fill(ds, "goofy"); byte[] expectedBytes1 = { 0x01, 0x02, 0x03, 0x04 }; byte[] val = (byte[])(ds.Tables[0].Rows[0][0]); Assert.True(ByteArraysEqual(expectedBytes1, val), "FAILED: Test 1: Unequal byte arrays."); byte[] expectedBytes2 = { 0x05, 0x06, 0x07 }; val = (byte[])(ds.Tables[0].Rows[0][1]); Assert.True(ByteArraysEqual(expectedBytes2, val), "FAILED: Test 2: Unequal byte arrays."); } } finally { if (dropSP) { ExecuteNonQueryCommand("DROP PROCEDURE sp_insertvarbin"); } ExecuteNonQueryCommand("DROP TABLE varbin"); } } [CheckConnStrSetupFact] public void SelectAllTest() { // Test exceptions using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(new SqlCommand("select * from orders", new SqlConnection(DataTestUtility.TcpConnStr)))) { DataSet dataset = new DataSet(); sqlAdapter.TableMappings.Add("Table", "orders"); sqlAdapter.Fill(dataset); } } private bool ByteArraysEqual(byte[] expectedBytes, byte[] actualBytes) { DataTestUtility.AssertEqualsWithDescription( expectedBytes.Length, actualBytes.Length, "Unexpected array length."); for (int i = 0; i < expectedBytes.Length; i++) { DataTestUtility.AssertEqualsWithDescription( expectedBytes[i], actualBytes[i], "Unexpected byte value."); } return true; } private void InitDataValues() { _c_numeric_val = new decimal(42424242.42); _c_unique_val = new byte[16]; _c_unique_val[0] = 0xba; _c_unique_val[1] = 0xad; _c_unique_val[2] = 0xf0; _c_unique_val[3] = 0x0d; _c_unique_val[4] = 0xba; _c_unique_val[5] = 0xad; _c_unique_val[6] = 0xf0; _c_unique_val[7] = 0x0d; _c_unique_val[8] = 0xba; _c_unique_val[9] = 0xad; _c_unique_val[10] = 0xf0; _c_unique_val[11] = 0x0d; _c_unique_val[12] = 0xba; _c_unique_val[13] = 0xad; _c_unique_val[14] = 0xf0; _c_unique_val[15] = 0x0d; _c_guid_val = new Guid(_c_unique_val); _c_varbinary_val = _c_unique_val; _c_binary_val = _c_unique_val; _c_money_val = new decimal((double)123456789.99); _c_smallmoney_val = new decimal((double)-6543.21); _c_datetime_val = new DateTime(1971, 7, 20, 23, 59, 59); _c_smalldatetime_val = new DateTime(1971, 7, 20, 23, 59, 0); _c_nvarchar_val = "1234567890"; _c_nchar_val = _c_nvarchar_val; _c_varchar_val = _c_nvarchar_val; _c_char_val = _c_nvarchar_val; _c_int_val = unchecked((int)0xffffffff); _c_smallint_val = unchecked((short)0xffff); _c_tinyint_val = 0xff; _c_bigint_val = 0x11ffffff; _c_bit_val = true; _c_float_val = (double)12345678.2; _c_real_val = (float)12345.1; _values = new object[18]; _values[0] = _c_numeric_val; _values[1] = _c_smalldatetime_val; _values[2] = _c_guid_val; _values[3] = _c_varbinary_val; _values[4] = _c_binary_val; _values[5] = _c_money_val; _values[6] = _c_smallmoney_val; _values[7] = _c_nvarchar_val; _values[8] = _c_varchar_val; _values[9] = _c_char_val; _values[10] = _c_int_val; _values[11] = _c_smallint_val; _values[12] = _c_tinyint_val; _values[13] = _c_bigint_val; _values[14] = _c_bit_val; _values[15] = _c_float_val; _values[16] = _c_real_val; _values[17] = _c_datetime_val; } private void VerifyFillSchemaResult(DataTable[] tables, string[] expectedTableNames) { DataTestUtility.AssertEqualsWithDescription(expectedTableNames.Length, tables.Length, "Unequal number of tables."); for (int i = 0; i < tables.Length; i++) { DataTestUtility.AssertEqualsWithDescription(expectedTableNames[i], tables[i].TableName, "Unexpected DataTable TableName."); } } // Prepares the Insert, Update, and Delete command to test updating against Northwind.Employees private void PrepareUpdateCommands(SqlDataAdapter adapter, SqlConnection conn, string table) { // insert adapter.InsertCommand = new SqlCommand() { CommandText = "INSERT INTO " + table + "(EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country) " + "VALUES (@EmployeeID, @LastName, @FirstName, @Title, @Address, @City, @Region, @PostalCode, @Country)" }; adapter.InsertCommand.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 0, "EmployeeID")); adapter.InsertCommand.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 20, "LastName")); adapter.InsertCommand.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 10, "FirstName")); adapter.InsertCommand.Parameters.Add(new SqlParameter("@Title", SqlDbType.NVarChar, 30, "Title")); adapter.InsertCommand.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 60, "Address")); adapter.InsertCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 15, "City")); adapter.InsertCommand.Parameters.Add(new SqlParameter("@Region", SqlDbType.NVarChar, 15, "Region")); adapter.InsertCommand.Parameters.Add(new SqlParameter("@PostalCode", SqlDbType.NVarChar, 10, "PostalCode")); adapter.InsertCommand.Parameters.Add(new SqlParameter("@Country", SqlDbType.NVarChar, 15, "Country")); adapter.InsertCommand.Connection = conn; // update adapter.UpdateCommand = new SqlCommand() { CommandText = "UPDATE " + table + " SET " + "EmployeeID = @EmployeeID, LastName = @LastName, FirstName = @FirstName, Title = @Title, Address = @Address, City = @City, Region = @Region, " + "PostalCode = @PostalCode, Country = @Country WHERE (EmployeeID = @OldEmployeeID)" }; adapter.UpdateCommand.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 0, "EmployeeID")); adapter.UpdateCommand.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 20, "LastName")); adapter.UpdateCommand.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 10, "FirstName")); adapter.UpdateCommand.Parameters.Add(new SqlParameter("@Title", SqlDbType.NVarChar, 30, "Title")); adapter.UpdateCommand.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 60, "Address")); adapter.UpdateCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 15, "City")); adapter.UpdateCommand.Parameters.Add(new SqlParameter("@Region", SqlDbType.NVarChar, 15, "Region")); adapter.UpdateCommand.Parameters.Add(new SqlParameter("@PostalCode", SqlDbType.NVarChar, 10, "PostalCode")); adapter.UpdateCommand.Parameters.Add(new SqlParameter("@Country", SqlDbType.NVarChar, 15, "Country")); adapter.UpdateCommand.Parameters.Add(new SqlParameter("@OldEmployeeID", SqlDbType.Int, 0, "EmployeeID")).SourceVersion = DataRowVersion.Original; adapter.UpdateCommand.Connection = conn; // // delete // adapter.DeleteCommand = new SqlCommand() { CommandText = "DELETE FROM " + table + " WHERE (EmployeeID = @EmployeeID)" }; adapter.DeleteCommand.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 0, "EmployeeID")); adapter.DeleteCommand.Connection = conn; } private void RowUpdating_UpdateRefreshTest(object sender, SqlRowUpdatingEventArgs e) { // make sure that we always get a cloned command back (which means that it should always have the badapple parameter!) e.Command = (SqlCommand)((ICloneable)e.Command).Clone(); DataTestUtility.AssertEqualsWithDescription("sp_insert", e.Command.CommandText.Substring(0, 9), "Unexpected command name."); e.Command.Parameters.RemoveAt("@badapple"); } private void RowUpdated_UpdateRefreshTest(object sender, SqlRowUpdatedEventArgs e) { DataTestUtility.AssertEqualsWithDescription("sp_insert", e.Command.CommandText.Substring(0, 9), "Unexpected command name."); } private void VerifyUpdateRow(SqlDataAdapter sa, DataSet ds, int cRows, string table) { ds.Reset(); sa.Fill(ds, table); // don't dump out all the data, just get the row count if (cRows > 0) { Assert.True(ds.Tables[0].Rows.Count == cRows, "FAILED: expected " + cRows.ToString() + " rows but got " + ds.Tables[0].Rows.Count.ToString()); } ds.Reset(); } private bool VerifyOutputParams(SqlParameterCollection sqlParameters) { return (int)sqlParameters[1].Value == 2000 && (0 == string.Compare((string)sqlParameters[2].Value, "Success!", false, CultureInfo.InvariantCulture)) && (int)sqlParameters[3].Value == 42; } private string DBConvertToString(object value) { StringBuilder builder = new StringBuilder(); WriteObject(builder, value, CultureInfo.InvariantCulture, null, 0, int.MaxValue); return builder.ToString(); } private void WriteObject(StringBuilder textBuilder, object value, CultureInfo cultureInfo, Hashtable used, int indent, int recursionLimit) { if (0 > --recursionLimit) { return; } if (null == value) { textBuilder.Append("DEFAULT"); } else if (Convert.IsDBNull(value)) { textBuilder.Append("ISNULL"); } else { Type valuetype = value.GetType(); if ((null != used) && (!valuetype.IsPrimitive)) { if (used.Contains(value)) { textBuilder.Append('#'); textBuilder.Append(((int)used[value]).ToString(cultureInfo)); return; } else { textBuilder.Append('#'); textBuilder.Append(used.Count.ToString(cultureInfo)); used.Add(value, used.Count); } } if ((value is string) || (value is SqlString)) { if (value is SqlString) { value = ((SqlString)value).Value; } textBuilder.Append(valuetype.Name); textBuilder.Append(":"); textBuilder.Append(((string)value).Length); textBuilder.Append("<"); textBuilder.Append((string)value); textBuilder.Append(">"); } else if ((value is DateTime) || (value is SqlDateTime)) { if (value is SqlDateTime) { value = ((SqlDateTime)value).Value; } textBuilder.Append(valuetype.Name); textBuilder.Append("<"); textBuilder.Append(((DateTime)value).ToString("s", cultureInfo)); textBuilder.Append(">"); } else if ((value is float) || (value is SqlSingle)) { if (value is SqlSingle) { value = ((SqlSingle)value).Value; } textBuilder.Append(valuetype.Name); textBuilder.Append("<"); textBuilder.Append(((float)value).ToString(cultureInfo)); textBuilder.Append(">"); } else if ((value is double) || (value is SqlDouble)) { if (value is SqlDouble) { value = ((SqlDouble)value).Value; } textBuilder.Append(valuetype.Name); textBuilder.Append("<"); textBuilder.Append(((double)value).ToString(cultureInfo)); textBuilder.Append(">"); } else if ((value is decimal) || (value is SqlDecimal) || (value is SqlMoney)) { if (value is SqlDecimal) { value = ((SqlDecimal)value).Value; } else if (value is SqlMoney) { value = ((SqlMoney)value).Value; } textBuilder.Append(valuetype.Name); textBuilder.Append("<"); textBuilder.Append(((decimal)value).ToString(cultureInfo)); textBuilder.Append(">"); } else if (value is INullable && ((INullable)value).IsNull) { textBuilder.Append(valuetype.Name); textBuilder.Append(" ISNULL"); } else if (valuetype.IsArray) { textBuilder.Append(valuetype.Name); Array array = (Array)value; if (1 < array.Rank) { textBuilder.Append("{"); } for (int i = 0; i < array.Rank; ++i) { int count = array.GetUpperBound(i); textBuilder.Append(' '); textBuilder.Append(count - array.GetLowerBound(i) + 1); textBuilder.Append("{ "); for (int k = array.GetLowerBound(i); k <= count; ++k) { AppendNewLineIndent(textBuilder, indent + 1); textBuilder.Append(','); WriteObject(textBuilder, array.GetValue(k), cultureInfo, used, 0, recursionLimit); textBuilder.Append(' '); } AppendNewLineIndent(textBuilder, indent); textBuilder.Append("}"); } if (1 < array.Rank) { textBuilder.Append('}'); } } else if (value is ICollection) { textBuilder.Append(valuetype.Name); ICollection collection = (ICollection)value; object[] newvalue = new object[collection.Count]; collection.CopyTo(newvalue, 0); textBuilder.Append(' '); textBuilder.Append(newvalue.Length); textBuilder.Append('{'); for (int k = 0; k < newvalue.Length; ++k) { AppendNewLineIndent(textBuilder, indent + 1); textBuilder.Append(','); WriteObject(textBuilder, newvalue[k], cultureInfo, used, indent + 1, recursionLimit); } AppendNewLineIndent(textBuilder, indent); textBuilder.Append('}'); } else if (value is Type) { textBuilder.Append(valuetype.Name); textBuilder.Append('<'); textBuilder.Append((value as Type).FullName); textBuilder.Append('>'); } else if (valuetype.IsEnum) { textBuilder.Append(valuetype.Name); textBuilder.Append('<'); textBuilder.Append(Enum.GetName(valuetype, value)); textBuilder.Append('>'); } else { string fullName = valuetype.FullName; if ("System.ComponentModel.ExtendedPropertyDescriptor" == fullName) { textBuilder.Append(fullName); } else { FieldInfo[] fields = valuetype.GetFields(BindingFlags.Instance | BindingFlags.Public); PropertyInfo[] properties = valuetype.GetProperties(BindingFlags.Instance | BindingFlags.Public); bool hasinfo = false; if ((null != fields) && (0 < fields.Length)) { textBuilder.Append(fullName); fullName = null; Array.Sort(fields, FieldInfoCompare.s_default); for (int i = 0; i < fields.Length; ++i) { FieldInfo field = fields[i]; AppendNewLineIndent(textBuilder, indent + 1); textBuilder.Append(field.Name); textBuilder.Append('='); object newvalue = field.GetValue(value); WriteObject(textBuilder, newvalue, cultureInfo, used, indent + 1, recursionLimit); } hasinfo = true; } if ((null != properties) && (0 < properties.Length)) { if (null != fullName) { textBuilder.Append(fullName); fullName = null; } Array.Sort(properties, PropertyInfoCompare.s_default); for (int i = 0; i < properties.Length; ++i) { PropertyInfo property = properties[i]; if (property.CanRead) { ParameterInfo[] parameters = property.GetIndexParameters(); if ((null == parameters) || (0 == parameters.Length)) { AppendNewLineIndent(textBuilder, indent + 1); textBuilder.Append(property.Name); textBuilder.Append('='); object newvalue = null; bool haveValue = false; try { newvalue = property.GetValue(value, BindingFlags.Public | BindingFlags.GetProperty, null, null, CultureInfo.InvariantCulture); haveValue = true; } catch (TargetInvocationException e) { textBuilder.Append(e.InnerException.GetType().Name); textBuilder.Append(": "); textBuilder.Append(e.InnerException.Message); } if (haveValue) { WriteObject(textBuilder, newvalue, cultureInfo, used, indent + 1, recursionLimit); } } } } hasinfo = true; } if (!hasinfo) { textBuilder.Append(valuetype.Name); textBuilder.Append('<'); MethodInfo method = valuetype.GetMethod("ToString", new Type[] { typeof(IFormatProvider) }); if (null != method) { textBuilder.Append((string)method.Invoke(value, new object[] { cultureInfo })); } else { string text = value.ToString(); textBuilder.Append(text); } textBuilder.Append('>'); } } } } } private void ExecuteNonQueryCommand(string cmdText) { using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = cmdText; cmd.ExecuteNonQuery(); } } private void AppendNewLineIndent(StringBuilder textBuilder, int indent) { textBuilder.Append(Environment.NewLine); char[] buf = _appendNewLineIndentBuffer; if (buf.Length < indent * 4) { buf = new char[indent * 4]; for (int i = 0; i < buf.Length; ++i) { buf[i] = ' '; } _appendNewLineIndentBuffer = buf; } textBuilder.Append(buf, 0, indent * 4); } private class PropertyInfoCompare : IComparer { internal static PropertyInfoCompare s_default = new PropertyInfoCompare(); private PropertyInfoCompare() { } public int Compare(object x, object y) { string propertyInfoName1 = ((PropertyInfo)x).Name; string propertyInfoName2 = ((PropertyInfo)y).Name; return CultureInfo.InvariantCulture.CompareInfo.Compare(propertyInfoName1, propertyInfoName2, CompareOptions.IgnoreCase); } } private class FieldInfoCompare : IComparer { internal static FieldInfoCompare s_default = new FieldInfoCompare(); private FieldInfoCompare() { } public int Compare(object x, object y) { string fieldInfoName1 = ((FieldInfo)x).Name; string fieldInfoName2 = ((FieldInfo)y).Name; return CultureInfo.InvariantCulture.CompareInfo.Compare(fieldInfoName1, fieldInfoName2, CompareOptions.IgnoreCase); } } } }
using MarkerMetro.Unity.WinIntegration.Resources; using MarkerMetro.Unity.WinIntegration.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; #if NETFX_CORE using Windows.ApplicationModel; using Windows.ApplicationModel.DataTransfer; using Windows.ApplicationModel.Contacts; using Windows.System; using System.Diagnostics; using System.Threading.Tasks; using Windows.ApplicationModel.Resources; using Windows.Networking.Connectivity; using Windows.UI.Popups; using Windows.Foundation; using Windows.Security.ExchangeActiveSyncProvisioning; using Windows.Networking.PushNotifications; using Windows.ApplicationModel.Store; #endif namespace MarkerMetro.Unity.WinIntegration { /// <summary> /// Integration Helpers /// </summary> public class Helper { private static Helper _instance; private static readonly object _sync = new object(); public static Helper Instance { get { lock (_sync) { if (_instance == null) _instance = new Helper(); } return _instance; } } /// <summary> /// Fired when the App visibility has changed /// </summary> /// <remarks> /// This should be activated in CommonMainPage.cs, when a Window.Current.VisibilityChanged happens. /// </remarks> public Action<bool> OnVisibilityChanged; /// <summary> /// Returns the application package version /// </summary> /// <returns></returns> public string GetAppVersion() { #if NETFX_CORE var major = Package.Current.Id.Version.Major; var minor = Package.Current.Id.Version.Minor.ToString(); var revision = Package.Current.Id.Version.Revision.ToString(); var build = Package.Current.Id.Version.Build.ToString(); var version = String.Format("{0}.{1}.{2}.{3}", major, minor, build, revision); return version; #else return String.Empty; #endif } /// <summary> /// Clears all local state /// </summary> /// <remarks> /// used to clear all local state from the app /// </remarks> public void ClearLocalState(Action<bool> callback) { #if NETFX_CORE Dispatcher.InvokeOnUIThread(async () => { try { await Windows.Storage.ApplicationData.Current.ClearAsync(Windows.Storage.ApplicationDataLocality.Local); if (callback != null) { Dispatcher.InvokeOnAppThread(() => callback(true)); }; } catch { if (callback != null) { Dispatcher.InvokeOnAppThread(() => callback(false)); }; } }); #else throw new PlatformNotSupportedException("ClearLocalState"); #endif } public void GetPushChannel(string channelName, Action<string> callback) { #if NETFX_CORE Dispatcher.InvokeOnUIThread(async () => { try { var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); if (callback != null) { Dispatcher.InvokeOnAppThread(() => callback(channel.Uri)); } } catch { if (callback != null) { Dispatcher.InvokeOnAppThread(() => callback(String.Empty)); } } }); #else throw new PlatformNotSupportedException("GetPushChannel(string channelName, Action<string> callback)"); #endif } /// <summary> /// Returns the application language /// </summary> /// <remarks> /// it's important to use this call rather than Unity APIs, which just return the top system language /// </remarks> public string GetAppLanguage() { #if NETFX_CORE return Windows.Globalization.ApplicationLanguages.Languages[0]; #else return System.Globalization.CultureInfo.CurrentUICulture.Name; #endif } /// <summary> /// Show the Share UI /// </summary> public void ShowShareUI() { #if NETFX_CORE try { Dispatcher.InvokeOnUIThread(() => DataTransferManager.ShowShareUI()); } catch (Exception ex) { # if DEBUG Debug.WriteLine("Unable to show the share UI because of: " + ex.Message); # else ExceptionLogger.Send(ex); # endif } #endif } /// <summary> /// Show the Share UI with a link - WP8 only /// </summary> /// <param name="text"></param> /// <param name="linkURL"></param> public void ShowShareUI(string text, string linkURL) { ShowShareUI(text, text, linkURL); } /// <summary> /// Show the Share UI with a link - WP8 only /// </summary> /// <param name="text"></param> /// <param name="message"></param> /// <param name="linkURL"></param> public void ShowShareUI(string text, string message, string linkURL) { #if NETFX_CORE throw new NotImplementedException("Not implemented for Windows Store Apps, use ShowShareUI() instead."); #endif } /// <summary> /// Show the Rate UI /// </summary> public void ShowRateUI() { #if NETFX_CORE Dispatcher.InvokeOnUIThread( async () => { try { Uri uri; #if WINDOWS_PHONE_APP uri = new Uri(String.Format("ms-windows-store:REVIEWAPP?appid={0}", CurrentApp.AppId)); #else var data = Package.Current.Id.FamilyName; uri = new Uri(String.Format("ms-windows-store:REVIEW?PFN={0}", data)); #endif # if DEBUG Debug.WriteLine(uri.ToString()); # endif await Launcher.LaunchUriAsync(uri); } catch (Exception ex) { # if DEBUG Debug.WriteLine("Unable to show MarketplaceReviewTask because of: " + ex.Message); # else ExceptionLogger.Send(ex); # endif } }); #else throw new NotImplementedException("Not implemented for unknown platform"); #endif } /// <summary> /// Uses a roaming Guid for Windows 8 and the device id for WP8 /// </summary> /// <returns></returns> public string GetUserDeviceId() { #if NETFX_CORE const string key = "UserDeviceId"; var values = Windows.Storage.ApplicationData.Current.RoamingSettings.Values; if (!values.ContainsKey(key)) { var value = Guid.NewGuid().ToString().Replace("-", ""); values[key] = value; } return (string)values[key]; #else throw new PlatformNotSupportedException("GetUserDeviceId()"); #endif } /// <summary> /// Returns the device manufacturer name. /// </summary> public string GetManufacturer() { #if NETFX_CORE return new EasClientDeviceInformation().SystemManufacturer; #else throw new PlatformNotSupportedException("GetManufacturer()"); #endif } /// <summary> /// Returns the device model (e.g. "NOKIA Lumia 720"). /// </summary> /// <remarks> /// If we need a more friendly name on WP8, read this: /// http://stackoverflow.com/questions/17425016/information-about-windows-phone-model-number /// </remarks> public string GetModel() { #if NETFX_CORE return new EasClientDeviceInformation().SystemProductName; #else throw new PlatformNotSupportedException("GetManufacturer()"); #endif } /// <summary> /// Returns the application's store url. Note: This won't be valid until the apps are published /// </summary> /// <returns></returns> public string GetAppStoreUri() { #if NETFX_CORE return "ms-windows-store:PDP?PFN=" + Package.Current.Id.FamilyName; #else return ""; #endif } #if NETFX_CORE && !WINDOWS_PHONE_APP public enum ProcessorArchitecture : ushort { INTEL = 0, MIPS = 1, ALPHA = 2, PPC = 3, SHX = 4, ARM = 5, IA64 = 6, ALPHA64 = 7, MSIL = 8, AMD64 = 9, IA32_ON_WIN64 = 10, UNKNOWN = 0xFFFF } [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] internal struct SYSTEM_INFO { public ushort wProcessorArchitecture; public ushort wReserved; public uint dwPageSize; public IntPtr lpMinimumApplicationAddress; public IntPtr lpMaximumApplicationAddress; public UIntPtr dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public ushort wProcessorLevel; public ushort wProcessorRevision; }; [System.Runtime.InteropServices.DllImport("kernel32.dll")] internal static extern void GetNativeSystemInfo(ref SYSTEM_INFO lpSystemInfo); #endif /// <summary> /// Determine whether or not a Windows device is generally considered low end /// </summary> /// <returns>Windows 8 Arm or Windows Phone Low Mem returns true</returns> public bool IsLowEndDevice() { #if WINDOWS_PHONE_APP long result = 0; try { result = (long)MemoryManager.AppMemoryUsageLimit; } catch (ArgumentOutOfRangeException) { // The device does not support querying for this value. This occurs // on Windows Phone OS 7.1 and older phones without OS updates. } return result <= 188743680; // less than or equal to 180MB including failure scenario #elif NETFX_CORE var systemInfo = new SYSTEM_INFO(); GetNativeSystemInfo(ref systemInfo); return systemInfo.wProcessorArchitecture == (uint)ProcessorArchitecture.ARM; #else return false; #endif } public bool HasInternetConnection { get { #if NETFX_CORE var profile = NetworkInformation.GetInternetConnectionProfile(); return profile != null && profile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess; #else throw new PlatformNotSupportedException("HasInternetConnection"); #endif } } public bool IsMeteredConnection { get { #if NETFX_CORE var profile = NetworkInformation.GetInternetConnectionProfile(); if (profile == null) { return false; } return profile.GetConnectionCost().NetworkCostType != NetworkCostType.Unrestricted; #else throw new PlatformNotSupportedException("IsMeteredConnection"); #endif } } public void ShowDialog(string contentKey, string titleKey, Action callback) { #if NETFX_CORE if (string.IsNullOrWhiteSpace(contentKey)) throw new ArgumentNullException("You must specify content resource key"); Dispatcher.InvokeOnUIThread(() => { var resourceHelper = ResourceHelper.GetInstance(); var content = resourceHelper.GetString(contentKey); var title = string.Empty; if (titleKey != null) title = resourceHelper.GetString(titleKey); #if NETFX_CORE ShowDialogAsync(contentKey, titleKey, callback).ContinueWith(t => { }); }); # endif #else throw new PlatformNotSupportedException("ShowDialog"); #endif } public void ShowDialog(string content, string title, Action<bool> callback, string okText = "", string cancelText = "") { #if NETFX_CORE Dispatcher.InvokeOnUIThread(() => { ShowDialogAsync(content, title, callback, okText, cancelText).ContinueWith(t => { }); }); #else throw new PlatformNotSupportedException("ShowDialog"); #endif } #if NETFX_CORE async Task ShowDialogAsync(string content, string title, Action callback) { var dialog = string.IsNullOrWhiteSpace(title) ? new MessageDialog(content) : new MessageDialog(content, title); await dialog.ShowAsync(); if (callback != null) Dispatcher.InvokeOnAppThread(() => callback()); } async Task ShowDialogAsync(string content, string title, Action<bool> callback, string okText, string cancelText) { var dialog = string.IsNullOrWhiteSpace(title) ? new MessageDialog(content) : new MessageDialog(content, title); Action<bool> callbackOnApp = b => Dispatcher.InvokeOnAppThread(() => callback(b)); if (!string.IsNullOrWhiteSpace(okText)) { dialog.Commands.Add(new UICommand(okText, new UICommandInvokedHandler( (command) => { if (callback != null) callbackOnApp(true); }))); } if (!string.IsNullOrWhiteSpace(cancelText)) { dialog.Commands.Add(new UICommand(cancelText, new UICommandInvokedHandler( (command) => { if (callback != null) callbackOnApp(false); }))); } if (!string.IsNullOrWhiteSpace(okText) && !string.IsNullOrWhiteSpace(cancelText)) { // Set the command that will be invoked by default dialog.DefaultCommandIndex = 0; // Set the command to be invoked when escape is pressed dialog.CancelCommandIndex = 1; } await dialog.ShowAsync(); } #endif /// <summary> /// Win8 - Launches a mailto: URI. /// WP8 - Calls email compose task. /// </summary> /// <param name="to">A comma-separated list of email addresses.</param> /// <param name="subject">The subject of the message.</param> /// <param name="body">The body of the message.</param> public void SendEmail(string to, string subject, string body) { #if NETFX_CORE Dispatcher.InvokeOnUIThread(async () => { subject = Uri.EscapeDataString(subject); body = Uri.EscapeDataString(body); var mailto = new Uri(String.Format("mailto:?to={0}&subject={1}&body={2}", to, subject, body)); await Launcher.LaunchUriAsync(mailto); }); #endif } } }
// // This CSharp output file generated by Gardens Point LEX // Gardens Point LEX (GPLEX) is Copyright (c) John Gough, QUT 2006-2014. // Output produced by GPLEX is the property of the user. // See accompanying file GPLEXcopyright.rtf. // // Version: 1.2.2 // Machine: // DateTime: // UserName: // GPLEX input file // GPLEX frame file <embedded resource> // // Option settings: verbose, parser, stack, minimize // Option settings: compressNext, persistBuffer, noEmbedBuffers // // // Revised backup code // Version 1.2.1 of 24-June-2013 // // #define STACK #define PERSIST #define BYTEMODE using System; using System.IO; using System.Text; using System.Globalization; using System.Collections.Generic; using System.Runtime.Serialization; using System.Diagnostics.CodeAnalysis; using QUT.GplexBuffers; namespace Calculator { /// <summary> /// Summary Canonical example of GPLEX automaton /// </summary> #if STANDALONE // // These are the dummy declarations for stand-alone GPLEX applications // normally these declarations would come from the parser. // If you declare /noparser, or %option noparser then you get this. // internal enum Token { EOF = 0, maxParseToken = int.MaxValue // must have at least these two, values are almost arbitrary } internal abstract class ScanBase { [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yylex")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yylex")] public abstract int yylex(); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yywrap")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yywrap")] protected virtual bool yywrap() { return true; } #if BABEL protected abstract int CurrentSc { get; set; } // EolState is the 32-bit of state data persisted at // the end of each line for Visual Studio colorization. // The default is to return CurrentSc. You must override // this if you want more complicated behavior. public virtual int EolState { get { return CurrentSc; } set { CurrentSc = value; } } } internal interface IColorScan { void SetSource(string source, int offset); int GetNext(ref int state, out int start, out int end); #endif // BABEL } #endif // STANDALONE // If the compiler can't find the scanner base class maybe you // need to run GPPG with the /gplex option, or GPLEX with /noparser #if BABEL internal sealed partial class CalculatorScanner : ScanBase, IColorScan { private ScanBuff buffer; int currentScOrd; // start condition ordinal protected override int CurrentSc { // The current start state is a property // to try to avoid the user error of setting // scState but forgetting to update the FSA // start state "currentStart" // get { return currentScOrd; } // i.e. return YY_START; set { currentScOrd = value; // i.e. BEGIN(value); currentStart = startState[value]; } } #else // BABEL internal sealed partial class CalculatorScanner : ScanBase { private ScanBuff buffer; int currentScOrd; // start condition ordinal #endif // BABEL /// <summary> /// The input buffer for this scanner. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ScanBuff Buffer { get { return buffer; } } private static int GetMaxParseToken() { System.Reflection.FieldInfo f = typeof(Token).GetField("maxParseToken"); return (f == null ? int.MaxValue : (int)f.GetValue(null)); } static int parserMax = GetMaxParseToken(); enum Result {accept, noMatch, contextFound}; const int maxAccept = 8; const int initial = 9; const int eofNum = 0; const int goStart = -1; const int INITIAL = 0; #region user code #endregion user code int state; int currentStart = startState[0]; int code; // last code read int cCol; // column number of code int lNum; // current line number // // The following instance variables are used, among other // things, for constructing the yylloc location objects. // int tokPos; // buffer position at start of token int tokCol; // zero-based column number at start of token int tokLin; // line number at start of token int tokEPos; // buffer position at end of token int tokECol; // column number at end of token int tokELin; // line number at end of token string tokTxt; // lazily constructed text of token #if STACK private Stack<int> scStack = new Stack<int>(); #endif // STACK #region ScannerTables struct Table { public int min; public int rng; public int dflt; public sbyte[] nxt; public Table(int m, int x, int d, sbyte[] n) { min = m; rng = x; dflt = d; nxt = n; } }; static int[] startState = new int[] {9, 0}; static Table[] NxS = new Table[10] { /* NxS[ 0] */ new Table(0, 0, 0, null), // Shortest string "" /* NxS[ 1] */ // Shortest string "\t" new Table(9, 24, -1, new sbyte[] {1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1}), /* NxS[ 2] */ new Table(0, 0, -1, null), // Shortest string "(" /* NxS[ 3] */ new Table(0, 0, -1, null), // Shortest string ")" /* NxS[ 4] */ new Table(0, 0, -1, null), // Shortest string "*" /* NxS[ 5] */ new Table(0, 0, -1, null), // Shortest string "+" /* NxS[ 6] */ new Table(0, 0, -1, null), // Shortest string "-" /* NxS[ 7] */ new Table(0, 0, -1, null), // Shortest string "/" /* NxS[ 8] */ // Shortest string "0" new Table(48, 10, -1, new sbyte[] {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}), /* NxS[ 9] */ // Shortest string "" new Table(9, 49, -1, new sbyte[] {1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, -1, 6, -1, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}), }; int NextState() { if (code == ScanBuff.EndOfFile) return eofNum; else unchecked { int rslt; int idx = (byte)(code - NxS[state].min); if ((uint)idx >= (uint)NxS[state].rng) rslt = NxS[state].dflt; else rslt = NxS[state].nxt[idx]; return rslt; } } #endregion #if BACKUP // ============================================================== // == Nested struct used for backup in automata that do backup == // ============================================================== struct Context // class used for automaton backup. { public int bPos; public int rPos; // scanner.readPos saved value public int cCol; public int lNum; // Need this in case of backup over EOL. public int state; public int cChr; } private Context ctx = new Context(); #endif // BACKUP // ============================================================== // ==== Nested struct to support input switching in scanners ==== // ============================================================== struct BufferContext { internal ScanBuff buffSv; internal int chrSv; internal int cColSv; internal int lNumSv; } // ============================================================== // ===== Private methods to save and restore buffer contexts ==== // ============================================================== /// <summary> /// This method creates a buffer context record from /// the current buffer object, together with some /// scanner state values. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] BufferContext MkBuffCtx() { BufferContext rslt; rslt.buffSv = this.buffer; rslt.chrSv = this.code; rslt.cColSv = this.cCol; rslt.lNumSv = this.lNum; return rslt; } /// <summary> /// This method restores the buffer value and allied /// scanner state from the given context record value. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] void RestoreBuffCtx(BufferContext value) { this.buffer = value.buffSv; this.code = value.chrSv; this.cCol = value.cColSv; this.lNum = value.lNumSv; } // =================== End Nested classes ======================= #if !NOFILES internal CalculatorScanner(Stream file) { SetSource(file); // no unicode option } #endif // !NOFILES internal CalculatorScanner() { } private int readPos; void GetCode() { if (code == '\n') // This needs to be fixed for other conventions // i.e. [\r\n\205\u2028\u2029] { cCol = -1; lNum++; } readPos = buffer.Pos; // Now read new codepoint. code = buffer.Read(); if (code > ScanBuff.EndOfFile) { #if (!BYTEMODE) if (code >= 0xD800 && code <= 0xDBFF) { int next = buffer.Read(); if (next < 0xDC00 || next > 0xDFFF) code = ScanBuff.UnicodeReplacementChar; else code = (0x10000 + ((code & 0x3FF) << 10) + (next & 0x3FF)); } #endif cCol++; } } void MarkToken() { #if (!PERSIST) buffer.Mark(); #endif tokPos = readPos; tokLin = lNum; tokCol = cCol; } void MarkEnd() { tokTxt = null; tokEPos = readPos; tokELin = lNum; tokECol = cCol; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] int Peek() { int rslt, codeSv = code, cColSv = cCol, lNumSv = lNum, bPosSv = buffer.Pos; GetCode(); rslt = code; lNum = lNumSv; cCol = cColSv; code = codeSv; buffer.Pos = bPosSv; return rslt; } // ============================================================== // ===== Initialization of string-based input buffers ==== // ============================================================== /// <summary> /// Create and initialize a StringBuff buffer object for this scanner /// </summary> /// <param name="source">the input string</param> /// <param name="offset">starting offset in the string</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void SetSource(string source, int offset) { this.buffer = ScanBuff.GetBuffer(source); this.buffer.Pos = offset; this.lNum = 0; this.code = '\n'; // to initialize yyline, yycol and lineStart GetCode(); } // ================ LineBuffer Initialization =================== /// <summary> /// Create and initialize a LineBuff buffer object for this scanner /// </summary> /// <param name="source">the list of input strings</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void SetSource(IList<string> source) { this.buffer = ScanBuff.GetBuffer(source); this.code = '\n'; // to initialize yyline, yycol and lineStart this.lNum = 0; GetCode(); } #if !NOFILES // =============== StreamBuffer Initialization ================== /// <summary> /// Create and initialize a StreamBuff buffer object for this scanner. /// StreamBuff is buffer for 8-bit byte files. /// </summary> /// <param name="source">the input byte stream</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void SetSource(Stream source) { this.buffer = ScanBuff.GetBuffer(source); this.lNum = 0; this.code = '\n'; // to initialize yyline, yycol and lineStart GetCode(); } #if !BYTEMODE // ================ TextBuffer Initialization =================== /// <summary> /// Create and initialize a TextBuff buffer object for this scanner. /// TextBuff is a buffer for encoded unicode files. /// </summary> /// <param name="source">the input text file</param> /// <param name="fallbackCodePage">Code page to use if file has /// no BOM. For 0, use machine default; for -1, 8-bit binary</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void SetSource(Stream source, int fallbackCodePage) { this.buffer = ScanBuff.GetBuffer(source, fallbackCodePage); this.lNum = 0; this.code = '\n'; // to initialize yyline, yycol and lineStart GetCode(); } #endif // !BYTEMODE #endif // !NOFILES // ============================================================== #if BABEL // // Get the next token for Visual Studio // // "state" is the inout mode variable that maintains scanner // state between calls, using the EolState property. In principle, // if the calls of EolState are costly set could be called once // only per line, at the start; and get called only at the end // of the line. This needs more infrastructure ... // public int GetNext(ref int state, out int start, out int end) { Token next; int s, e; s = state; // state at start EolState = state; next = (Token)Scan(); state = EolState; e = state; // state at end; start = tokPos; end = tokEPos - 1; // end is the index of last char. return (int)next; } #endif // BABEL // ======== AbstractScanner<> Implementation ========= [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yylex")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yylex")] public override int yylex() { // parserMax is set by reflecting on the Tokens // enumeration. If maxParseToken is defined // that is used, otherwise int.MaxValue is used. int next; do { next = Scan(); } while (next >= parserMax); return next; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] int yypos { get { return tokPos; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] int yyline { get { return tokLin; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] int yycol { get { return tokCol; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yytext")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yytext")] public string yytext { get { if (tokTxt == null) tokTxt = buffer.GetString(tokPos, tokEPos); return tokTxt; } } /// <summary> /// Discards all but the first "n" codepoints in the recognized pattern. /// Resets the buffer position so that only n codepoints have been consumed; /// yytext is also re-evaluated. /// </summary> /// <param name="n">The number of codepoints to consume</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] void yyless(int n) { buffer.Pos = tokPos; // Must read at least one char, so set before start. cCol = tokCol - 1; GetCode(); // Now ensure that line counting is correct. lNum = tokLin; // And count the rest of the text. for (int i = 0; i < n; i++) GetCode(); MarkEnd(); } // // It would be nice to count backward in the text // but it does not seem possible to re-establish // the correct column counts except by going forward. // /// <summary> /// Removes the last "n" code points from the pattern. /// </summary> /// <param name="n">The number to remove</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] void _yytrunc(int n) { yyless(yyleng - n); } // // This is painful, but we no longer count // codepoints. For the overwhelming majority // of cases the single line code is fast, for // the others, well, at least it is all in the // buffer so no files are touched. Note that we // can't use (tokEPos - tokPos) because of the // possibility of surrogate pairs in the token. // /// <summary> /// The length of the pattern in codepoints (not the same as /// string-length if the pattern contains any surrogate pairs). /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yyleng")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yyleng")] public int yyleng { get { if (tokELin == tokLin) return tokECol - tokCol; else #if BYTEMODE return tokEPos - tokPos; #else { int ch; int count = 0; int save = buffer.Pos; buffer.Pos = tokPos; do { ch = buffer.Read(); if (!char.IsHighSurrogate((char)ch)) count++; } while (buffer.Pos < tokEPos && ch != ScanBuff.EndOfFile); buffer.Pos = save; return count; } #endif // BYTEMODE } } // ============ methods available in actions ============== [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal int YY_START { get { return currentScOrd; } set { currentScOrd = value; currentStart = startState[value]; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal void BEGIN(int next) { currentScOrd = next; currentStart = startState[next]; } // ============== The main tokenizer code ================= int Scan() { for (; ; ) { int next; // next state to enter #if LEFTANCHORS for (;;) { // Discard characters that do not start any pattern. // Must check the left anchor condition after *every* GetCode! state = ((cCol == 0) ? anchorState[currentScOrd] : currentStart); if ((next = NextState()) != goStart) break; // LOOP EXIT HERE... GetCode(); } #else // !LEFTANCHORS state = currentStart; while ((next = NextState()) == goStart) { // At this point, the current character has no // transition from the current state. We discard // the "no-match" char. In traditional LEX such // characters are echoed to the console. GetCode(); } #endif // LEFTANCHORS // At last, a valid transition ... MarkToken(); state = next; GetCode(); #if BACKUP bool contextSaved = false; while ((next = NextState()) > eofNum) { // Exit for goStart AND for eofNum if (state <= maxAccept && next > maxAccept) { // need to prepare backup data // Store data for the *latest* accept state that was found. SaveStateAndPos( ref ctx ); contextSaved = true; } state = next; GetCode(); } if (state > maxAccept && contextSaved) RestoreStateAndPos( ref ctx ); #else // BACKUP while ((next = NextState()) > eofNum) { // Exit for goStart AND for eofNum state = next; GetCode(); } #endif // BACKUP if (state <= maxAccept) { MarkEnd(); #region ActionSwitch #pragma warning disable 162, 1522 switch (state) { case eofNum: if (yywrap()) return (int)Token.EOF; break; case 1: // Recognized '{Space}+', Shortest string "\t" /* skip */ break; case 2: // Recognized '{POpen}', Shortest string "(" Console.WriteLine("token: {0}", yytext); return (int)Token.P_OPEN; break; case 3: // Recognized '{PClose}', Shortest string ")" Console.WriteLine("token: {0}", yytext); return (int)Token.P_CLOSE; break; case 4: // Recognized '{OpMult}', Shortest string "*" Console.WriteLine("token: {0}", yytext); return (int)Token.OP_MULT; break; case 5: // Recognized '{OpPlus}', Shortest string "+" Console.WriteLine("token: {0}", yytext); return (int)Token.OP_PLUS; break; case 6: // Recognized '{OpMinus}', Shortest string "-" Console.WriteLine("token: {0}", yytext); return (int)Token.OP_MINUS; break; case 7: // Recognized '{OpDiv}', Shortest string "/" Console.WriteLine("token: {0}", yytext); return (int)Token.OP_DIV; break; case 8: // Recognized '{Number}', Shortest string "0" Console.WriteLine("token: {0}", yytext); GetNumber(); return (int)Token.NUMBER; break; default: break; } #pragma warning restore 162, 1522 #endregion } } } #if BACKUP void SaveStateAndPos(ref Context ctx) { ctx.bPos = buffer.Pos; ctx.rPos = readPos; ctx.cCol = cCol; ctx.lNum = lNum; ctx.state = state; ctx.cChr = code; } void RestoreStateAndPos(ref Context ctx) { buffer.Pos = ctx.bPos; readPos = ctx.rPos; cCol = ctx.cCol; lNum = ctx.lNum; state = ctx.state; code = ctx.cChr; } #endif // BACKUP // ============= End of the tokenizer code ================ #if STACK [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal void yy_clear_stack() { scStack.Clear(); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal int yy_top_state() { return scStack.Peek(); } internal void yy_push_state(int state) { scStack.Push(currentScOrd); BEGIN(state); } internal void yy_pop_state() { // Protect against input errors that pop too far ... if (scStack.Count > 0) { int newSc = scStack.Pop(); BEGIN(newSc); } // Otherwise leave stack unchanged. } #endif // STACK [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal void ECHO() { Console.Out.Write(yytext); } } // end class $Scanner } // end namespace
namespace AverageFrequencyCalculator.Framework { partial class MainWindow { /// <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.RootPanel = new System.Windows.Forms.Panel(); this.StatusTabControl = new System.Windows.Forms.TabControl(); this.AlgorithmTabPage = new System.Windows.Forms.TabPage(); this.AlgorithmMessageBox = new System.Windows.Forms.RichTextBox(); this.SubscriberTabPage = new System.Windows.Forms.TabPage(); this.SubscriberSplitContainer = new System.Windows.Forms.SplitContainer(); this.SubscriberStatusGroupBox = new System.Windows.Forms.GroupBox(); this.SubscriberStatusBox = new System.Windows.Forms.RichTextBox(); this.SubscriberMessageGroupBox = new System.Windows.Forms.GroupBox(); this.SubscriberMessageBox = new System.Windows.Forms.RichTextBox(); this.ConcentratorTabPage = new System.Windows.Forms.TabPage(); this.ConcentratorSplitContainer = new System.Windows.Forms.SplitContainer(); this.ConcentratorStatusGroupBox = new System.Windows.Forms.GroupBox(); this.ConcentratorStatusBox = new System.Windows.Forms.RichTextBox(); this.ConcentratorMessageGroupBox = new System.Windows.Forms.GroupBox(); this.ConcentratorMessageBox = new System.Windows.Forms.RichTextBox(); this.panel1 = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.RootPanel.SuspendLayout(); this.StatusTabControl.SuspendLayout(); this.AlgorithmTabPage.SuspendLayout(); this.SubscriberTabPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.SubscriberSplitContainer)).BeginInit(); this.SubscriberSplitContainer.Panel1.SuspendLayout(); this.SubscriberSplitContainer.Panel2.SuspendLayout(); this.SubscriberSplitContainer.SuspendLayout(); this.SubscriberStatusGroupBox.SuspendLayout(); this.SubscriberMessageGroupBox.SuspendLayout(); this.ConcentratorTabPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.ConcentratorSplitContainer)).BeginInit(); this.ConcentratorSplitContainer.Panel1.SuspendLayout(); this.ConcentratorSplitContainer.Panel2.SuspendLayout(); this.ConcentratorSplitContainer.SuspendLayout(); this.ConcentratorStatusGroupBox.SuspendLayout(); this.ConcentratorMessageGroupBox.SuspendLayout(); this.SuspendLayout(); // // RootPanel // this.RootPanel.Controls.Add(this.StatusTabControl); this.RootPanel.Controls.Add(this.panel1); this.RootPanel.Controls.Add(this.label1); this.RootPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.RootPanel.Location = new System.Drawing.Point(0, 0); this.RootPanel.Name = "RootPanel"; this.RootPanel.Padding = new System.Windows.Forms.Padding(10); this.RootPanel.Size = new System.Drawing.Size(734, 459); this.RootPanel.TabIndex = 1; // // StatusTabControl // this.StatusTabControl.Alignment = System.Windows.Forms.TabAlignment.Bottom; this.StatusTabControl.Controls.Add(this.AlgorithmTabPage); this.StatusTabControl.Controls.Add(this.SubscriberTabPage); this.StatusTabControl.Controls.Add(this.ConcentratorTabPage); this.StatusTabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.StatusTabControl.Location = new System.Drawing.Point(10, 43); this.StatusTabControl.Name = "StatusTabControl"; this.StatusTabControl.SelectedIndex = 0; this.StatusTabControl.Size = new System.Drawing.Size(714, 406); this.StatusTabControl.TabIndex = 3; // // AlgorithmTabPage // this.AlgorithmTabPage.Controls.Add(this.AlgorithmMessageBox); this.AlgorithmTabPage.Location = new System.Drawing.Point(4, 4); this.AlgorithmTabPage.Name = "AlgorithmTabPage"; this.AlgorithmTabPage.Size = new System.Drawing.Size(706, 380); this.AlgorithmTabPage.TabIndex = 2; this.AlgorithmTabPage.Text = "Algorithm"; this.AlgorithmTabPage.UseVisualStyleBackColor = true; // // AlgorithmMessageBox // this.AlgorithmMessageBox.BackColor = System.Drawing.SystemColors.Window; this.AlgorithmMessageBox.Dock = System.Windows.Forms.DockStyle.Fill; this.AlgorithmMessageBox.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.AlgorithmMessageBox.Location = new System.Drawing.Point(0, 0); this.AlgorithmMessageBox.Name = "AlgorithmMessageBox"; this.AlgorithmMessageBox.ReadOnly = true; this.AlgorithmMessageBox.Size = new System.Drawing.Size(706, 380); this.AlgorithmMessageBox.TabIndex = 0; this.AlgorithmMessageBox.Text = ""; // // SubscriberTabPage // this.SubscriberTabPage.Controls.Add(this.SubscriberSplitContainer); this.SubscriberTabPage.Location = new System.Drawing.Point(4, 4); this.SubscriberTabPage.Name = "SubscriberTabPage"; this.SubscriberTabPage.Padding = new System.Windows.Forms.Padding(3); this.SubscriberTabPage.Size = new System.Drawing.Size(706, 380); this.SubscriberTabPage.TabIndex = 0; this.SubscriberTabPage.Text = "Subscriber"; this.SubscriberTabPage.UseVisualStyleBackColor = true; // // SubscriberSplitContainer // this.SubscriberSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.SubscriberSplitContainer.Location = new System.Drawing.Point(3, 3); this.SubscriberSplitContainer.Name = "SubscriberSplitContainer"; // // SubscriberSplitContainer.Panel1 // this.SubscriberSplitContainer.Panel1.BackColor = System.Drawing.SystemColors.Control; this.SubscriberSplitContainer.Panel1.Controls.Add(this.SubscriberStatusGroupBox); // // SubscriberSplitContainer.Panel2 // this.SubscriberSplitContainer.Panel2.Controls.Add(this.SubscriberMessageGroupBox); this.SubscriberSplitContainer.Size = new System.Drawing.Size(700, 374); this.SubscriberSplitContainer.SplitterDistance = 350; this.SubscriberSplitContainer.SplitterWidth = 2; this.SubscriberSplitContainer.TabIndex = 1; // // SubscriberStatusGroupBox // this.SubscriberStatusGroupBox.Controls.Add(this.SubscriberStatusBox); this.SubscriberStatusGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.SubscriberStatusGroupBox.Location = new System.Drawing.Point(0, 0); this.SubscriberStatusGroupBox.Name = "SubscriberStatusGroupBox"; this.SubscriberStatusGroupBox.Size = new System.Drawing.Size(350, 374); this.SubscriberStatusGroupBox.TabIndex = 1; this.SubscriberStatusGroupBox.TabStop = false; this.SubscriberStatusGroupBox.Text = "Status"; // // SubscriberStatusBox // this.SubscriberStatusBox.BackColor = System.Drawing.SystemColors.Window; this.SubscriberStatusBox.Dock = System.Windows.Forms.DockStyle.Fill; this.SubscriberStatusBox.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.SubscriberStatusBox.Location = new System.Drawing.Point(3, 16); this.SubscriberStatusBox.Name = "SubscriberStatusBox"; this.SubscriberStatusBox.ReadOnly = true; this.SubscriberStatusBox.Size = new System.Drawing.Size(344, 355); this.SubscriberStatusBox.TabIndex = 0; this.SubscriberStatusBox.Text = ""; this.SubscriberStatusBox.WordWrap = false; // // SubscriberMessageGroupBox // this.SubscriberMessageGroupBox.Controls.Add(this.SubscriberMessageBox); this.SubscriberMessageGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.SubscriberMessageGroupBox.Location = new System.Drawing.Point(0, 0); this.SubscriberMessageGroupBox.Name = "SubscriberMessageGroupBox"; this.SubscriberMessageGroupBox.Size = new System.Drawing.Size(348, 374); this.SubscriberMessageGroupBox.TabIndex = 1; this.SubscriberMessageGroupBox.TabStop = false; this.SubscriberMessageGroupBox.Text = "Messages"; // // SubscriberMessageBox // this.SubscriberMessageBox.BackColor = System.Drawing.SystemColors.Window; this.SubscriberMessageBox.Dock = System.Windows.Forms.DockStyle.Fill; this.SubscriberMessageBox.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.SubscriberMessageBox.Location = new System.Drawing.Point(3, 16); this.SubscriberMessageBox.Name = "SubscriberMessageBox"; this.SubscriberMessageBox.ReadOnly = true; this.SubscriberMessageBox.Size = new System.Drawing.Size(342, 355); this.SubscriberMessageBox.TabIndex = 0; this.SubscriberMessageBox.Text = ""; this.SubscriberMessageBox.WordWrap = false; // // ConcentratorTabPage // this.ConcentratorTabPage.Controls.Add(this.ConcentratorSplitContainer); this.ConcentratorTabPage.Location = new System.Drawing.Point(4, 4); this.ConcentratorTabPage.Name = "ConcentratorTabPage"; this.ConcentratorTabPage.Padding = new System.Windows.Forms.Padding(3); this.ConcentratorTabPage.Size = new System.Drawing.Size(706, 380); this.ConcentratorTabPage.TabIndex = 1; this.ConcentratorTabPage.Text = "Concentrator"; this.ConcentratorTabPage.UseVisualStyleBackColor = true; // // ConcentratorSplitContainer // this.ConcentratorSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.ConcentratorSplitContainer.Location = new System.Drawing.Point(3, 3); this.ConcentratorSplitContainer.Name = "ConcentratorSplitContainer"; // // ConcentratorSplitContainer.Panel1 // this.ConcentratorSplitContainer.Panel1.BackColor = System.Drawing.SystemColors.Control; this.ConcentratorSplitContainer.Panel1.Controls.Add(this.ConcentratorStatusGroupBox); // // ConcentratorSplitContainer.Panel2 // this.ConcentratorSplitContainer.Panel2.Controls.Add(this.ConcentratorMessageGroupBox); this.ConcentratorSplitContainer.Size = new System.Drawing.Size(700, 374); this.ConcentratorSplitContainer.SplitterDistance = 350; this.ConcentratorSplitContainer.SplitterWidth = 2; this.ConcentratorSplitContainer.TabIndex = 1; // // ConcentratorStatusGroupBox // this.ConcentratorStatusGroupBox.Controls.Add(this.ConcentratorStatusBox); this.ConcentratorStatusGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.ConcentratorStatusGroupBox.Location = new System.Drawing.Point(0, 0); this.ConcentratorStatusGroupBox.Name = "ConcentratorStatusGroupBox"; this.ConcentratorStatusGroupBox.Size = new System.Drawing.Size(350, 374); this.ConcentratorStatusGroupBox.TabIndex = 0; this.ConcentratorStatusGroupBox.TabStop = false; this.ConcentratorStatusGroupBox.Text = "Status"; // // ConcentratorStatusBox // this.ConcentratorStatusBox.BackColor = System.Drawing.SystemColors.Window; this.ConcentratorStatusBox.Dock = System.Windows.Forms.DockStyle.Fill; this.ConcentratorStatusBox.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ConcentratorStatusBox.Location = new System.Drawing.Point(3, 16); this.ConcentratorStatusBox.Name = "ConcentratorStatusBox"; this.ConcentratorStatusBox.ReadOnly = true; this.ConcentratorStatusBox.Size = new System.Drawing.Size(344, 355); this.ConcentratorStatusBox.TabIndex = 0; this.ConcentratorStatusBox.Text = ""; this.ConcentratorStatusBox.WordWrap = false; // // ConcentratorMessageGroupBox // this.ConcentratorMessageGroupBox.Controls.Add(this.ConcentratorMessageBox); this.ConcentratorMessageGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.ConcentratorMessageGroupBox.Location = new System.Drawing.Point(0, 0); this.ConcentratorMessageGroupBox.Name = "ConcentratorMessageGroupBox"; this.ConcentratorMessageGroupBox.Size = new System.Drawing.Size(348, 374); this.ConcentratorMessageGroupBox.TabIndex = 0; this.ConcentratorMessageGroupBox.TabStop = false; this.ConcentratorMessageGroupBox.Text = "Messages"; // // ConcentratorMessageBox // this.ConcentratorMessageBox.BackColor = System.Drawing.SystemColors.Window; this.ConcentratorMessageBox.Dock = System.Windows.Forms.DockStyle.Fill; this.ConcentratorMessageBox.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ConcentratorMessageBox.Location = new System.Drawing.Point(3, 16); this.ConcentratorMessageBox.Name = "ConcentratorMessageBox"; this.ConcentratorMessageBox.ReadOnly = true; this.ConcentratorMessageBox.Size = new System.Drawing.Size(342, 355); this.ConcentratorMessageBox.TabIndex = 0; this.ConcentratorMessageBox.Text = ""; this.ConcentratorMessageBox.WordWrap = false; // // panel1 // this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(10, 33); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(714, 10); this.panel1.TabIndex = 2; // // label1 // this.label1.Dock = System.Windows.Forms.DockStyle.Top; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(10, 10); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(714, 23); this.label1.TabIndex = 1; this.label1.Text = "AverageFrequencyCalculator is running. To stop the algorithm, close this window."; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // MainWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(734, 459); this.Controls.Add(this.RootPanel); this.Name = "MainWindow"; this.Text = "AverageFrequencyCalculator"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainWindow_FormClosed); this.Load += new System.EventHandler(this.MainWindow_Load); this.RootPanel.ResumeLayout(false); this.StatusTabControl.ResumeLayout(false); this.AlgorithmTabPage.ResumeLayout(false); this.SubscriberTabPage.ResumeLayout(false); this.SubscriberSplitContainer.Panel1.ResumeLayout(false); this.SubscriberSplitContainer.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.SubscriberSplitContainer)).EndInit(); this.SubscriberSplitContainer.ResumeLayout(false); this.SubscriberStatusGroupBox.ResumeLayout(false); this.SubscriberMessageGroupBox.ResumeLayout(false); this.ConcentratorTabPage.ResumeLayout(false); this.ConcentratorSplitContainer.Panel1.ResumeLayout(false); this.ConcentratorSplitContainer.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.ConcentratorSplitContainer)).EndInit(); this.ConcentratorSplitContainer.ResumeLayout(false); this.ConcentratorStatusGroupBox.ResumeLayout(false); this.ConcentratorMessageGroupBox.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel RootPanel; private System.Windows.Forms.TabControl StatusTabControl; private System.Windows.Forms.TabPage SubscriberTabPage; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.TabPage ConcentratorTabPage; private System.Windows.Forms.RichTextBox SubscriberStatusBox; private System.Windows.Forms.RichTextBox ConcentratorStatusBox; private System.Windows.Forms.TabPage AlgorithmTabPage; private System.Windows.Forms.RichTextBox AlgorithmMessageBox; private System.Windows.Forms.SplitContainer SubscriberSplitContainer; private System.Windows.Forms.RichTextBox SubscriberMessageBox; private System.Windows.Forms.SplitContainer ConcentratorSplitContainer; private System.Windows.Forms.GroupBox ConcentratorStatusGroupBox; private System.Windows.Forms.GroupBox ConcentratorMessageGroupBox; private System.Windows.Forms.GroupBox SubscriberStatusGroupBox; private System.Windows.Forms.GroupBox SubscriberMessageGroupBox; private System.Windows.Forms.RichTextBox ConcentratorMessageBox; } }
#region License /* * WebSocketFrame.cs * * The MIT License * * Copyright (c) 2012-2015 sta.blockhead * * 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 #region Contributors /* * Contributors: * - Chris Swiedler */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace WebSocketSharp { internal class WebSocketFrame : IEnumerable<byte> { #region Private Fields private byte[] _extPayloadLength; private Fin _fin; private Mask _mask; private byte[] _maskingKey; private Opcode _opcode; private PayloadData _payloadData; private byte _payloadLength; private Rsv _rsv1; private Rsv _rsv2; private Rsv _rsv3; #endregion #region Internal Fields internal static readonly byte[] EmptyUnmaskPingBytes; #endregion #region Static Constructor static WebSocketFrame () { EmptyUnmaskPingBytes = CreatePingFrame (false).ToByteArray (); } #endregion #region Private Constructors private WebSocketFrame () { } #endregion #region Internal Constructors internal WebSocketFrame (Opcode opcode, PayloadData payloadData, bool mask) : this (Fin.Final, opcode, payloadData, false, mask) { } internal WebSocketFrame (Fin fin, Opcode opcode, byte[] data, bool compressed, bool mask) : this (fin, opcode, new PayloadData (data), compressed, mask) { } internal WebSocketFrame ( Fin fin, Opcode opcode, PayloadData payloadData, bool compressed, bool mask) { _fin = fin; _rsv1 = isData (opcode) && compressed ? Rsv.On : Rsv.Off; _rsv2 = Rsv.Off; _rsv3 = Rsv.Off; _opcode = opcode; var len = payloadData.Length; if (len < 126) { _payloadLength = (byte) len; _extPayloadLength = WebSocket.EmptyBytes; } else if (len < 0x010000) { _payloadLength = (byte) 126; _extPayloadLength = ((ushort) len).InternalToByteArray (ByteOrder.Big); } else { _payloadLength = (byte) 127; _extPayloadLength = len.InternalToByteArray (ByteOrder.Big); } if (mask) { _mask = Mask.Mask; _maskingKey = createMaskingKey (); payloadData.Mask (_maskingKey); } else { _mask = Mask.Unmask; _maskingKey = WebSocket.EmptyBytes; } _payloadData = payloadData; } #endregion #region Public Properties public byte[] ExtendedPayloadLength { get { return _extPayloadLength; } } public int ExtendedPayloadLengthCount { get { return _payloadLength < 126 ? 0 : (_payloadLength == 126 ? 2 : 8); } } public Fin Fin { get { return _fin; } } public ulong FullPayloadLength { get { return _payloadLength < 126 ? _payloadLength : _payloadLength == 126 ? _extPayloadLength.ToUInt16 (ByteOrder.Big) : _extPayloadLength.ToUInt64 (ByteOrder.Big); } } public bool IsBinary { get { return _opcode == Opcode.Binary; } } public bool IsClose { get { return _opcode == Opcode.Close; } } public bool IsCompressed { get { return _rsv1 == Rsv.On; } } public bool IsContinuation { get { return _opcode == Opcode.Cont; } } public bool IsControl { get { return _opcode == Opcode.Close || _opcode == Opcode.Ping || _opcode == Opcode.Pong; } } public bool IsData { get { return _opcode == Opcode.Binary || _opcode == Opcode.Text; } } public bool IsFinal { get { return _fin == Fin.Final; } } public bool IsFragmented { get { return _fin == Fin.More || _opcode == Opcode.Cont; } } public bool IsMasked { get { return _mask == Mask.Mask; } } public bool IsPerMessageCompressed { get { return (_opcode == Opcode.Binary || _opcode == Opcode.Text) && _rsv1 == Rsv.On; } } public bool IsPing { get { return _opcode == Opcode.Ping; } } public bool IsPong { get { return _opcode == Opcode.Pong; } } public bool IsText { get { return _opcode == Opcode.Text; } } public ulong Length { get { return 2 + (ulong) (_extPayloadLength.Length + _maskingKey.Length) + _payloadData.Length; } } public Mask Mask { get { return _mask; } } public byte[] MaskingKey { get { return _maskingKey; } } public Opcode Opcode { get { return _opcode; } } public PayloadData PayloadData { get { return _payloadData; } } public byte PayloadLength { get { return _payloadLength; } } public Rsv Rsv1 { get { return _rsv1; } } public Rsv Rsv2 { get { return _rsv2; } } public Rsv Rsv3 { get { return _rsv3; } } #endregion #region Private Methods private static byte[] createMaskingKey () { var key = new byte[4]; WebSocket.RandomNumber.GetBytes (key); return key; } private static string dump (WebSocketFrame frame) { var len = frame.Length; var cnt = (long) (len / 4); var rem = (int) (len % 4); int cntDigit; string cntFmt; if (cnt < 10000) { cntDigit = 4; cntFmt = "{0,4}"; } else if (cnt < 0x010000) { cntDigit = 4; cntFmt = "{0,4:X}"; } else if (cnt < 0x0100000000) { cntDigit = 8; cntFmt = "{0,8:X}"; } else { cntDigit = 16; cntFmt = "{0,16:X}"; } var spFmt = String.Format ("{{0,{0}}}", cntDigit); var headerFmt = String.Format (@" {0} 01234567 89ABCDEF 01234567 89ABCDEF {0}+--------+--------+--------+--------+\n", spFmt); var lineFmt = String.Format ("{0}|{{1,8}} {{2,8}} {{3,8}} {{4,8}}|\n", cntFmt); var footerFmt = String.Format ("{0}+--------+--------+--------+--------+", spFmt); var output = new StringBuilder (64); Func<Action<string, string, string, string>> linePrinter = () => { long lineCnt = 0; return (arg1, arg2, arg3, arg4) => output.AppendFormat (lineFmt, ++lineCnt, arg1, arg2, arg3, arg4); }; var printLine = linePrinter (); output.AppendFormat (headerFmt, String.Empty); var bytes = frame.ToByteArray (); for (long i = 0; i <= cnt; i++) { var j = i * 4; if (i < cnt) { printLine ( Convert.ToString (bytes[j], 2).PadLeft (8, '0'), Convert.ToString (bytes[j + 1], 2).PadLeft (8, '0'), Convert.ToString (bytes[j + 2], 2).PadLeft (8, '0'), Convert.ToString (bytes[j + 3], 2).PadLeft (8, '0')); continue; } if (rem > 0) printLine ( Convert.ToString (bytes[j], 2).PadLeft (8, '0'), rem >= 2 ? Convert.ToString (bytes[j + 1], 2).PadLeft (8, '0') : String.Empty, rem == 3 ? Convert.ToString (bytes[j + 2], 2).PadLeft (8, '0') : String.Empty, String.Empty); } output.AppendFormat (footerFmt, String.Empty); return output.ToString (); } private static bool isControl (Opcode opcode) { return opcode == Opcode.Close || opcode == Opcode.Ping || opcode == Opcode.Pong; } private static bool isData (Opcode opcode) { return opcode == Opcode.Text || opcode == Opcode.Binary; } private static string print (WebSocketFrame frame) { /* Opcode */ var opcode = frame._opcode.ToString (); /* Payload Length */ var payloadLen = frame._payloadLength; /* Extended Payload Length */ var extPayloadLen = payloadLen < 126 ? String.Empty : payloadLen == 126 ? frame._extPayloadLength.ToUInt16 (ByteOrder.Big).ToString () : frame._extPayloadLength.ToUInt64 (ByteOrder.Big).ToString (); /* Masking Key */ var masked = frame.IsMasked; var maskingKey = masked ? BitConverter.ToString (frame._maskingKey) : String.Empty; /* Payload Data */ var payload = payloadLen == 0 ? String.Empty : payloadLen > 125 ? String.Format ("A {0} frame.", opcode.ToLower ()) : !masked && !frame.IsFragmented && !frame.IsCompressed && frame.IsText ? Encoding.UTF8.GetString (frame._payloadData.ApplicationData) : frame._payloadData.ToString (); var fmt = @" FIN: {0} RSV1: {1} RSV2: {2} RSV3: {3} Opcode: {4} MASK: {5} Payload Length: {6} Extended Payload Length: {7} Masking Key: {8} Payload Data: {9}"; return String.Format ( fmt, frame._fin, frame._rsv1, frame._rsv2, frame._rsv3, opcode, frame._mask, payloadLen, extPayloadLen, maskingKey, payload); } private static WebSocketFrame processHeader (byte[] header) { if (header.Length != 2) throw new WebSocketException ( "The header part of a frame cannot be read from the data source."); // FIN var fin = (header[0] & 0x80) == 0x80 ? Fin.Final : Fin.More; // RSV1 var rsv1 = (header[0] & 0x40) == 0x40 ? Rsv.On : Rsv.Off; // RSV2 var rsv2 = (header[0] & 0x20) == 0x20 ? Rsv.On : Rsv.Off; // RSV3 var rsv3 = (header[0] & 0x10) == 0x10 ? Rsv.On : Rsv.Off; // Opcode var opcode = (Opcode) (header[0] & 0x0f); // MASK var mask = (header[1] & 0x80) == 0x80 ? Mask.Mask : Mask.Unmask; // Payload Length var payloadLen = (byte) (header[1] & 0x7f); // Check if valid header. var err = isControl (opcode) && payloadLen > 125 ? "A control frame has payload data which is greater than the allowable max length." : isControl (opcode) && fin == Fin.More ? "A control frame is fragmented." : !isData (opcode) && rsv1 == Rsv.On ? "A non data frame is compressed." : null; if (err != null) throw new WebSocketException (CloseStatusCode.ProtocolError, err); var frame = new WebSocketFrame (); frame._fin = fin; frame._rsv1 = rsv1; frame._rsv2 = rsv2; frame._rsv3 = rsv3; frame._opcode = opcode; frame._mask = mask; frame._payloadLength = payloadLen; return frame; } private static WebSocketFrame readExtendedPayloadLength (Stream stream, WebSocketFrame frame) { var len = frame.ExtendedPayloadLengthCount; if (len == 0) { frame._extPayloadLength = WebSocket.EmptyBytes; return frame; } var bytes = stream.ReadBytes (len); if (bytes.Length != len) throw new WebSocketException ( "The 'Extended Payload Length' of a frame cannot be read from the data source."); frame._extPayloadLength = bytes; return frame; } private static void readExtendedPayloadLengthAsync ( Stream stream, WebSocketFrame frame, Action<WebSocketFrame> completed, Action<Exception> error) { var len = frame.ExtendedPayloadLengthCount; if (len == 0) { frame._extPayloadLength = WebSocket.EmptyBytes; completed (frame); return; } stream.ReadBytesAsync ( len, bytes => { if (bytes.Length != len) throw new WebSocketException ( "The 'Extended Payload Length' of a frame cannot be read from the data source."); frame._extPayloadLength = bytes; completed (frame); }, error); } private static WebSocketFrame readHeader (Stream stream) { return processHeader (stream.ReadBytes (2)); } private static void readHeaderAsync ( Stream stream, Action<WebSocketFrame> completed, Action<Exception> error) { stream.ReadBytesAsync (2, bytes => completed (processHeader (bytes)), error); } private static WebSocketFrame readMaskingKey (Stream stream, WebSocketFrame frame) { var len = frame.IsMasked ? 4 : 0; if (len == 0) { frame._maskingKey = WebSocket.EmptyBytes; return frame; } var bytes = stream.ReadBytes (len); if (bytes.Length != len) throw new WebSocketException ( "The 'Masking Key' of a frame cannot be read from the data source."); frame._maskingKey = bytes; return frame; } private static void readMaskingKeyAsync ( Stream stream, WebSocketFrame frame, Action<WebSocketFrame> completed, Action<Exception> error) { var len = frame.IsMasked ? 4 : 0; if (len == 0) { frame._maskingKey = WebSocket.EmptyBytes; completed (frame); return; } stream.ReadBytesAsync ( len, bytes => { if (bytes.Length != len) throw new WebSocketException ( "The 'Masking Key' of a frame cannot be read from the data source."); frame._maskingKey = bytes; completed (frame); }, error); } private static WebSocketFrame readPayloadData (Stream stream, WebSocketFrame frame) { var len = frame.FullPayloadLength; if (len == 0) { frame._payloadData = new PayloadData (WebSocket.EmptyBytes, frame.IsMasked); return frame; } // Check if allowable length. if (len > PayloadData.MaxLength) throw new WebSocketException ( CloseStatusCode.TooBig, "The length of 'Payload Data' of a frame is greater than the allowable max length."); var bytes = frame._payloadLength < 127 ? stream.ReadBytes ((int) len) : stream.ReadBytes ((long) len, 1024); if (bytes.LongLength != (long) len) throw new WebSocketException ( "The 'Payload Data' of a frame cannot be read from the data source."); frame._payloadData = new PayloadData (bytes, frame.IsMasked); return frame; } private static void readPayloadDataAsync ( Stream stream, WebSocketFrame frame, Action<WebSocketFrame> completed, Action<Exception> error) { var len = frame.FullPayloadLength; if (len == 0) { frame._payloadData = new PayloadData (WebSocket.EmptyBytes, frame.IsMasked); completed (frame); return; } // Check if allowable length. if (len > PayloadData.MaxLength) throw new WebSocketException ( CloseStatusCode.TooBig, "The length of 'Payload Data' of a frame is greater than the allowable max length."); Action<byte[]> compl = bytes => { if (bytes.LongLength != (long) len) throw new WebSocketException ( "The 'Payload Data' of a frame cannot be read from the data source."); frame._payloadData = new PayloadData (bytes, frame.IsMasked); completed (frame); }; if (frame._payloadLength < 127) { stream.ReadBytesAsync ((int) len, compl, error); return; } stream.ReadBytesAsync ((long) len, 1024, compl, error); } #endregion #region Internal Methods internal static WebSocketFrame CreateCloseFrame (PayloadData payloadData, bool mask) { return new WebSocketFrame (Fin.Final, Opcode.Close, payloadData, false, mask); } internal static WebSocketFrame CreatePingFrame (bool mask) { return new WebSocketFrame (Fin.Final, Opcode.Ping, new PayloadData (), false, mask); } internal static WebSocketFrame CreatePingFrame (byte[] data, bool mask) { return new WebSocketFrame (Fin.Final, Opcode.Ping, new PayloadData (data), false, mask); } internal static WebSocketFrame Read (Stream stream) { return Read (stream, true); } internal static WebSocketFrame Read (Stream stream, bool unmask) { var frame = readHeader (stream); readExtendedPayloadLength (stream, frame); readMaskingKey (stream, frame); readPayloadData (stream, frame); if (unmask) frame.Unmask (); return frame; } internal static void ReadAsync ( Stream stream, Action<WebSocketFrame> completed, Action<Exception> error) { ReadAsync (stream, true, completed, error); } internal static void ReadAsync ( Stream stream, bool unmask, Action<WebSocketFrame> completed, Action<Exception> error) { readHeaderAsync ( stream, frame => readExtendedPayloadLengthAsync ( stream, frame, frame1 => readMaskingKeyAsync ( stream, frame1, frame2 => readPayloadDataAsync ( stream, frame2, frame3 => { if (unmask) frame3.Unmask (); completed (frame3); }, error), error), error), error); } internal void Unmask () { if (_mask == Mask.Unmask) return; _mask = Mask.Unmask; _payloadData.Mask (_maskingKey); _maskingKey = WebSocket.EmptyBytes; } #endregion #region Public Methods public IEnumerator<byte> GetEnumerator () { foreach (var b in ToByteArray ()) yield return b; } public void Print (bool dumped) { Console.WriteLine (dumped ? dump (this) : print (this)); } public string PrintToString (bool dumped) { return dumped ? dump (this) : print (this); } public byte[] ToByteArray () { using (var buff = new MemoryStream ()) { var header = (int) _fin; header = (header << 1) + (int) _rsv1; header = (header << 1) + (int) _rsv2; header = (header << 1) + (int) _rsv3; header = (header << 4) + (int) _opcode; header = (header << 1) + (int) _mask; header = (header << 7) + (int) _payloadLength; buff.Write (((ushort) header).InternalToByteArray (ByteOrder.Big), 0, 2); if (_payloadLength > 125) buff.Write (_extPayloadLength, 0, _payloadLength == 126 ? 2 : 8); if (_mask == Mask.Mask) buff.Write (_maskingKey, 0, 4); if (_payloadLength > 0) { var bytes = _payloadData.ToByteArray (); if (_payloadLength < 127) buff.Write (bytes, 0, bytes.Length); else buff.WriteBytes (bytes); } buff.Close (); return buff.ToArray (); } } public override string ToString () { return BitConverter.ToString (ToByteArray ()); } #endregion #region Explicit Interface Implementations IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } #endregion } }
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.org // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Reflection; using SharpTemplate.Parsers; namespace SharpTemplate.Compilers { public class SourceCompiler : IDisposable { private readonly string _asmName; private readonly string _asmPath; private readonly Dictionary<string, object> _references; private readonly ISourceCompilerDescriptor _sourceCompilerDescriptor; /// <summary> /// Internal template to build a reference to the eventual keyFile /// </summary> const string KEY_FILE_DUMMY = @" using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyKeyFile(""{0}"")] namespace Testn {{ public class Testc {{ }} }} "; /// <summary> /// The assemblies that are not loaded yet but known (thus added through AddSearchAssembly) /// </summary> private ConcurrentDictionary<string, Assembly> _preloadedAssembly; /// <summary> /// Errors, by compilation run /// </summary> public List<List<string>> Errors { get; private set; } /// <summary> /// The full qualified path of the key file for signing. The ".snk" file /// </summary> public string Key { get; set; } public bool HasErrors { get { if (Errors.Count == 0) return false; foreach (var error in Errors) { if (error.Count > 0) return true; } return false; } } /// <summary> /// If should setup the compiler into a new AppDomain and discard it after the compilation /// </summary> public bool UseAppdomain = false; /// <summary> /// Add an assembly to the current assembly resolver /// </summary> /// <param name="asm"></param> public void AddSearchAssembly(Assembly asm) { var asmName = asm.GetName().Name; _preloadedAssembly.AddOrUpdate(asmName, asm, (a, b) => asm); } /// <summary> /// Unregister the AssemblyResolve callback /// </summary> public void Dispose() { AppDomain.CurrentDomain.AssemblyResolve -= OnAssemblyResolve; } /// <summary> /// /// </summary> /// <param name="asmName">The new name for the assembly</param> /// <param name="asmPath">The new assembly path</param> public SourceCompiler(string asmName, string asmPath) { _preloadedAssembly = new ConcurrentDictionary<string, Assembly>(); AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve; AddSearchAssembly(Assembly.GetExecutingAssembly()); Errors = new List<List<string>>(); _asmName = asmName; _asmPath = asmPath; var fullPath = Path.Combine(_asmPath, _asmName + ".dll"); if (File.Exists(fullPath)) File.Delete(fullPath); _sourceCompilerDescriptor = new SourceCompilerDescriptor(); _references = new Dictionary<string, object>(); } /// <summary> /// Add a file to compile /// </summary> /// <param name="nameSpace">Namespace for the file</param> /// <param name="name">New class name</param> /// <param name="source">Source content</param> /// <param name="reference"></param> /// <returns></returns> public string AddFile(string nameSpace, string name, string source, object reference = null) { var className = nameSpace + "." + name; if (!_references.ContainsKey(className)) { _references.Add(className, reference); return _sourceCompilerDescriptor.AddFile(nameSpace, name, source); } throw new DuplicateNameException(string.Format("Duplicate class name {0}", className)); } /// <summary> /// Add a parsed Sharp file /// </summary> /// <param name="classDefinition"></param> /// <param name="reference"></param> /// <returns></returns> public string AddFile(SharpClass classDefinition, object reference = null) { return AddFile(classDefinition.ClassNamespace, classDefinition.ClassName, classDefinition.ToString(), reference); } /// <summary> /// Load path of all assemblies loaded in the current appdomain /// </summary> public void LoadCurrentAssemblies() { AddSearchAssembly(Assembly.GetCallingAssembly()); AddAssembly(Assembly.GetCallingAssembly().Location); AddAssembly(Assembly.GetExecutingAssembly().Location); if (typeof(Microsoft.CSharp.RuntimeBinder.Binder).Name == "") { throw new NotSupportedException("Runtime binder must exist"); } var assemblies = new List<string>(); assemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Replace("file:\\", "") .Replace("file:///", "")); assemblies.AddRange(new List<string>(AppDomain.CurrentDomain.GetAssemblies(). Where((a) => !a.IsDynamic).Select((a) => { var uri = new Uri(a.CodeBase); return uri.LocalPath; }))); assemblies.Reverse(); var dict = new HashSet<string>(); for (var i = assemblies.Count - 1; i >= 0; i--) { var asmPath = Path.GetFileName(assemblies[i]); if (asmPath != null) { asmPath = asmPath.ToLowerInvariant(); if (dict.Contains(asmPath)) { assemblies.RemoveAt(i); } else { dict.Add(asmPath); } } } foreach (var toAddAsm in assemblies) { AddAssembly(toAddAsm); } } /// <summary> /// Add a single assembly path /// </summary> /// <param name="assembly"></param> public void AddAssembly(string assembly) { _sourceCompilerDescriptor.AddAssembly(assembly); } /// <summary> /// Compile all that is defined /// </summary> /// <param name="bestEffort">How many times should try to compile.</param> /// <returns>The path of the freshly created dll</returns> public string Compile(int bestEffort = 1) { if (!string.IsNullOrEmpty(Key)) { var fileContent = string.Format(KEY_FILE_DUMMY, Key.Replace("\\", "\\\\")); AddFile("Testn", "Testc", fileContent); } string resultAssemblyPath = null; AppDomain compileAppDomain = null; if (UseAppdomain) compileAppDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString()); try { Assembly ass = Assembly.GetExecutingAssembly(); string assemblyLocation = ass.Location; string assemblyCodeBase = ass.CodeBase.Replace("file:///", ""); var appDomainCompilerType = typeof(AppDomainCompiler); var sourceCompilerDescriptorType = typeof(SourceCompilerDescriptor); IAppDomainCompiler appDomainCompiler = null; ISourceCompilerDescriptor clonedSourceDescriptor = null; if (UseAppdomain) { appDomainCompiler = (IAppDomainCompiler)CreateInstance(compileAppDomain, assemblyLocation, appDomainCompilerType, assemblyCodeBase); } else { appDomainCompiler = new AppDomainCompiler(); } if (UseAppdomain) { clonedSourceDescriptor = (ISourceCompilerDescriptor)CreateInstance(compileAppDomain, assemblyLocation, sourceCompilerDescriptorType, assemblyCodeBase); } else { clonedSourceDescriptor = new SourceCompilerDescriptor(); } _sourceCompilerDescriptor.CopyTo(clonedSourceDescriptor); appDomainCompiler.Initialize(bestEffort, _asmName, _asmPath, clonedSourceDescriptor, _asmPath); resultAssemblyPath = appDomainCompiler.Compile(); if (appDomainCompiler.Errors.Count > 0) { Errors.Add(appDomainCompiler.Errors); } } catch (Exception ex) { Errors.Add(new List<string> { "Unexpected Exception", ex.ToString() }); } finally { if (UseAppdomain) AppDomain.Unload(compileAppDomain); } return resultAssemblyPath; } /// <summary> /// Create an instance of the required type using the AppDomain /// </summary> /// <param name="compileAppDomain"></param> /// <param name="assemblyLocation"></param> /// <param name="classType"></param> /// <param name="assemblyCodeBase"></param> /// <returns></returns> private static object CreateInstance(AppDomain compileAppDomain, string assemblyLocation, Type classType, string assemblyCodeBase) { object instance = null; try { instance = compileAppDomain.CreateInstanceFrom(assemblyLocation, classType.FullName).Unwrap(); } catch (Exception) { } if (instance == null) { try { instance = compileAppDomain.CreateInstanceFrom(assemblyCodeBase, classType.FullName).Unwrap(); } catch (Exception) { } } return instance; } /// <summary> /// Internal callback to facilitate assembly resolving /// </summary> /// <param name="sender"></param> /// <param name="args"></param> /// <returns></returns> private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args) { var asmName = new AssemblyName(args.Name).Name; if (_preloadedAssembly.ContainsKey(asmName)) { return _preloadedAssembly[asmName]; } return null; } } }
using System; using System.Runtime.InteropServices; using System.Diagnostics; namespace System.Management { internal static class OSHelper { public static PlatformID Platform { get { return Environment.OSVersion.Platform; } } public static bool IsUnix { get { return Platform == PlatformID.MacOSX || Platform == PlatformID.Unix; } } public static bool IsWindows { get { return !IsUnix; } } public static bool IsMacOSX { get { return IsUnix && Kernel == KernelVersion.MacOSX; } } private static KernelVersion _kernel; public static KernelVersion Kernel { get { if (_kernel == KernelVersion.Undefined) { var str = DetectUnixKernel (); switch(str) { case "Linux": _kernel = KernelVersion.Linux; break; case "FreeBSD": _kernel = KernelVersion.FreeBSD; break; case "Darwin": _kernel = KernelVersion.MacOSX; break; default: _kernel = KernelVersion.Unix; break; } } return _kernel; } } #region private static string DetectUnixKernel() [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] struct utsname { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string sysname; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string nodename; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string release; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string version; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string machine; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] public string extraJustInCase; } internal class OSInformation { public string ProductName { get; set; } public string Version { get; set; } public string BuildNumber { get; set; } public override string ToString () { return string.Format ("{0} {1} {2}", ProductName, Version, BuildNumber); } } private static OSInformation _osInfo; public static OSInformation GetComputerDescription () { if (_osInfo == null) { OSInformation info = new OSInformation (); if (OSHelper.IsUnix) { if (OSHelper.IsMacOSX) { string[] resultLines = new string[3]; int i = 0; var versionProcess = Process.Start (new ProcessStartInfo ("bash", "-c \"sw_vers\"") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true }); versionProcess.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { if (i >= resultLines.Length) return; resultLines [i] += e.Data; i++; }; versionProcess.BeginOutputReadLine (); versionProcess.WaitForExit (); info.ProductName = FixSwVersString (resultLines [0]); info.Version = FixSwVersString (resultLines [1]); info.BuildNumber = FixSwVersString (resultLines [2]); } else { info.ProductName = "UNIX"; info.Version = "Undefined Version"; /* TODO: Complete with uname */ } } else { //Get Operating system information. OperatingSystem os = Environment.OSVersion; //Get version information about the os. Version vs = os.Version; //Variable to hold our return value string operatingSystem = ""; info.ProductName = "Windows"; if (os.Platform == PlatformID.Win32Windows) { //This is a pre-NT version of Windows switch (vs.Minor) { case 0: operatingSystem = "95"; break; case 10: if (vs.Revision.ToString () == "2222A") operatingSystem = "98SE"; else operatingSystem = "98"; break; case 90: operatingSystem = "Me"; break; default: break; } } else if (os.Platform == PlatformID.Win32NT) { switch (vs.Major) { case 3: operatingSystem = "NT 3.51"; break; case 4: operatingSystem = "NT 4.0"; break; case 5: if (vs.Minor == 0) operatingSystem = "2000"; else operatingSystem = "XP"; break; case 6: if (vs.Minor == 0) operatingSystem = "Vista"; else if (vs.Minor == 1) operatingSystem = "7"; else operatingSystem = "8"; break; default: break; } } //Make sure we actually got something in our OS check //We don't want to just return " Service Pack 2" or " 32-bit" //That information is useless without the OS version. if (operatingSystem != "") { //Got something. Let's prepend "Windows" and get more info. info.Version = operatingSystem; //See if there's a service pack installed. if (os.ServicePack != "") { //Append it to the OS name. i.e. "Windows XP Service Pack 3" info.BuildNumber = os.ServicePack; } //Append the OS architecture. i.e. "Windows XP Service Pack 3 32-bit" //operatingSystem += " " + getOSArchitecture().ToString() + "-bit"; } } _osInfo = info; } return _osInfo; } private static string FixSwVersString (string s) { int index = s.IndexOf (":"); if (index != -1) s = s.Substring (index +1); return s.Trim (); } private static string DetectUnixKernel() { utsname uts = new utsname(); uname(out uts); /* Debug.WriteLine("System:"); Debug.Indent(); Debug.WriteLine(uts.sysname); Debug.WriteLine(uts.nodename); Debug.WriteLine(uts.release); Debug.WriteLine(uts.version); Debug.WriteLine(uts.machine); Debug.Unindent(); */ return uts.sysname.ToString(); } [DllImport("libc")] private static extern void uname(out utsname uname_struct); #endregion public enum KernelVersion { Undefined, Linux, FreeBSD, Unix, MacOSX } } }
using System; namespace eduLang { /// <summary> /// Summary description for MachineTrace. /// </summary> public class MachineTrace { public static string Next(LispNode N) { if(N == ActiveNode) return "<b><font color=\"red\">" + ProduceListing(N,false,false) + "</font></b>"; return ProduceListing(N,false,false); } public static string Next(LispNode N, bool IN, bool Capture) { if(N == ActiveNode) return "<b><font color=\"red\">" + ProduceListing(N,IN, Capture) + "</font></b>"; return ProduceListing(N,IN, Capture); } public static string tabPrefix; public static void reset() { tabPrefix = ""; } public static LispNode ActiveNode; public static string ProduceListing(LispNode N, bool inBlock, bool Capture) { if(N.node.Equals("real")) return N.children[0].node + "." + N.children[2].node; if(N.node.Equals("null")) return "null"; if(N.node.Equals("integer")) return N.children[0].node; if(N.node.Equals("char")) return "'" + N.children[0].node + "'"; if(N.node.Equals("string")) return "\"" + N.children[0].node.Replace("\\","\\\\") + "\""; if(N.node.Equals("lookup")) { string idx = ""; for(int k = 1; k < N.children.Length; k++) idx += "[" + Next(N.children[k]) + "]"; return "(" + Next(N.children[0]) + ")" + idx; } if(N.node.Equals(".")) { return "(" + Next(N.children[0]) + ")." + N.children[1].node; } if(N.node.Equals("return")) { return tabPrefix + "return " + Next(N.children[0]) + ";\n"; } if(N.node.Equals("delete")) { return tabPrefix + "delete " + Next(N.children[0]) + ";\n"; } if(!Capture) { if(N.node.Equals("assigneval")) return tabPrefix + Next(N.children[0]) + " = " + Next(N.children[1]) + ";\n"; if(N.node.Equals("=")) return tabPrefix + N.children[0].node + " = " + Next(N.children[1]) + ";\n"; } else { if(N.node.Equals("assigneval")) return tabPrefix + Next(N.children[0]) + " = " + Next(N.children[1]); if(N.node.Equals("=")) return tabPrefix + N.children[0].node + " = " + Next(N.children[1]); } if(N.node.Equals("null_init") || N.node.Equals("null_cond")) return ";"; if(N.node.Equals("null_incr")) return ""; if(N.node.Equals("while")) { string Cond = tabPrefix + "while(" + Next(N.children[0]) + ")\n"; string OldPre = tabPrefix; tabPrefix += "\t"; string Body = Next(N.children[1],true,false) + "\n"; tabPrefix = OldPre; return Cond + Body; } if(N.node.Equals("for")) { string PreFix = tabPrefix; tabPrefix = ""; string Init = Next(N.children[0],false,true).Trim(); string Cond = Next(N.children[1]).Trim(); string Inc = Next(N.children[2],false,true).Trim(); tabPrefix = PreFix; string Top = tabPrefix + "for(" + Init + ";" + Cond + ";" + Inc + ")\n"; tabPrefix += "\t"; string Bottom = Next(N.children[3],true,false) + "\n"; tabPrefix = PreFix; return Top + Bottom; } if(N.node.Equals("if")) { string Cond = Next(N.children[0]); string PreFix = tabPrefix; string Bottom = ""; tabPrefix += "\t"; Bottom = Next(N.children[1],true,false); if(N.children.Length == 3) { Bottom += PreFix + "else\n" + Next(N.children[2],true,false); } tabPrefix = PreFix; return tabPrefix + "if(" + Cond + ")\n" + Bottom; } if(N.node.Equals("news")) { string res = "new " + Next(N.children[0]) + "("; for(int k = 1; k < N.children.Length; k++) { if(k!=1) res += ","; res += Next(N.children[k]); } return res + ")"; } if(N.node.Equals("newa")) return "new " + Next(N.children[0]) + "[" + Next(N.children[1]) + "]"; if(!Capture) { if(N.node.Equals("decl")) return tabPrefix + Next(N.children[0]) + " " + N.children[1].node + ";\n"; if(N.node.Equals("decla")) return tabPrefix + Next(N.children[0]) + " " + N.children[1].node + " = " + Next(N.children[2]) + ";\n"; } else { if(N.node.Equals("decl")) return tabPrefix + Next(N.children[0]) + " " + N.children[1].node; if(N.node.Equals("decla")) return tabPrefix + Next(N.children[0]) + " " + N.children[1].node + " = " + Next(N.children[2]); } if(N.node.Equals("var")) return N.children[0].node; if(N.node.Equals("block")) { string PreFix = tabPrefix; string Top = tabPrefix + "{\n"; string Bottom = tabPrefix + "}\n"; tabPrefix += "\t"; string Middle = ""; if(N.children != null) { for(int k = 0; k < N.children.Length; k++) Middle += Next(N.children[k],true,false); } tabPrefix = PreFix; return Top + Middle + Bottom; } if(N.node.Equals("fun_app")) { string FunctionName = N.children[0].children[0].node; string Param = ""; for(int k = 1; k < N.children.Length; k++) { if(k!=1) Param+=","; Param += Next(N.children[k]); } if(inBlock) return tabPrefix + FunctionName + "(" + Param + ");\n"; return FunctionName + "(" + Param + ")"; } if(N.node.Equals("-")) { if(N.children.Length == 1) { return "-(" + Next(N.children[0]) + ")"; } } if(N.node.Equals("not")) { if(N.children.Length == 1) { return "not (" + Next(N.children[0]) + ")"; } } if( N.node.Equals("+") || N.node.Equals("*") || N.node.Equals("-") || N.node.Equals("/") || N.node.Equals("%") || N.node.Equals("<") || N.node.Equals("<=") || N.node.Equals(">=") || N.node.Equals(">") || N.node.Equals("or") || N.node.Equals("and") || N.node.Equals("!=") || N.node.Equals("==") || N.node.Equals("<<") || N.node.Equals(">>") ) { return "(" + Next(N.children[0]) + " " + N.node.Replace("<","&lt;").Replace(">","&gt") + " " + Next(N.children[1]) + ")"; } if(N.node.Equals("prog")) { string res = ""; foreach(LispNode LN in N.children) { tabPrefix = ""; res += Next(LN) + "\n"; } return res; } if(N.node.Equals("struct")) { if(N.children.Length != 2) throw new Exception("struct: err"); string structName = N.children[0].node; LispNode structParam = N.children[1]; string P = ""; for(int k = 0; k < structParam.children.Length/2; k++) { string Typ = Next(structParam.children[2*k]); string Nam = structParam.children[2*k+1].node; P += "\t" + Typ + " " + Nam + ";\n"; } return "struct " + structName + "\n{\n" + P+ "}"; } if(N.node.Equals("type_def")) { string Typ = N.children[0].node; for(int k = 1; k < N.children.Length; k++) Typ += "[]"; return Typ; } if(N.node.Equals("func_decl")) { //if(N.children.Length != 2) throw new Exception("func_decl: err"); LispNode DeclNode = N.children[0]; string Nam = DeclNode.children[0].node; string Typ = Next(DeclNode.children[0].children[0]); string Param = ""; if(DeclNode.children[0].children.Length == 2) { LispNode Formal = DeclNode.children[0].children[1]; for(int k = 0; k < Formal.children.Length/2; k++) { string PTyp = Next(Formal.children[2*k]); string PNam = Formal.children[2*k+1].node; if(k!=0) Param += ","; Param += PTyp + " " + PNam; } } LispNode BodyNode = N.children[1]; string Body = Typ + " " + Nam + "(" + Param + ")\n" + Next(BodyNode,true,false); //Env.CreateNewFunction(Decl, Body); // return new Value(); return Body; } if(N.node.Equals("glob_assign")) { string Typ = Next(N.children[0]); string Nme = N.children[1].node; string Exp = Next(N.children[2]); return Typ + " " + Nme + " = " + Exp + ";\n"; } if(N.node.Equals("glob_decl")) { string Typ = Next(N.children[0]); string Nme = N.children[1].node; return Typ + " " + Nme + ";\n"; } return N.str(); /* return new Value(); */ } } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using Kemel.Orm.Schema; using Kemel.Orm.NQuery.Storage.Column; using Kemel.Orm.NQuery.Storage.Function; using Kemel.Orm.Base; namespace Kemel.Orm.NQuery.Storage.Table { public class StoredTableCollection : List<StoredTable> { public new StoredTable Add(StoredTable item) { base.Add(item); return item; } public StoredTable Find(string name) { name = name.ToUpper(); foreach (StoredTable table in this) { if ((table.Compare(name))) { return table; } } return null; } public StoredTable Find(ITableDefinition tableDef) { return this.Find(tableDef.Name); } } public class StoredTable : IGetQuery { public StoredTable(ITableDefinition tableDef, StoredTypes type, Query parent) { this.objParent = parent; this.itdTableDefinition = tableDef; this.estType = type; } #region "Properties" private ITableDefinition itdTableDefinition; public ITableDefinition TableDefinition { get { return itdTableDefinition; } } private string objOwner = null; public string Owner { get { return this.objOwner; } set { this.objOwner = value; } } private string objAlias = null; public string Alias { get { return this.objAlias; } set { this.objAlias = value; } } private bool blnWithNolock = false; public bool NoLock { get { return this.blnWithNolock; } set { this.blnWithNolock = value; } } private StoredColumnCollectoin lstColumns = null; public StoredColumnCollectoin StoredColumns { get { if (this.lstColumns == null) { this.lstColumns = new StoredColumnCollectoin(); } return this.lstColumns; } } private Query objParent = null; public Query Parent { get { return this.objParent; } set { this.objParent = value; } } public string ColumnPrefix { get { if (string.IsNullOrEmpty(this.Alias)) { return this.TableDefinition.Name; } else { return this.Alias; } } } public bool HasAlias { get { return !string.IsNullOrEmpty(this.Alias); } } #endregion #region "Methods" public StoredColumn FindOrAddColumn(IColumnDefinition column) { StoredColumn col = this.FindColumn(column.Name); if ((col.Type == StoredColumn.StoredTypes.Schema)) { return this.Column((ColumnSchema)column); } else { return this.Column(column.Name); } } public StoredColumn FindColumn(string columnName) { return this.StoredColumns.Find(columnName); } //Public Function FindColumn(ByVal column As IColumnDefinition) As StoredColumn // Dim tq As StoredTable = Me.TableDefinition.GetColumn(column.Name) // If tq Is Nothing Then // Throw New OrmException(Messages.TableDoesNotExistInQuery) // End If // Return tq.FindOrAddColumn(column) //End Function public Query AllColumns() { if ((this.Type == StoredTypes.Schema)) { TableSchema tbSchema = (TableSchema)this.TableDefinition; foreach (ColumnSchema colSchema in tbSchema.Columns) { if ((!colSchema.IgnoreColumn)) { this.Column(colSchema); } } } else { this.StoredColumns.Add(StorageFactory.Column.Create("*", this, this.Parent)); } return this.Parent; } public Query Columns(params string[] columnsNames) { foreach (string column in columnsNames) { this.Column(column); } return this.Parent; } public StoredColumn Column(string columnName) { return this.StoredColumns.Add(StorageFactory.Column.Create(columnName, this, this.Parent)); } public StoredColumn Column(Schema.ColumnSchema columnSchema) { return this.StoredColumns.Add(StorageFactory.Column.Create(columnSchema, this, this.Parent)); } public StoredColumn Column(StoredFunction stFunction) { StoredColumn retColumn = StorageFactory.Column.Create(stFunction, this.Parent); return this.StoredColumns.Add(retColumn); } public StoredColumn Max(ColumnSchema column) { return this.Column(StorageFactory.SFunction.Max.Create(this.Parent).SetValue(column)); } public StoredTable WithNoLock() { this.NoLock = true; return this; } public StoredTable As(string p_alias) { this.Alias = p_alias; return this; } public StoredTable SetOwner(string owner) { this.objOwner = owner; return this; } public bool EqualsTableNameOrAlias(string tableName) { tableName = tableName.ToUpper(); if (this.EqualsTableName(tableName)) { return true; } else if (this.HasAlias) { return this.Alias.ToUpper().Equals(tableName); } else { return false; } } public bool EqualsTableName(string tableName) { tableName = tableName.ToUpper(); return this.TableDefinition.Name.ToUpper().Equals(tableName); } public Query EndTable() { return this.Parent; } #endregion public Join.StoredJoin AsJoin() { return this as Join.StoredJoin; } private StoredTypes estType; public StoredTypes Type { get { return estType; } } public enum StoredTypes { Schema, Name, SubQuery, StoredFunction } public bool Compare(string name) { if ((!string.IsNullOrEmpty(itdTableDefinition.Name))) { if ((itdTableDefinition.Name.ToUpper().Equals(name))) { return true; } } else if ((!string.IsNullOrEmpty(itdTableDefinition.Alias))) { if ((itdTableDefinition.Alias.ToUpper().Equals(name))) { return true; } } if ((!string.IsNullOrEmpty(this.Alias))) { if ((this.Alias.ToUpper().Equals(name))) { return true; } } return false; } public Query GetQuery() { return this.Parent; } public void SetQuery(Query query) { this.Parent = query; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Xml; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { internal class PSClassHelpProvider : HelpProviderWithCache { /// <summary> /// Constructor for PSClassHelpProvider. /// </summary> internal PSClassHelpProvider(HelpSystem helpSystem) : base(helpSystem) { _context = helpSystem.ExecutionContext; } /// <summary> /// Execution context of the HelpSystem. /// </summary> private readonly ExecutionContext _context; /// <summary> /// This is a hashtable to track which help files are loaded already. /// /// This will avoid one help file getting loaded again and again. /// </summary> private readonly Hashtable _helpFiles = new Hashtable(); [TraceSource("PSClassHelpProvider", "PSClassHelpProvider")] private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("PSClassHelpProvider", "PSClassHelpProvider"); #region common properties /// <summary> /// Name of the Help Provider. /// </summary> internal override string Name { get { return "Powershell Class Help Provider"; } } /// <summary> /// Supported Help Categories. /// </summary> internal override HelpCategory HelpCategory { get { return Automation.HelpCategory.Class; } } #endregion /// <summary> /// Override SearchHelp to find a class module with help matching a pattern. /// </summary> /// <param name="helpRequest">Help request.</param> /// <param name="searchOnlyContent">Not used.</param> /// <returns></returns> internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { Debug.Assert(helpRequest != null, "helpRequest cannot be null."); string target = helpRequest.Target; Collection<string> patternList = new Collection<string>(); bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target); if (decoratedSearch) { patternList.Add("*" + target + "*"); } else patternList.Add(target); foreach (string pattern in patternList) { PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards: true, _context); foreach (var helpInfo in GetHelpInfo(searcher)) { if (helpInfo != null) yield return helpInfo; } } } /// <summary> /// Override ExactMatchHelp to find the matching class module matching help request. /// </summary> /// <param name="helpRequest">Help Request for the search.</param> /// <returns>Enumerable of HelpInfo objects.</returns> internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest) { Debug.Assert(helpRequest != null, "helpRequest cannot be null."); if ((helpRequest.HelpCategory & Automation.HelpCategory.Class) == 0) { yield return null; } PSClassSearcher searcher = new PSClassSearcher(helpRequest.Target, useWildCards: false, _context); foreach (var helpInfo in GetHelpInfo(searcher)) { if (helpInfo != null) { yield return helpInfo; } } } /// <summary> /// Get the help in for the PS Class Info. /// /// </summary> /// <param name="searcher">Searcher for PS Classes.</param> /// <returns>Next HelpInfo object.</returns> private IEnumerable<HelpInfo> GetHelpInfo(PSClassSearcher searcher) { while (searcher.MoveNext()) { PSClassInfo current = ((IEnumerator<PSClassInfo>)searcher).Current; string moduleName = current.Module.Name; string moduleDir = current.Module.ModuleBase; if (!string.IsNullOrEmpty(moduleName) && !string.IsNullOrEmpty(moduleDir)) { string helpFileToFind = moduleName + "-Help.xml"; string helpFileName = null; Collection<string> searchPaths = new Collection<string>(); searchPaths.Add(moduleDir); string externalHelpFile = current.HelpFile; if (!string.IsNullOrEmpty(externalHelpFile)) { FileInfo helpFileInfo = new FileInfo(externalHelpFile); DirectoryInfo dirToSearch = helpFileInfo.Directory; if (dirToSearch.Exists) { searchPaths.Add(dirToSearch.FullName); helpFileToFind = helpFileInfo.Name; // If external help file is specified. Then use it. } } HelpInfo helpInfo = GetHelpInfoFromHelpFile(current, helpFileToFind, searchPaths, true, out helpFileName); if (helpInfo != null) { yield return helpInfo; } } } } /// <summary> /// Check whether a HelpItems node indicates that the help content is /// authored using maml schema. /// /// This covers two cases: /// a. If the help file has an extension .maml. /// b. If HelpItems node (which should be the top node of any command help file) /// has an attribute "schema" with value "maml", its content is in maml /// schema. /// </summary> /// <param name="helpFile">File name.</param> /// <param name="helpItemsNode">Nodes to check.</param> /// <returns></returns> internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode) { Debug.Assert(!string.IsNullOrEmpty(helpFile), "helpFile cannot be null."); if (helpFile.EndsWith(".maml", StringComparison.OrdinalIgnoreCase)) return true; if (helpItemsNode.Attributes == null) return false; foreach (XmlNode attribute in helpItemsNode.Attributes) { if (attribute.Name.Equals("schema", StringComparison.OrdinalIgnoreCase) && attribute.Value.Equals("maml", StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } #region private methods private HelpInfo GetHelpInfoFromHelpFile(PSClassInfo classInfo, string helpFileToFind, Collection<string> searchPaths, bool reportErrors, out string helpFile) { Dbg.Assert(classInfo != null, "Caller should verify that classInfo != null"); Dbg.Assert(helpFileToFind != null, "Caller should verify that helpFileToFind != null"); helpFile = MUIFileSearcher.LocateFile(helpFileToFind, searchPaths); if (!File.Exists(helpFile)) return null; if (!string.IsNullOrEmpty(helpFile)) { // Load the help file only once. Then use it from the cache. if (!_helpFiles.Contains(helpFile)) { LoadHelpFile(helpFile, helpFile, classInfo.Name, reportErrors); } return GetFromPSClassHelpCache(helpFile, Automation.HelpCategory.Class); } return null; } /// <summary> /// Gets the HelpInfo object corresponding to the command. /// </summary> /// <param name="helpFileIdentifier">Help file identifier (either name of PSSnapIn or simply full path to help file).</param> /// <param name="helpCategory">Help Category for search.</param> /// <returns>HelpInfo object.</returns> private HelpInfo GetFromPSClassHelpCache(string helpFileIdentifier, HelpCategory helpCategory) { Debug.Assert(!string.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier should not be null or empty."); HelpInfo result = GetCache(helpFileIdentifier); if (result != null) { MamlClassHelpInfo original = (MamlClassHelpInfo)result; result = original.Copy(helpCategory); } return result; } private void LoadHelpFile(string helpFile, string helpFileIdentifier, string commandName, bool reportErrors) { Exception e = null; try { LoadHelpFile(helpFile, helpFileIdentifier); } catch (IOException ioException) { e = ioException; } catch (System.Security.SecurityException securityException) { e = securityException; } catch (XmlException xmlException) { e = xmlException; } catch (NotSupportedException notSupportedException) { e = notSupportedException; } catch (UnauthorizedAccessException unauthorizedAccessException) { e = unauthorizedAccessException; } catch (InvalidOperationException invalidOperationException) { e = invalidOperationException; } if (e != null) s_tracer.WriteLine("Error occured in PSClassHelpProvider {0}", e.Message); if (reportErrors && (e != null)) { ReportHelpFileError(e, commandName, helpFile); } } /// <summary> /// Load help file for HelpInfo objects. The HelpInfo objects will be /// put into help cache. /// </summary> /// <remarks> /// 1. Needs to pay special attention about error handling in this function. /// Common errors include: file not found and invalid xml. None of these error /// should cause help search to stop. /// 2. a helpfile cache is used to avoid same file got loaded again and again. /// </remarks> private void LoadHelpFile(string helpFile, string helpFileIdentifier) { Dbg.Assert(!string.IsNullOrEmpty(helpFile), "HelpFile cannot be null or empty."); Dbg.Assert(!string.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier cannot be null or empty."); XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( new FileInfo(helpFile), false, /* ignore whitespace, comments, etc. */ null); /* default maxCharactersInDocument */ // Add this file into _helpFiles hashtable to prevent it to be loaded again. _helpFiles[helpFile] = 0; XmlNode helpItemsNode = null; if (doc.HasChildNodes) { for (int i = 0; i < doc.ChildNodes.Count; i++) { XmlNode node = doc.ChildNodes[i]; if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase)) { helpItemsNode = node; break; } } } if (helpItemsNode == null) { s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); return; } bool isMaml = IsMamlHelp(helpFile, helpItemsNode); using (this.HelpSystem.Trace(helpFile)) { if (helpItemsNode.HasChildNodes) { for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++) { XmlNode node = helpItemsNode.ChildNodes[i]; string nodeLocalName = node.LocalName; bool isClass = (string.Equals(nodeLocalName, "class", StringComparison.OrdinalIgnoreCase)); if (node.NodeType == XmlNodeType.Element && isClass) { MamlClassHelpInfo helpInfo = null; if (isMaml) { if (isClass) helpInfo = MamlClassHelpInfo.Load(node, HelpCategory.Class); } if (helpInfo != null) { this.HelpSystem.TraceErrors(helpInfo.Errors); AddCache(helpFileIdentifier, helpInfo); } } } } } } #endregion } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-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_5 || 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; using System.Collections.Generic; using System.Diagnostics; #if !UNITY #if XAMIOS || XAMDROID using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // XAMIOS || XAMDROID #endif // !UNITY using System.Globalization; using System.Linq; using System.Reflection; using MsgPack.Serialization.Reflection; namespace MsgPack.Serialization { internal static class ReflectionExtensions { private static readonly Type[] ExceptionConstructorWithInnerParameterTypes = { typeof( string ), typeof( Exception ) }; public static object InvokePreservingExceptionType( this ConstructorInfo source, params object[] parameters ) { try { return source.Invoke( parameters ); } catch ( TargetInvocationException ex ) { var rethrowing = HoistUpInnerException( ex ); if ( rethrowing == null ) { // ctor.Invoke threw exception, so rethrow original TIE. throw; } else { throw rethrowing; } } } public static object InvokePreservingExceptionType( this MethodInfo source, object instance, params object[] parameters ) { try { return source.Invoke( instance, parameters ); } catch ( TargetInvocationException ex ) { var rethrowing = HoistUpInnerException( ex ); if ( rethrowing == null ) { // ctor.Invoke threw exception, so rethrow original TIE. throw; } else { throw rethrowing; } } } public static T CreateInstancePreservingExceptionType<T>( Type instanceType, params object[] constructorParameters ) { return ( T )CreateInstancePreservingExceptionType( instanceType, constructorParameters ); } public static object CreateInstancePreservingExceptionType( Type type, params object[] constructorParameters ) { try { return Activator.CreateInstance( type, constructorParameters ); } catch ( TargetInvocationException ex ) { var rethrowing = HoistUpInnerException( ex ); if ( rethrowing == null ) { // ctor.Invoke threw exception, so rethrow original TIE. throw; } else { throw rethrowing; } } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "This method should swallow exception in restoring inner exception of TargetInvocationException." )] private static Exception HoistUpInnerException( TargetInvocationException targetInvocationException ) { if ( targetInvocationException.InnerException == null ) { return null; } var ctor = targetInvocationException.InnerException.GetType().GetConstructor( ExceptionConstructorWithInnerParameterTypes ); if ( ctor == null ) { return null; } try { return ctor.Invoke( new object[] { targetInvocationException.InnerException.Message, targetInvocationException } ) as Exception; } #if !UNITY || MSGPACK_UNITY_FULL catch ( Exception ex ) #else catch ( Exception ) #endif // !UNITY || MSGPACK_UNITY_FULL { #if !UNITY || MSGPACK_UNITY_FULL Debug.WriteLine( "HoistUpInnerException:" + ex ); #endif // !UNITY || MSGPACK_UNITY_FULL return null; } } public static Type GetMemberValueType( this MemberInfo source ) { if ( source == null ) { throw new ArgumentNullException( "source" ); } var asProperty = source as PropertyInfo; var asField = source as FieldInfo; if ( asProperty == null && asField == null ) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "'{0}'({1}) is not field nor property.", source, source.GetType() ) ); } return asProperty != null ? asProperty.PropertyType : asField.FieldType; } public static CollectionTraits GetCollectionTraits( this Type source ) { #if !UNITY && DEBUG Contract.Assert( !source.GetContainsGenericParameters(), "!source.GetContainsGenericParameters()" ); #endif // !UNITY /* * SPEC * If the object has single public method TEnumerator GetEnumerator() ( where TEnumerator implements IEnumerator<TItem>), * then the object is considered as the collection of TItem. * When the object is considered as the collection of TItem, TItem is KeyValuePair<TKey,TValue>, * and the object implements IDictionary<TKey,TValue>, then the object is considered as dictionary of TKey and TValue. * Else, if the object has single public method IEnumerator GetEnumerator(), then the object is considered as the collection of Object. * When it also implements IDictionary, however, it is considered dictionary of Object and Object. * Otherwise, that means it implements multiple collection interface, is following. * First, if the object implements IDictionary<MessagePackObject,MessagePackObject>, then it is considered as MPO dictionary. * Second, if the object implements IEnumerable<MPO>, then it is considered as MPO dictionary. * Third, if the object implement SINGLE IDictionary<TKey,TValue> and multiple IEnumerable<T>, then it is considered as dictionary of TKey and TValue. * Fourth, the object is considered as UNSERIALIZABLE member. This behavior similer to DataContract serialization behavor * (see http://msdn.microsoft.com/en-us/library/aa347850.aspx ). */ if ( !source.IsAssignableTo( typeof( IEnumerable ) ) ) { return CollectionTraits.NotCollection; } if ( source.IsArray ) { return new CollectionTraits( CollectionDetailedKind.Array, null, // Add() : Never used for array. null, // get_Count() : Never used for array. null, // GetEnumerator() : Never used for array. source.GetElementType() ); } var getEnumerator = source.GetMethod( "GetEnumerator", ReflectionAbstractions.EmptyTypes ); if ( getEnumerator != null && getEnumerator.ReturnType.IsAssignableTo( typeof( IEnumerator ) ) ) { // If public 'GetEnumerator' is found, it is primary collection traits. CollectionTraits result; if ( TryCreateCollectionTraitsForHasGetEnumeratorType( source, getEnumerator, out result ) ) { return result; } } Type ienumerableT = null; Type icollectionT = null; #if !NETFX_35 && !UNITY Type isetT = null; #endif // !NETFX_35 && !UNITY Type ilistT = null; Type idictionaryT = null; #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) Type ireadOnlyCollectionT = null; Type ireadOnlyListT = null; Type ireadOnlyDictionaryT = null; #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) Type ienumerable = null; Type icollection = null; Type ilist = null; Type idictionary = null; var sourceInterfaces = source.FindInterfaces( FilterCollectionType, null ); if ( source.GetIsInterface() && FilterCollectionType( source, null ) ) { var originalSourceInterfaces = sourceInterfaces.ToArray(); var concatenatedSourceInterface = new Type[ originalSourceInterfaces.Length + 1 ]; concatenatedSourceInterface[ 0 ] = source; for ( int i = 0; i < originalSourceInterfaces.Length; i++ ) { concatenatedSourceInterface[ i + 1 ] = originalSourceInterfaces[ i ]; } sourceInterfaces = concatenatedSourceInterface; } foreach ( var type in sourceInterfaces ) { CollectionTraits result; if ( TryCreateGenericCollectionTraits( source, type, out result ) ) { return result; } if ( !DetermineCollectionInterfaces( type, ref idictionaryT, #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ref ireadOnlyDictionaryT, #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ref ilistT, #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ref ireadOnlyListT, #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) #if !NETFX_35 && !UNITY ref isetT, #endif // !NETFX_35 && !UNITY ref icollectionT, #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ref ireadOnlyCollectionT, #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ref ienumerableT, ref idictionary, ref ilist, ref icollection, ref ienumerable ) ) { return CollectionTraits.Unserializable; } } if ( idictionaryT != null ) { var elementType = typeof( KeyValuePair<,> ).MakeGenericType( idictionaryT.GetGenericArguments() ); return new CollectionTraits( CollectionDetailedKind.GenericDictionary, GetAddMethod( source, idictionaryT.GetGenericArguments()[ 0 ], idictionaryT.GetGenericArguments()[ 1 ] ), GetCountGetterMethod( source, elementType ), FindInterfaceMethod( source, typeof( IEnumerable<> ).MakeGenericType( elementType ), "GetEnumerator", ReflectionAbstractions.EmptyTypes ), elementType ); } #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) if ( ireadOnlyDictionaryT != null ) { var elementType = typeof( KeyValuePair<,> ).MakeGenericType( ireadOnlyDictionaryT.GetGenericArguments() ); return new CollectionTraits( CollectionDetailedKind.GenericReadOnlyDictionary, null, GetCountGetterMethod( source, elementType ), FindInterfaceMethod( source, typeof( IEnumerable<> ).MakeGenericType( elementType ), "GetEnumerator", ReflectionAbstractions.EmptyTypes ), elementType ); } #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) if ( ienumerableT != null ) { var elementType = ienumerableT.GetGenericArguments()[ 0 ]; return new CollectionTraits( ( ilistT != null ) ? CollectionDetailedKind.GenericList #if !NETFX_35 && !UNITY : ( isetT != null ) ? CollectionDetailedKind.GenericSet #endif // !NETFX_35 && !UNITY : ( icollectionT != null ) ? CollectionDetailedKind.GenericCollection #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) : ( ireadOnlyListT != null ) ? CollectionDetailedKind.GenericReadOnlyList #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) : ( ireadOnlyCollectionT != null ) ? CollectionDetailedKind.GenericReadOnlyCollection #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) : CollectionDetailedKind.GenericEnumerable, GetAddMethod( source, elementType ), GetCountGetterMethod( source, elementType ), FindInterfaceMethod( source, ienumerableT, "GetEnumerator", ReflectionAbstractions.EmptyTypes ), elementType ); } if ( idictionary != null ) { return new CollectionTraits( CollectionDetailedKind.NonGenericDictionary, GetAddMethod( source, typeof( object ), typeof( object ) ), GetCountGetterMethod( source, typeof( object ) ), FindInterfaceMethod( source, idictionary, "GetEnumerator", ReflectionAbstractions.EmptyTypes ), typeof( object ) ); } if ( ienumerable != null ) { var addMethod = GetAddMethod( source, typeof( object ) ); if ( addMethod != null ) { return new CollectionTraits( ( ilist != null ) ? CollectionDetailedKind.NonGenericList : ( icollection != null ) ? CollectionDetailedKind.NonGenericCollection : CollectionDetailedKind.NonGenericEnumerable, addMethod, GetCountGetterMethod( source, typeof( object ) ), FindInterfaceMethod( source, ienumerable, "GetEnumerator", ReflectionAbstractions.EmptyTypes ), typeof( object ) ); } } return CollectionTraits.NotCollection; } private static bool TryCreateCollectionTraitsForHasGetEnumeratorType( Type source, MethodInfo getEnumerator, out CollectionTraits result ) { if ( source.Implements( typeof( IDictionary<,> ) ) #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) || source.Implements( typeof( IReadOnlyDictionary<,> ) ) #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ) { var ienumetaorT = getEnumerator.ReturnType.GetInterfaces() .FirstOrDefault( @interface => @interface.GetIsGenericType() && @interface.GetGenericTypeDefinition() == typeof( IEnumerator<> ) ); if ( ienumetaorT != null ) { var elementType = ienumetaorT.GetGenericArguments()[ 0 ]; { result = new CollectionTraits( #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) source.Implements( typeof( IDictionary<,> ) ) ? CollectionDetailedKind.GenericDictionary : CollectionDetailedKind.GenericReadOnlyDictionary, #else CollectionDetailedKind.GenericDictionary, #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) GetAddMethod( source, elementType.GetGenericArguments()[ 0 ], elementType.GetGenericArguments()[ 1 ] ), GetCountGetterMethod( source, elementType ), getEnumerator, elementType ); return true; } } } if ( source.IsAssignableTo( typeof( IDictionary ) ) ) { { result = new CollectionTraits( CollectionDetailedKind.NonGenericDictionary, GetAddMethod( source, typeof( object ), typeof( object ) ), GetCountGetterMethod( source, typeof( object ) ), getEnumerator, typeof( DictionaryEntry ) ); return true; } } // Block to limit variable scope { var ienumetaorT = IsIEnumeratorT( getEnumerator.ReturnType ) ? getEnumerator.ReturnType : getEnumerator.ReturnType.GetInterfaces().FirstOrDefault( IsIEnumeratorT ); if ( ienumetaorT != null ) { var elementType = ienumetaorT.GetGenericArguments()[ 0 ]; { result = new CollectionTraits( source.Implements( typeof( IList<> ) ) ? CollectionDetailedKind.GenericList #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) : source.Implements( typeof( IReadOnlyList<> ) ) ? CollectionDetailedKind.GenericReadOnlyList #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) #if !NETFX_35 && !UNITY : source.Implements( typeof( ISet<> ) ) ? CollectionDetailedKind.GenericSet #endif // !NETFX_35 && !UNITY : source.Implements( typeof( ICollection<> ) ) ? CollectionDetailedKind.GenericCollection #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) : source.Implements( typeof( IReadOnlyCollection<> ) ) ? CollectionDetailedKind.GenericReadOnlyCollection #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) : CollectionDetailedKind.GenericEnumerable, GetAddMethod( source, elementType ), GetCountGetterMethod( source, elementType ), getEnumerator, elementType ); return true; } } } result = default( CollectionTraits ); return false; } private static bool TryCreateGenericCollectionTraits( Type source, Type type, out CollectionTraits result ) { if ( type == typeof( IDictionary<MessagePackObject, MessagePackObject> ) #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) || type == typeof( IReadOnlyDictionary<MessagePackObject, MessagePackObject> ) #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ) { result = new CollectionTraits( #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ( source == typeof( IDictionary<MessagePackObject, MessagePackObject> ) || source.Implements( typeof( IDictionary<MessagePackObject, MessagePackObject> ) ) ) ? CollectionDetailedKind.GenericDictionary : CollectionDetailedKind.GenericReadOnlyDictionary, #else CollectionDetailedKind.GenericDictionary, #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) GetAddMethod( source, typeof( MessagePackObject ), typeof( MessagePackObject ) ), GetCountGetterMethod( source, typeof( KeyValuePair<MessagePackObject, MessagePackObject> ) ), FindInterfaceMethod( source, typeof( IEnumerable<KeyValuePair<MessagePackObject, MessagePackObject>> ), "GetEnumerator", ReflectionAbstractions.EmptyTypes ), typeof( KeyValuePair<MessagePackObject, MessagePackObject> ) ); return true; } if ( type == typeof( IEnumerable<MessagePackObject> ) ) { var addMethod = GetAddMethod( source, typeof( MessagePackObject ) ); if ( addMethod != null ) { { result = new CollectionTraits( ( source == typeof( IList<MessagePackObject> ) || source.Implements( typeof( IList<MessagePackObject> ) ) ) ? CollectionDetailedKind.GenericList #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) : ( source == typeof( IReadOnlyList<MessagePackObject> ) || source.Implements( typeof( IReadOnlyList<MessagePackObject> ) ) ) ? CollectionDetailedKind.GenericReadOnlyList #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) #if !NETFX_35 && !UNITY : ( source == typeof( ISet<MessagePackObject> ) || source.Implements( typeof( ISet<MessagePackObject> ) ) ) ? CollectionDetailedKind.GenericSet #endif // !NETFX_35 && !UNITY : ( source == typeof( ICollection<MessagePackObject> ) || source.Implements( typeof( ICollection<MessagePackObject> ) ) ) ? CollectionDetailedKind.GenericCollection #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) : ( source == typeof( IReadOnlyCollection<MessagePackObject> ) || source.Implements( typeof( IReadOnlyCollection<MessagePackObject> ) ) ) ? CollectionDetailedKind.GenericReadOnlyCollection #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) : CollectionDetailedKind.GenericEnumerable, addMethod, GetCountGetterMethod( source, typeof( MessagePackObject ) ), FindInterfaceMethod( source, typeof( IEnumerable<MessagePackObject> ), "GetEnumerator", ReflectionAbstractions.EmptyTypes ), typeof( MessagePackObject ) ); return true; } } } result = default( CollectionTraits ); return false; } private static bool DetermineCollectionInterfaces( Type type, ref Type idictionaryT, #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ref Type ireadOnlyDictionaryT, #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ref Type ilistT, #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ref Type ireadOnlyListT, #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) #if !NETFX_35 && !UNITY ref Type isetT, #endif // !NETFX_35 && !UNITY ref Type icollectionT, #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ref Type ireadOnlyCollectionT, #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) ref Type ienumerableT, ref Type idictionary, ref Type ilist, ref Type icollection, ref Type ienumerable ) { if ( type.GetIsGenericType() ) { var genericTypeDefinition = type.GetGenericTypeDefinition(); if ( genericTypeDefinition == typeof( IDictionary<,> ) ) { if ( idictionaryT != null ) { return false; } idictionaryT = type; } #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) else if ( genericTypeDefinition == typeof( IReadOnlyDictionary<,> ) ) { if ( ireadOnlyDictionaryT != null ) { return false; } ireadOnlyDictionaryT = type; } #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) else if ( genericTypeDefinition == typeof( IList<> ) ) { if ( ilistT != null ) { return false; } ilistT = type; } #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) else if ( genericTypeDefinition == typeof( IReadOnlyList<> ) ) { if ( ireadOnlyListT != null ) { return false; } ireadOnlyListT = type; } #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) #if !NETFX_35 && !UNITY else if ( genericTypeDefinition == typeof( ISet<> ) ) { if ( isetT != null ) { return false; } isetT = type; } #endif // !NETFX_35 && !UNITY else if ( genericTypeDefinition == typeof( ICollection<> ) ) { if ( icollectionT != null ) { return false; } icollectionT = type; } #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) else if ( genericTypeDefinition == typeof( IReadOnlyCollection<> ) ) { if ( ireadOnlyCollectionT != null ) { return false; } ireadOnlyCollectionT = type; } #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) else if ( genericTypeDefinition == typeof( IEnumerable<> ) ) { if ( ienumerableT != null ) { return false; } ienumerableT = type; } } else { if ( type == typeof( IDictionary ) ) { idictionary = type; } else if ( type == typeof( IList ) ) { ilist = type; } else if ( type == typeof( ICollection ) ) { icollection = type; } else if ( type == typeof( IEnumerable ) ) { ienumerable = type; } } return true; } private static MethodInfo FindInterfaceMethod( Type targetType, Type interfaceType, string name, Type[] parameterTypes ) { if ( targetType.GetIsInterface() ) { return targetType.FindInterfaces( ( type, _ ) => type == interfaceType, null ).Single().GetMethod( name, parameterTypes ); } var map = targetType.GetInterfaceMap( interfaceType ); #if !SILVERLIGHT || WINDOWS_PHONE int index = Array.FindIndex( map.InterfaceMethods, method => method.Name == name && method.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameterTypes ) ); #else int index = map.InterfaceMethods.FindIndex( method => method.Name == name && method.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameterTypes ) ); #endif if ( index < 0 ) { #if DEBUG && !UNITY #if !NETFX_35 Contract.Assert( false, interfaceType + "::" + name + "(" + String.Join<Type>( ", ", parameterTypes ) + ") is not found in " + targetType ); #else Contract.Assert( false, interfaceType + "::" + name + "(" + String.Join( ", ", parameterTypes.Select( t => t.ToString() ).ToArray() ) + ") is not found in " + targetType ); #endif // !NETFX_35 #endif // DEBUG && !UNITY // ReSharper disable once HeuristicUnreachableCode return null; } return map.TargetMethods[ index ]; } private static MethodInfo GetAddMethod( Type targetType, Type argumentType ) { var argumentTypes = new[] { argumentType }; var result = targetType.GetMethod( "Add", argumentTypes ); if ( result != null ) { return result; } var icollectionT = typeof( ICollection<> ).MakeGenericType( argumentType ); if ( targetType.IsAssignableTo( icollectionT ) ) { return icollectionT.GetMethod( "Add", argumentTypes ); } if ( targetType.IsAssignableTo( typeof( IList ) ) ) { return typeof( IList ).GetMethod( "Add", new[] { typeof( object ) } ); } return null; } private static MethodInfo GetCountGetterMethod( Type targetType, Type elementType ) { var result = targetType.GetProperty( "Count" ); if ( result != null && result.GetHasPublicGetter() ) { return result.GetGetMethod(); } var icollectionT = typeof( ICollection<> ).MakeGenericType( elementType ); if ( targetType.IsAssignableTo( icollectionT ) ) { return icollectionT.GetProperty( "Count" ).GetGetMethod(); } #if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) var ireadOnlyCollectionT = typeof( IReadOnlyCollection<> ).MakeGenericType( elementType ); if ( targetType.IsAssignableTo( ireadOnlyCollectionT ) ) { return ireadOnlyCollectionT.GetProperty( "Count" ).GetGetMethod(); } #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) if ( targetType.IsAssignableTo( typeof( ICollection ) ) ) { return typeof( ICollection ).GetProperty( "Count" ).GetGetMethod(); } return null; } private static MethodInfo GetAddMethod( Type targetType, Type keyType, Type valueType ) { var argumentTypes = new[] { keyType, valueType }; var result = targetType.GetMethod( "Add", argumentTypes ); if ( result != null ) { return result; } return typeof( IDictionary<,> ).MakeGenericType( argumentTypes ).GetMethod( "Add", argumentTypes ); } private static bool FilterCollectionType( Type type, object filterCriteria ) { #if !NETFX_CORE #if !UNITY Contract.Assert( type.IsInterface, "type.IsInterface" ); #endif // !UNITY return type.Assembly.Equals( typeof( Array ).Assembly ) && ( type.Namespace == "System.Collections" || type.Namespace == "System.Collections.Generic" ); #else var typeInfo = type.GetTypeInfo(); Contract.Assert( typeInfo.IsInterface ); return typeInfo.Assembly.Equals( typeof( Array ).GetTypeInfo().Assembly ) && ( type.Namespace == "System.Collections" || type.Namespace == "System.Collections.Generic" ); #endif // !NETFX_CORE } private static bool IsIEnumeratorT( Type @interface ) { return @interface.GetIsGenericType() && @interface.GetGenericTypeDefinition() == typeof( IEnumerator<> ); } #if WINDOWS_PHONE public static IEnumerable<Type> FindInterfaces( this Type source, Func<Type, object, bool> filter, object criterion ) { foreach ( var @interface in source.GetInterfaces() ) { if ( filter( @interface, criterion ) ) { yield return @interface; } } } #endif public static bool GetHasPublicGetter( this MemberInfo source ) { PropertyInfo asProperty; FieldInfo asField; if ( ( asProperty = source as PropertyInfo ) != null ) { #if !NETFX_CORE return asProperty.GetGetMethod() != null; #else return ( asProperty.GetMethod != null && asProperty.GetMethod.IsPublic ); #endif } else if ( ( asField = source as FieldInfo ) != null ) { return asField.IsPublic; } else { throw new NotSupportedException( source.GetType() + " is not supported." ); } } public static bool GetHasPublicSetter( this MemberInfo source ) { PropertyInfo asProperty; FieldInfo asField; if ( ( asProperty = source as PropertyInfo ) != null ) { #if !NETFX_CORE return asProperty.GetSetMethod() != null; #else return ( asProperty.SetMethod != null && asProperty.SetMethod.IsPublic ); #endif } else if ( ( asField = source as FieldInfo ) != null ) { return asField.IsPublic && !asField.IsInitOnly && !asField.IsLiteral; } else { throw new NotSupportedException( source.GetType() + " is not supported." ); } } public static bool GetIsPublic( this MemberInfo source ) { PropertyInfo asProperty; FieldInfo asField; MethodBase asMethod; #if !NETFX_CORE Type asType; #endif if ( ( asProperty = source as PropertyInfo ) != null ) { #if !NETFX_CORE return asProperty.GetAccessors( true ).Where( a => a.ReturnType != typeof( void ) ).All( a => a.IsPublic ); #else return ( asProperty.GetMethod == null || asProperty.GetMethod.IsPublic ); #endif } else if ( ( asField = source as FieldInfo ) != null ) { return asField.IsPublic; } else if ( ( asMethod = source as MethodBase ) != null ) { return asMethod.IsPublic; } #if !NETFX_CORE else if ( ( asType = source as Type ) != null ) { return asType.IsPublic; } #endif else { throw new NotSupportedException( source.GetType() + " is not supported." ); } } public static bool GetIsVisible( this Type source ) { #if !NETFX_CORE return source.IsVisible; #else return source.GetTypeInfo().IsVisible; #endif } } }
using System; using System.Text; using System.Collections; using System.Windows.Forms; using System.Collections.Specialized; using System.Data; using System.Drawing; using System.Data.OleDb; using System.Reflection; using C1.Win.C1Preview; using PCSComUtils.Common; using PCSUtils.Utils; namespace DetailItemPriceByPOReceipt { [Serializable] public class DetailItemPriceByPOReceipt : MarshalByRefObject, IDynamicReport { public DetailItemPriceByPOReceipt() { } #region Constants private const string TABLE_NAME = "tbl_OutsideProcessing"; private const string NAME_FLD = "Name"; private const string EXCHANGE_RATE_FLD = "ExchangeRate"; private const string PRODUCT_ID_FLD = "ProductID"; private const string PRODUCT_CODE_FLD = "Code"; private const string PRODUCT_NAME_FLD = "Description"; #endregion #region IDynamicReport Members private bool mUseReportViewerRenderEngine = false; private string mConnectionString; private ReportBuilder mReportBuilder; private C1PrintPreviewControl mReportViewer; private object mResult; /// <summary> /// ConnectionString, provide for the Dynamic Report /// ALlow Dynamic Report to access the DataBase of PCS /// </summary> public string PCSConnectionString { get { return mConnectionString; } set { mConnectionString = value; } } /// <summary> /// Report Builder Utility Object /// Dynamic Report can use this object to render, modify, layout the report /// </summary> public ReportBuilder PCSReportBuilder { get { return mReportBuilder; } set { mReportBuilder = value; } } /// <summary> /// ReportViewer Object, provide for the DynamicReport, /// allow Dynamic Report to manipulate with the REportViewer, /// modify the report after rendered if needed /// </summary> public C1PrintPreviewControl PCSReportViewer { get { return mReportViewer; } set { mReportViewer = value; } } /// <summary> /// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid /// </summary> public object Result { get { return mResult; } set { mResult = value; } } /// <summary> /// Notify PCS whether the rendering report process is run by /// this IDynamicReport or the ReportViewer Engine (in the ReportViewer form) /// </summary> public bool UseReportViewerRenderEngine { get { return mUseReportViewerRenderEngine; } set { mUseReportViewerRenderEngine = value; } } private string mstrReportDefinitionFolder = string.Empty; /// <summary> /// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path ) /// </summary> public string ReportDefinitionFolder { get { return mstrReportDefinitionFolder; } set { mstrReportDefinitionFolder = value; } } private string mstrReportLayoutFile = string.Empty; /// <summary> /// Inform External Process about the Layout file /// in which PCS instruct to use /// (PCS will assign this property while ReportViewer Form execute, /// ReportVIewer form will use the layout file in the report config entry to put in this property) /// </summary> public string ReportLayoutFile { get { return mstrReportLayoutFile; } set { mstrReportLayoutFile = value; } } #endregion #region Detailed Item Price By PO Receipt Datat: Tuan TQ /// <summary> /// Get CCN Info /// </summary> /// <param name="pstrID"></param> /// <returns></returns> private string GetHomeCurrency(string pstrCCNID) { const string HOME_CURRENCY_FLD = "HomeCurrencyID"; OleDbConnection oconPCS = null; try { string strResult = string.Empty; OleDbDataReader odrPCS = null; OleDbCommand ocmdPCS = null; string strSql = "SELECT " + HOME_CURRENCY_FLD; strSql += " FROM MST_CCN"; strSql += " WHERE CCNID = " + pstrCCNID; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); if(odrPCS != null) { if(odrPCS.Read()) { strResult = odrPCS[HOME_CURRENCY_FLD].ToString().Trim(); } } return strResult; } catch (Exception ex) { throw ex; } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); oconPCS = null; } } } DataTable GetDetailedItemPriceByPOReceiptData(string pstrCCNID, string pstrMasLocID, string pstrPOTypeID, string pstrFromDate, string pstrToDate, string pstrProductIDList, string pstrCurrencyID, string pstrExchangeRate, string pstrHomeCurrency) { DataTable dtbResult = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; //Freight exchange rate string strFreightExchangeRate = " (("; strFreightExchangeRate += "SELECT ISNULL(freight.ExchangeRate, 1) as ExchangeRate"; strFreightExchangeRate += " FROM cst_FreightMaster freight WHERE freight.FreightMasterID = cst_FreightMaster.FreightMasterID"; strFreightExchangeRate += " AND freight.ACPurposeID = " + (int)ACPurpose.Freight; strFreightExchangeRate += ")"; //PO exchange rate string strPOExchangeRate = " (("; strPOExchangeRate += "SELECT ISNULL(po.ExchangeRate, 1) as ExchangeRate"; strPOExchangeRate += " FROM PO_PurchaseOrderMaster po WHERE po.PurchaseOrderMasterID = PO_PurchaseOrderMaster.PurchaseOrderMasterID "; strPOExchangeRate += ")"; //Invoice exchange rate string strInvoiceExchangeRate = " (("; strInvoiceExchangeRate += "SELECT ISNULL(invoice.ExchangeRate, 1) as ExchangeRate"; strInvoiceExchangeRate += " FROM PO_InvoiceMaster invoice WHERE invoice.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID"; strInvoiceExchangeRate += ")"; if(pstrExchangeRate != string.Empty && pstrExchangeRate != null) { if(pstrCurrencyID != pstrHomeCurrency) { //Freight strFreightExchangeRate += @" /"; strFreightExchangeRate += pstrExchangeRate; //PO strPOExchangeRate += @" /"; strPOExchangeRate += pstrExchangeRate; //Invoice strInvoiceExchangeRate += @" /"; strInvoiceExchangeRate += pstrExchangeRate; } } else { //Exchange rate of view currency string strViewExchangeRate = string.Empty; strViewExchangeRate += " (SELECT ISNULL( (SELECT TOP 1 ISNULL(Rate, 1)"; strViewExchangeRate += " FROM MST_ExchangeRate rate"; strViewExchangeRate += " WHERE rate.Approved = 1"; strViewExchangeRate += " AND rate.CurrencyID = " + pstrCurrencyID; strViewExchangeRate += " ORDER BY BeginDate DESC), 1)"; strViewExchangeRate += " )"; //Freight strFreightExchangeRate += @" /"; strFreightExchangeRate += strViewExchangeRate; //PO strPOExchangeRate += @" /"; strPOExchangeRate += strViewExchangeRate; //Invoice strInvoiceExchangeRate += @" /"; strInvoiceExchangeRate += strViewExchangeRate; } strFreightExchangeRate += " )"; strPOExchangeRate += " )"; strInvoiceExchangeRate += " )"; StringBuilder strSqlBuilder = new StringBuilder(); strSqlBuilder.Append("SELECT DISTINCT"); strSqlBuilder.Append(" PO_PurchaseOrderReceiptMaster.PostDate,"); strSqlBuilder.Append(" PO_PurchaseOrderReceiptMaster.ReceiveNo,"); strSqlBuilder.Append(" ITM_Product.Code AS PartNo,"); strSqlBuilder.Append(" ITM_Product.Description as PartName,"); strSqlBuilder.Append(" ITM_Product.Revision as PartModel,"); strSqlBuilder.Append(" MST_UnitOfMeasure.Code as BuyingUM,"); strSqlBuilder.Append(" ITM_Category.Code as CategoryCode,"); strSqlBuilder.Append(" PO_PurchaseOrderReceiptDetail.ReceiveQuantity, "); strSqlBuilder.Append(" Case "); strSqlBuilder.Append(" When PO_PurchaseOrderReceiptMaster.InvoiceMasterID is null then "); strSqlBuilder.Append(" PO_PurchaseOrderDetail.UnitPrice * "); //Exchange rate by PO currency strSqlBuilder.Append(strPOExchangeRate); //End exchange rate strSqlBuilder.Append(" Else"); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" (PO_InvoiceDetail.CIFAmount/PO_InvoiceDetail.InvoiceQuantity) *"); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" )"); strSqlBuilder.Append(" End as UnitPrice, "); strSqlBuilder.Append(" Case "); strSqlBuilder.Append(" When PO_PurchaseOrderReceiptMaster.InvoiceMasterID is null then "); strSqlBuilder.Append(" PO_PurchaseOrderDetail.UnitPrice * "); strSqlBuilder.Append(" PO_PurchaseOrderReceiptDetail.ReceiveQuantity * "); //Exchange rate by PO currency strSqlBuilder.Append(strPOExchangeRate); //End-Exchange rate strSqlBuilder.Append(" Else "); strSqlBuilder.Append(" (PO_InvoiceDetail.CIFAmount/PO_InvoiceDetail.InvoiceQuantity) * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" * PO_PurchaseOrderReceiptDetail.ReceiveQuantity"); strSqlBuilder.Append(" End as Amount,"); strSqlBuilder.Append(" Case "); strSqlBuilder.Append(" When PO_PurchaseOrderReceiptMaster.InvoiceMasterID is null then 0"); strSqlBuilder.Append(" Else ISNULL(PO_InvoiceDetail.ImportTaxAmount, 0) * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" End as ImportTax, "); strSqlBuilder.Append(" Case"); strSqlBuilder.Append(" When PO_PurchaseOrderReceiptMaster.InvoiceMasterID is null then "); strSqlBuilder.Append(" ISNULL("); strSqlBuilder.Append(" cst_FreightDetail.Amount *"); //Exchange rate by Freight currency strSqlBuilder.Append(strFreightExchangeRate); //End-Exchange rate strSqlBuilder.Append(" , 0)"); strSqlBuilder.Append(" Else "); strSqlBuilder.Append(" ISNULL("); strSqlBuilder.Append(" cst_FreightDetail.Amount * "); //Exchange rate by Freight currency strSqlBuilder.Append(strFreightExchangeRate); //End-Exchange rate strSqlBuilder.Append(" , 0)"); strSqlBuilder.Append(" End as FreightAmount,"); strSqlBuilder.Append(" Case "); strSqlBuilder.Append(" When PO_PurchaseOrderReceiptMaster.InvoiceMasterID is null then 0"); strSqlBuilder.Append(" Else ISNULL(PO_InvoiceDetail.Inland, 0) * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" End as AdditionalCharge, "); strSqlBuilder.Append(" Case "); strSqlBuilder.Append(" When PO_PurchaseOrderReceiptMaster.InvoiceMasterID is null then "); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" PO_PurchaseOrderDetail.UnitPrice * "); //Exchange rate S by PO currency strSqlBuilder.Append(strPOExchangeRate); //End-Exchange rate strSqlBuilder.Append(" * PO_PurchaseOrderReceiptDetail.ReceiveQuantity"); strSqlBuilder.Append(" )"); strSqlBuilder.Append(" + "); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" ISNULL(cst_FreightDetail.Amount *"); //Exchange rate by Freight currency strSqlBuilder.Append(strFreightExchangeRate); //End-Exchange rate strSqlBuilder.Append(" , 0)"); strSqlBuilder.Append(" )"); strSqlBuilder.Append(" Else ("); strSqlBuilder.Append(" PO_InvoiceDetail.Inland * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" ) "); strSqlBuilder.Append(" + "); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" PO_InvoiceDetail.Inland * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" )"); strSqlBuilder.Append(" +"); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" PO_InvoiceDetail.ImportTaxAmount * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" ) "); strSqlBuilder.Append(" +"); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" (PO_InvoiceDetail.CIFAmount/PO_InvoiceDetail.InvoiceQuantity) * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" * PO_PurchaseOrderReceiptDetail.ReceiveQuantity"); strSqlBuilder.Append(" )"); strSqlBuilder.Append(" + "); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" ISNULL(cst_FreightDetail.Amount * "); //Exchange rate by Freigth currency strSqlBuilder.Append(strFreightExchangeRate); //End-Exchange rate strSqlBuilder.Append(" , 0))"); strSqlBuilder.Append(" End as TotalAmount, "); strSqlBuilder.Append(" Case "); strSqlBuilder.Append(" When PO_PurchaseOrderReceiptMaster.InvoiceMasterID is null then "); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" (PO_PurchaseOrderDetail.UnitPrice * "); //Exchange rate by PO currency strSqlBuilder.Append(strPOExchangeRate); //End-Exchange rate strSqlBuilder.Append(" * PO_PurchaseOrderReceiptDetail.ReceiveQuantity"); strSqlBuilder.Append(" * ISNULL(PO_PurchaseOrderDetail.VAT, 0) * 0.01 )"); strSqlBuilder.Append(" + "); strSqlBuilder.Append(" ISNULL(cst_FreightDetail.VATAmount * "); //Exchange rate by Freight currency strSqlBuilder.Append(strFreightExchangeRate); //End-Exchange rate strSqlBuilder.Append(" , 0)"); strSqlBuilder.Append(" ) "); strSqlBuilder.Append(" Else ("); strSqlBuilder.Append(" ISNULL(PO_InvoiceDetail.VATAmount, 0) * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" )"); strSqlBuilder.Append(" + "); strSqlBuilder.Append(" ISNULL(cst_FreightDetail.VATAmount * "); //Exchange rate by Freight currency strSqlBuilder.Append(strFreightExchangeRate); //End-Exchange rate strSqlBuilder.Append(" , 0)"); strSqlBuilder.Append(" End as VATAmount, "); strSqlBuilder.Append(" Case When PO_PurchaseOrderReceiptMaster.InvoiceMasterID is null then "); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" PO_PurchaseOrderDetail.UnitPrice * "); //Exchange rate by PO currency strSqlBuilder.Append(strPOExchangeRate); //End-Exchange rate strSqlBuilder.Append(" * PO_PurchaseOrderReceiptDetail.ReceiveQuantity"); strSqlBuilder.Append(" )"); strSqlBuilder.Append(" + "); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" ISNULL(cst_FreightDetail.Amount * "); //Exchange rate by Freight currency strSqlBuilder.Append(strFreightExchangeRate); //End-Exchange rate strSqlBuilder.Append(" , 0)"); strSqlBuilder.Append(" ) "); strSqlBuilder.Append(" +"); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" PO_PurchaseOrderDetail.UnitPrice * "); //Exchange rate by PO currency strSqlBuilder.Append(strPOExchangeRate); //End-Exchange rate strSqlBuilder.Append(" * PO_PurchaseOrderReceiptDetail.ReceiveQuantity"); strSqlBuilder.Append(" * ISNULL(PO_PurchaseOrderDetail.VAT, 0) * 0.01"); strSqlBuilder.Append(" ) "); strSqlBuilder.Append(" Else ("); strSqlBuilder.Append(" PO_InvoiceDetail.Inland * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" ) "); strSqlBuilder.Append(" +"); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" PO_InvoiceDetail.Inland * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" )"); strSqlBuilder.Append(" +"); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" PO_InvoiceDetail.ImportTaxAmount * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" ) "); strSqlBuilder.Append(" +"); strSqlBuilder.Append(" ( "); strSqlBuilder.Append(" (PO_InvoiceDetail.CIFAmount/PO_InvoiceDetail.InvoiceQuantity) * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" * PO_PurchaseOrderReceiptDetail.ReceiveQuantity"); strSqlBuilder.Append(" )"); strSqlBuilder.Append(" +"); strSqlBuilder.Append(" ( "); strSqlBuilder.Append(" ISNULL(cst_FreightDetail.Amount * "); //Exchange rate by Freight currency strSqlBuilder.Append(strFreightExchangeRate); //End-Exchange rate strSqlBuilder.Append(" , 0)"); strSqlBuilder.Append(" )"); strSqlBuilder.Append(" +"); strSqlBuilder.Append(" ("); strSqlBuilder.Append(" ISNULL(PO_InvoiceDetail.VATAmount, 0) * "); //Exchange rate by Invoice currency strSqlBuilder.Append(strInvoiceExchangeRate); //End-Exchange rate strSqlBuilder.Append(" )"); strSqlBuilder.Append(" End as PaymentAmount,"); strSqlBuilder.Append(" MST_Location.Code AS LocationCode,"); strSqlBuilder.Append(" MST_BIN.Code AS BinCode,"); strSqlBuilder.Append(" Case When PO_PurchaseOrderReceiptMaster.InvoiceMasterID is null then POCurrency.Code"); strSqlBuilder.Append(" Else InvoiceCurrency.Code"); strSqlBuilder.Append(" End as CurrencyCode"); strSqlBuilder.Append(" FROM PO_PurchaseOrderReceiptMaster"); strSqlBuilder.Append(" INNER JOIN PO_PurchaseOrderReceiptDetail ON PO_PurchaseOrderReceiptMaster.PurchaseOrderReceiptID = PO_PurchaseOrderReceiptDetail.PurchaseOrderReceiptID"); strSqlBuilder.Append(" INNER JOIN ITM_Product ON ITM_Product.ProductID = PO_PurchaseOrderReceiptDetail.ProductID"); strSqlBuilder.Append(" INNER JOIN MST_UnitOfMeasure ON PO_PurchaseOrderReceiptDetail.BuyingUMID = MST_UnitOfMeasure.UnitOfMeasureID"); strSqlBuilder.Append(" INNER JOIN MST_MasterLocation ON PO_PurchaseOrderReceiptMaster.MasterLocationID = MST_MasterLocation.MasterLocationID"); strSqlBuilder.Append(" LEFT JOIN ITM_Category ON ITM_Category.CategoryID = ITM_Product.CategoryID"); strSqlBuilder.Append(" LEFT JOIN cst_FreightMaster ON cst_FreightMaster.PurchaseOrderReceiptID = PO_PurchaseOrderReceiptMaster.PurchaseOrderReceiptID"); // 17-8-2006 dungla: only retrieve data of freight transaction strSqlBuilder.Append(" AND cst_FreightMaster.ACPurposeID = " + (int)ACPurpose.Freight); strSqlBuilder.Append(" LEFT JOIN cst_FreightDetail ON cst_FreightDetail.FreightMasterID = cst_FreightMaster.FreightMasterID"); strSqlBuilder.Append(" AND cst_FreightDetail.ProductID = PO_PurchaseOrderReceiptDetail.ProductID"); strSqlBuilder.Append(" LEFT JOIN PO_PurchaseOrderMaster POInMaster ON PO_PurchaseOrderReceiptMaster.PurchaseOrderMasterID = POInMaster.PurchaseOrderMasterID"); strSqlBuilder.Append(" LEFT JOIN MST_Location ON PO_PurchaseOrderReceiptDetail.LocationID = MST_Location.LocationID"); strSqlBuilder.Append(" LEFT JOIN MST_BIN ON MST_BIN.BinID = PO_PurchaseOrderReceiptDetail.BinID"); strSqlBuilder.Append(" LEFT JOIN PO_PurchaseOrderMaster ON PO_PurchaseOrderReceiptDetail.PurchaseOrderMasterID = PO_PurchaseOrderMaster.PurchaseOrderMasterID"); strSqlBuilder.Append(" LEFT JOIN PO_PurchaseOrderDetail ON PO_PurchaseOrderReceiptDetail.PurchaseOrderDetailID = PO_PurchaseOrderDetail.PurchaseOrderDetailID"); strSqlBuilder.Append(" LEFT JOIN PO_InvoiceMaster ON PO_PurchaseOrderReceiptMaster.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID"); strSqlBuilder.Append(" LEFT JOIN MST_Currency InvoiceCurrency ON InvoiceCurrency.CurrencyID = PO_InvoiceMaster.CurrencyID"); strSqlBuilder.Append(" LEFT JOIN MST_Currency POCurrency ON POCurrency.CurrencyID = POInMaster.CurrencyID"); strSqlBuilder.Append(" LEFT JOIN PO_InvoiceDetail ON PO_InvoiceDetail.InvoiceMasterID = PO_PurchaseOrderReceiptMaster.InvoiceMasterID"); strSqlBuilder.Append(" AND PO_InvoiceDetail.PurchaseOrderDetailID = PO_PurchaseOrderReceiptDetail.PurchaseOrderDetailID"); strSqlBuilder.Append(" WHERE PO_PurchaseOrderReceiptMaster.CCNID = " + pstrCCNID); strSqlBuilder.Append(" AND PO_PurchaseOrderReceiptMaster.MasterLocationID = " + pstrMasLocID); //From date if(pstrFromDate != string.Empty && pstrFromDate != null) { strSqlBuilder.Append(" AND PO_PurchaseOrderReceiptMaster.PostDate >= '" + pstrFromDate + "'"); } //To date if(pstrToDate != string.Empty && pstrToDate != null) { strSqlBuilder.Append(" AND PO_PurchaseOrderReceiptMaster.PostDate <= '" + pstrToDate + "'"); } //PO Type if(pstrPOTypeID != string.Empty && pstrPOTypeID != null) { strSqlBuilder.Append(" AND PO_PurchaseOrderReceiptMaster.ReceiptType = " + pstrPOTypeID); } //PO Type if(pstrProductIDList != string.Empty && pstrProductIDList != null) { strSqlBuilder.Append(" AND PO_PurchaseOrderReceiptDetail.ProductID IN (" + pstrProductIDList + ")"); } Console.WriteLine(strSqlBuilder.ToString()); oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSqlBuilder.ToString(), oconPCS); ocmdPCS.CommandTimeout = 1000; ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbResult); return dtbResult; } /// <summary> /// Get CCN Info /// </summary> /// <param name="pstrID"></param> /// <returns></returns> private string GetCompanyFullName() { const string FULL_COMPANY_NAME = "CompanyFullName"; OleDbConnection oconPCS = null; try { string strResult = string.Empty; OleDbDataReader odrPCS = null; OleDbCommand ocmdPCS = null; string strSql = "SELECT [Value]" + " FROM Sys_Param" + " WHERE [Name] = '" + FULL_COMPANY_NAME + "'"; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); if(odrPCS != null) { if(odrPCS.Read()) { strResult = odrPCS["Value"].ToString().Trim(); } } return strResult; } catch (Exception ex) { throw ex; } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); oconPCS = null; } } } /// <summary> /// Get CCN Info /// </summary> /// <param name="pstrID"></param> /// <returns></returns> private string GetCCNInfoByID(string pstrID) { string strResult = string.Empty; OleDbConnection oconPCS = null; try { OleDbDataReader odrPCS = null; OleDbCommand ocmdPCS = null; string strSql = "SELECT " + PRODUCT_CODE_FLD + ", " + PRODUCT_NAME_FLD + " FROM MST_CCN" + " WHERE MST_CCN.CCNID = " + pstrID; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); if(odrPCS != null) { if(odrPCS.Read()) { strResult = odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + " (" + odrPCS[PRODUCT_NAME_FLD].ToString().Trim() + ")"; } } return strResult; } catch (Exception ex) { throw ex; } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); oconPCS = null; } } } /// <summary> /// Get PO Receipt Info /// </summary> /// <param name="pstrID"></param> /// <returns></returns> private string GetPOReceiptType(string pstrID) { string strResult = string.Empty; OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; try { OleDbCommand ocmdPCS = null; string strSql = "SELECT Description as " + PRODUCT_NAME_FLD; strSql += " FROM enm_POReceiptType"; strSql += " WHERE POReceiptTypeCode = " + pstrID; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); if(odrPCS != null) { if(odrPCS.Read()) { strResult = odrPCS[PRODUCT_NAME_FLD].ToString().Trim(); } } return strResult; } catch (Exception ex) { throw ex; } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); oconPCS = null; } } } /// <summary> /// Get Location Info /// </summary> /// <param name="pstrID"></param> /// <returns></returns> private string GetProductInfo(string pstrIDList) { const string SEMI_COLON = "; "; string strResult = string.Empty; OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; try { OleDbCommand ocmdPCS = null; string strSql = "SELECT Code, Description"; strSql += " FROM ITM_Product"; strSql += " WHERE ProductID IN (" + pstrIDList + ")"; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); if(odrPCS != null) { while(odrPCS.Read()) { strResult += odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + SEMI_COLON; } } if(strResult.Length > 250) { int i = strResult.IndexOf(SEMI_COLON, 250); if(i > 0) { strResult = strResult.Substring(0, i + SEMI_COLON.Length) + "..."; } } return strResult; } catch (Exception ex) { throw ex; } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); oconPCS = null; } } } /// <summary> /// Get Location Info /// </summary> /// <param name="pstrID"></param> /// <returns></returns> private string GetMasterLocationInfoByID(string pstrID) { string strResult = string.Empty; OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; try { OleDbCommand ocmdPCS = null; string strSql = "SELECT " + PRODUCT_CODE_FLD + ", " + NAME_FLD + " FROM MST_MasterLocation" + " WHERE MasterLocationID = " + pstrID; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); if(odrPCS != null) { if(odrPCS.Read()) { strResult = odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + " (" + odrPCS[NAME_FLD].ToString().Trim() + ")"; } } return strResult; } catch (Exception ex) { throw ex; } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); oconPCS = null; } } } /// <summary> /// Get Location Info /// </summary> /// <param name="pstrID"></param> /// <returns></returns> private Hashtable GetCurrencyInfo(string pstrID) { OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; try { OleDbCommand ocmdPCS = null; string strSql = "SELECT ISNULL(rate.Rate, 1) as " + EXCHANGE_RATE_FLD; strSql += " , currency.Code"; strSql += " FROM MST_Currency currency"; strSql += " LEFT JOIN MST_ExchangeRate rate ON rate.CurrencyID = currency.CurrencyID AND rate.Approved = 1"; strSql += " WHERE currency.CurrencyID = " + pstrID; strSql += " ORDER BY rate.BeginDate DESC"; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); Hashtable htbResult = new Hashtable(); if(odrPCS != null) { if(odrPCS.Read()) { htbResult.Add(PRODUCT_CODE_FLD, odrPCS[PRODUCT_CODE_FLD]); htbResult.Add(EXCHANGE_RATE_FLD, odrPCS[EXCHANGE_RATE_FLD]); } } return htbResult; } catch (Exception ex) { throw ex; } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); oconPCS = null; } } } #endregion Delivery To Customer Schedule Report: Tuan TQ #region Public Method public object Invoke(string pstrMethod, object[] pobjParameters) { return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters); } /// <summary> /// Build and show Detai lItem Price By PO Receipt /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <author> Tuan TQ, 11 Apr, 2006</author> public DataTable ExecuteReport(string pstrCCNID, string pstrMasLocID, string pstrCurrencyID, string pstrExchangeRate, string pstrFromDate, string pstrToDate, string pstrProductIDList ) { try { string strPOTypeID = Convert.ToString((int)PCSComUtils.Common.POReceiptTypeEnum.ByInvoice); const string DATE_HOUR_FORMAT = "dd-MM-yyyy HH:mm"; const string NUMERIC_FORMAT = "#,##0.00"; const string REPORT_TEMPLATE = "DetailItemPriceByPOReceipt.xml"; const string RPT_PAGE_HEADER = "PageHeader"; const string REPORT_NAME = "ItemPriceByPOReceipt"; const string RPT_TITLE_FLD = "fldTitle"; const string RPT_COMPANY_FLD = "fldCompany"; const string RPT_CCN_FLD = "CCN"; const string RPT_MASTER_LOCATION_FLD = "Master Location"; const string RPT_FROM_DATE_FLD = "From Date"; const string RPT_TO_DATE_FLD = "To Date"; const string RPT_PO_TYPE_FLD = "PO Type"; const string RPT_PART_NUMBER_FLD = "Part Number"; const string RPT_CURRENCY_FLD = "Currency"; const string RPT_EXCHANGE_RATE_FLD = "Exchange Rate"; DataTable dtbDataSource = null; string strHomeCurrency = GetHomeCurrency(pstrCCNID); dtbDataSource = GetDetailedItemPriceByPOReceiptData(pstrCCNID, pstrMasLocID, strPOTypeID, pstrFromDate, pstrToDate, pstrProductIDList, pstrCurrencyID, pstrExchangeRate, strHomeCurrency); //Create builder object ReportWithSubReportBuilder reportBuilder = new ReportWithSubReportBuilder(); //Set report name reportBuilder.ReportName = REPORT_NAME; //Set Datasource reportBuilder.SourceDataTable = dtbDataSource; //Set report layout location reportBuilder.ReportDefinitionFolder = mstrReportDefinitionFolder; reportBuilder.ReportLayoutFile = REPORT_TEMPLATE; reportBuilder.UseLayoutFile = true; reportBuilder.MakeDataTableForRender(); // and show it in preview dialog PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog printPreview = new PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog(); //Attach report viewer reportBuilder.ReportViewer = printPreview.ReportViewer; reportBuilder.RenderReport(); reportBuilder.DrawPredefinedField(RPT_COMPANY_FLD, GetCompanyFullName()); //Draw parameters System.Collections.Specialized.NameValueCollection arrParamAndValue = new System.Collections.Specialized.NameValueCollection(); arrParamAndValue.Add(RPT_CCN_FLD, GetCCNInfoByID(pstrCCNID)); arrParamAndValue.Add(RPT_MASTER_LOCATION_FLD, GetMasterLocationInfoByID(pstrMasLocID)); Hashtable htbCurrency = GetCurrencyInfo(pstrCurrencyID); if(htbCurrency != null) { arrParamAndValue.Add(RPT_CURRENCY_FLD, htbCurrency[PRODUCT_CODE_FLD].ToString()); if(strHomeCurrency == pstrCurrencyID) { arrParamAndValue.Add(RPT_EXCHANGE_RATE_FLD, decimal.One.ToString(NUMERIC_FORMAT)); } else { if(pstrExchangeRate != string.Empty && pstrExchangeRate != null) { arrParamAndValue.Add(RPT_EXCHANGE_RATE_FLD, decimal.Parse(pstrExchangeRate).ToString(NUMERIC_FORMAT)); } else { arrParamAndValue.Add(RPT_EXCHANGE_RATE_FLD, decimal.Parse(htbCurrency[EXCHANGE_RATE_FLD].ToString()).ToString(NUMERIC_FORMAT)); } } } /* if(strPOTypeID != null && strPOTypeID != string.Empty) { arrParamAndValue.Add(RPT_PO_TYPE_FLD, GetPOReceiptType(strPOTypeID)); } */ if(pstrFromDate != null && pstrFromDate != string.Empty) { arrParamAndValue.Add(RPT_FROM_DATE_FLD, DateTime.Parse(pstrFromDate).ToString(DATE_HOUR_FORMAT)); } if(pstrToDate != null && pstrToDate != string.Empty) { arrParamAndValue.Add(RPT_TO_DATE_FLD, DateTime.Parse(pstrToDate).ToString(DATE_HOUR_FORMAT)); } if(pstrProductIDList != null && pstrProductIDList != string.Empty) { arrParamAndValue.Add(RPT_PART_NUMBER_FLD, GetProductInfo(pstrProductIDList)); } //Anchor the Parameter drawing canvas cordinate to the fldTitle C1.C1Report.Field fldTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD); double dblStartX = fldTitle.Left; double dblStartY = fldTitle.Top + 1.3 * fldTitle.RenderHeight; reportBuilder.GetSectionByName(RPT_PAGE_HEADER).CanGrow = true; reportBuilder.DrawParameters(reportBuilder.GetSectionByName(RPT_PAGE_HEADER), dblStartX, dblStartY, arrParamAndValue, reportBuilder.Report.Font.Size); try { printPreview.FormTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD).Text; } catch {} reportBuilder.RefreshReport(); printPreview.Show(); //return table return dtbDataSource; } catch (Exception ex) { throw ex; } } #endregion Public Method } }
using AllReady.Areas.Admin.Features.Events; using AllReady.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AllReady.Areas.Admin.ViewModels.Event; using Xunit; namespace AllReady.UnitTest.Areas.Admin.Features.Events { public class DuplicateEventCommandHandlerShould : InMemoryContextTest { private const int EventToDuplicateId = 1; [Fact] public async Task CreateANewEventEntity() { var eventId = await DuplicateEvent(new DuplicateEventViewModel { Id = EventToDuplicateId }); var sut = await GetEvent(eventId); Assert.Equal(2, sut.Id); } [Fact] public async Task CopyEventPropertyValuesToTheNewEvent() { var duplicateEventModel = new DuplicateEventViewModel { Id = EventToDuplicateId, Name = "Name", Description = "Description", StartDateTime = new DateTimeOffset(2016, 1, 1, 0, 0, 0, new TimeSpan()), EndDateTime = new DateTimeOffset(2016, 1, 31, 0, 0, 0, new TimeSpan()) }; var eventId = await DuplicateEvent(duplicateEventModel); var sut = await GetEvent(eventId); Assert.Equal(1, sut.CampaignId); Assert.Equal(1, sut.Campaign.Id); Assert.Equal("Name", sut.Name); Assert.Equal("Description", sut.Description); Assert.Equal(EventType.Itinerary, sut.EventType); Assert.Equal(new DateTimeOffset(2016, 1, 1, 0, 0, 0, new TimeSpan()), sut.StartDateTime); Assert.Equal(new DateTimeOffset(2016, 1, 31, 0, 0, 0, new TimeSpan()), sut.EndDateTime); Assert.Equal("Organizer", sut.Organizer.Id); Assert.Equal("ImageUrl", sut.ImageUrl); Assert.False(sut.IsLimitVolunteers); Assert.True(sut.IsAllowWaitList); } [Fact] public async Task CreateANewLocationEntity() { var eventId = await DuplicateEvent(new DuplicateEventViewModel { Id = EventToDuplicateId }); var sut = await GetEvent(eventId); Assert.Equal(2, sut.Location.Id); } [Fact] public async Task CopyLocationPropertyValuesToTheNewLocation() { var eventId = await DuplicateEvent(new DuplicateEventViewModel { Id = EventToDuplicateId }); var @event = await GetEvent(eventId); var sut = @event.Location; Assert.Equal("Address1", sut.Address1); Assert.Equal("Address2", sut.Address2); Assert.Equal("City", sut.City); Assert.Equal("State", sut.State); Assert.Equal("PostalCode", sut.PostalCode); Assert.Equal("Name", sut.Name); Assert.Equal("PhoneNumber", sut.PhoneNumber); Assert.Equal("Country", sut.Country); } [Fact] public async Task CreateNewTaskEntities() { var eventId = await DuplicateEvent(new DuplicateEventViewModel { Id = EventToDuplicateId }); var @event = await GetEvent(eventId); var sut = @event.VolunteerTasks.OrderBy(t => t.Id).ToList(); Assert.Equal(2, sut.Count()); Assert.Equal(3, sut[0].Id); Assert.Equal(4, sut[1].Id); } [Fact] public async Task MaintainOffsetBetweenTaskStartTimeAndEventStartTimeInNewTask() { var duplicateEventModel = new DuplicateEventViewModel { Id = EventToDuplicateId, Name = "Name", Description = "Description", StartDateTime = new DateTimeOffset(2016, 2, 1, 0, 0, 0, new TimeSpan()), EndDateTime = new DateTimeOffset(2016, 2, 28, 0, 0, 0, new TimeSpan()) }; var eventId = await DuplicateEvent(duplicateEventModel); var @event = await GetEvent(eventId); var sut = @event.VolunteerTasks.OrderBy(t => t.StartDateTime).ToList(); Assert.Equal(new DateTimeOffset(2016, 2, 1, 9, 0, 0, new TimeSpan()), sut[0].StartDateTime); Assert.Equal(new DateTimeOffset(2016, 2, 2, 10, 0, 0, new TimeSpan()), sut[1].StartDateTime); } [Fact] public async Task MaintainTaskDurationInNewTask() { var duplicateEventModel = new DuplicateEventViewModel { Id = EventToDuplicateId, Name = "Name", Description = "Description", StartDateTime = new DateTimeOffset(2016, 2, 1, 0, 0, 0, new TimeSpan()), EndDateTime = new DateTimeOffset(2016, 2, 28, 0, 0, 0, new TimeSpan()) }; var eventId = await DuplicateEvent(duplicateEventModel); var @event = await GetEvent(eventId); var sut = @event.VolunteerTasks.OrderBy(t => t.StartDateTime).ToList(); Assert.Equal(new TimeSpan(8, 0, 0), sut[0].EndDateTime - sut[0].StartDateTime); Assert.Equal(new TimeSpan(6, 0, 0), sut[1].EndDateTime - sut[1].StartDateTime); } [Fact] public async Task CreateNewTasksWithoutCopyingAssignedVolunteers() { var duplicateEventModel = new DuplicateEventViewModel { Id = EventToDuplicateId, Name = "Name", Description = "Description", StartDateTime = new DateTimeOffset(2016, 2, 1, 0, 0, 0, new TimeSpan()), EndDateTime = new DateTimeOffset(2016, 2, 28, 0, 0, 0, new TimeSpan()) }; var eventId = await DuplicateEvent(duplicateEventModel); var @event = await GetEvent(eventId); var sut = @event.VolunteerTasks.OrderBy(t => t.StartDateTime).ToList(); Assert.Empty(sut[0].AssignedVolunteers); Assert.Empty(sut[1].AssignedVolunteers); } [Fact] public async Task CreateNewTasksWithTheSameRequiredSkills() { var eventId = await DuplicateEvent(new DuplicateEventViewModel { Id = EventToDuplicateId }); var @event = await GetEvent(eventId); var sut = @event.VolunteerTasks.OrderBy(t => t.StartDateTime).ToList(); Assert.Equal(2, sut[0].RequiredSkills.Count()); Assert.Equal("Skill One", sut[0].RequiredSkills.OrderBy(ts => ts.Skill.Name).ToList()[0].Skill.Name); Assert.Equal("Skill Two", sut[0].RequiredSkills.OrderBy(ts => ts.Skill.Name).ToList()[1].Skill.Name); Assert.Empty(sut[1].RequiredSkills); } [Fact] public async Task CreateNewEventWithTheSameRequiredSkills() { var eventId = await DuplicateEvent(new DuplicateEventViewModel { Id = EventToDuplicateId }); var @event = await GetEvent(eventId); var sut = @event.RequiredSkills.OrderBy(es => es.Skill.Name).ToList(); Assert.Equal(2, sut.Count()); Assert.Equal("Skill One", sut[0].Skill.Name); Assert.Equal("Skill Two", sut[1].Skill.Name); } async Task<Event> GetEvent(int eventId) { return await Context.Events .AsNoTracking() .Include(e => e.Campaign) .Include(e => e.Location) .Include(e => e.VolunteerTasks).ThenInclude(t => t.RequiredSkills).ThenInclude(ts => ts.Skill) .Include(e => e.Organizer) .Include(e => e.RequiredSkills).ThenInclude(es => es.Skill) .SingleAsync(e => e.Id == eventId); } async Task<int> DuplicateEvent(DuplicateEventViewModel duplicateEventModel) { var command = new DuplicateEventCommand { DuplicateEventModel = duplicateEventModel }; var handler = new DuplicateEventCommandHandler(Context); return await handler.Handle(command); } protected override void LoadTestData() { var skillOne = new Skill { Name = "Skill One" }; var skillTwo = new Skill { Name = "Skill Two" }; Context.AddRange(skillOne, skillTwo); var @event = new Event { Campaign = new Campaign(), Name = "Name", Description = "Description", EventType = EventType.Itinerary, StartDateTime = new DateTimeOffset(2016, 1, 1, 0, 0, 0, new TimeSpan()), EndDateTime = new DateTimeOffset(2016, 1, 31, 0, 0, 0, new TimeSpan()), Location = new Location { Address1 = "Address1", Address2 = "Address2", City = "City", State = "State", PostalCode = "PostalCode", Name = "Name", PhoneNumber = "PhoneNumber", Country = "Country" }, VolunteerTasks = new List<VolunteerTask> { new VolunteerTask { StartDateTime = new DateTimeOffset(2016, 1, 1, 9, 0, 0, new TimeSpan()), EndDateTime = new DateTimeOffset(2016, 1, 1, 17, 0, 0, new TimeSpan()), AssignedVolunteers = new List<VolunteerTaskSignup> { new VolunteerTaskSignup(), new VolunteerTaskSignup() }, RequiredSkills = new List<VolunteerTaskSkill> { new VolunteerTaskSkill { Skill = skillOne }, new VolunteerTaskSkill { Skill = skillTwo }, }, }, new VolunteerTask { StartDateTime = new DateTimeOffset(2016, 1, 2, 10, 0, 0, new TimeSpan()), EndDateTime = new DateTimeOffset(2016, 1, 2, 16, 0, 0, new TimeSpan()), AssignedVolunteers = new List<VolunteerTaskSignup> { new VolunteerTaskSignup(), new VolunteerTaskSignup() } }, }, Organizer = new ApplicationUser { Id = "Organizer" }, ImageUrl = "ImageUrl", RequiredSkills = new List<EventSkill> { new EventSkill { Skill = skillOne }, new EventSkill { Skill = skillTwo }, }, IsLimitVolunteers = false, IsAllowWaitList = true }; Context.Add(@event.Campaign); Context.Add(@event.Location); Context.Add(@event.Organizer); Context.Add(@event); Context.SaveChanges(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; namespace MonoGame.Extended.BitmapFonts { public class BitmapFont { private readonly Dictionary<int, BitmapFontRegion> _characterMap = new Dictionary<int, BitmapFontRegion>(); public BitmapFont(string name, IEnumerable<BitmapFontRegion> regions, int lineHeight) { foreach (var region in regions) _characterMap.Add(region.Character, region); Name = name; LineHeight = lineHeight; } public string Name { get; } public int LineHeight { get; } public int LetterSpacing { get; set; } = 0; public static bool UseKernings { get; set; } = true; public BitmapFontRegion GetCharacterRegion(int character) { BitmapFontRegion region; return _characterMap.TryGetValue(character, out region) ? region : null; } public Size2 MeasureString(string text) { if (string.IsNullOrEmpty(text)) return Size2.Empty; var stringRectangle = GetStringRectangle(text); return new Size2(stringRectangle.Width, stringRectangle.Height); } public Size2 MeasureString(StringBuilder text) { if (text == null || text.Length == 0) return Size2.Empty; var stringRectangle = GetStringRectangle(text); return new Size2(stringRectangle.Width, stringRectangle.Height); } public RectangleF GetStringRectangle(string text, Point2? position = null) { var position1 = position ?? new Point2(); var glyphs = GetGlyphs(text, position1); var rectangle = new RectangleF(position1.X, position1.Y, 0, LineHeight); foreach (var glyph in glyphs) { if (glyph.FontRegion != null) { var right = glyph.Position.X + glyph.FontRegion.Width; if (right > rectangle.Right) rectangle.Width = (int)(right - rectangle.Left); } if (glyph.Character == '\n') rectangle.Height += LineHeight; } return rectangle; } public RectangleF GetStringRectangle(StringBuilder text, Point2? position = null) { var position1 = position ?? new Point2(); var glyphs = GetGlyphs(text, position1); var rectangle = new RectangleF(position1.X, position1.Y, 0, LineHeight); foreach (var glyph in glyphs) { if (glyph.FontRegion != null) { var right = glyph.Position.X + glyph.FontRegion.Width; if (right > rectangle.Right) rectangle.Width = (int)(right - rectangle.Left); } if (glyph.Character == '\n') rectangle.Height += LineHeight; } return rectangle; } public StringGlyphEnumerable GetGlyphs(string text, Point2? position = null) { return new StringGlyphEnumerable(this, text, position); } public StringBuilderGlyphEnumerable GetGlyphs(StringBuilder text, Point2? position) { return new StringBuilderGlyphEnumerable(this, text, position); } public override string ToString() { return $"{Name}"; } public struct StringGlyphEnumerable : IEnumerable<BitmapFontGlyph> { private readonly StringGlyphEnumerator _enumerator; public StringGlyphEnumerable(BitmapFont font, string text, Point2? position) { _enumerator = new StringGlyphEnumerator(font, text, position); } public StringGlyphEnumerator GetEnumerator() { return _enumerator; } IEnumerator<BitmapFontGlyph> IEnumerable<BitmapFontGlyph>.GetEnumerator() { return _enumerator; } IEnumerator IEnumerable.GetEnumerator() { return _enumerator; } } public struct StringGlyphEnumerator : IEnumerator<BitmapFontGlyph> { private readonly BitmapFont _font; private readonly string _text; private int _index; private readonly Point2 _position; private Vector2 _positionDelta; private BitmapFontGlyph _currentGlyph; private BitmapFontGlyph? _previousGlyph; object IEnumerator.Current { get { // casting a struct to object will box it, behaviour we want to avoid... throw new InvalidOperationException(); } } public BitmapFontGlyph Current => _currentGlyph; public StringGlyphEnumerator(BitmapFont font, string text, Point2? position) { _font = font; _text = text; _index = -1; _position = position ?? new Point2(); _positionDelta = new Vector2(); _currentGlyph = new BitmapFontGlyph(); _previousGlyph = null; } public bool MoveNext() { if (++_index >= _text.Length) return false; var character = GetUnicodeCodePoint(_text, ref _index); _currentGlyph.Character = character; _currentGlyph.FontRegion = _font.GetCharacterRegion(character); _currentGlyph.Position = _position + _positionDelta; if (_currentGlyph.FontRegion != null) { _currentGlyph.Position.X += _currentGlyph.FontRegion.XOffset; _currentGlyph.Position.Y += _currentGlyph.FontRegion.YOffset; _positionDelta.X += _currentGlyph.FontRegion.XAdvance + _font.LetterSpacing; } if (UseKernings && _previousGlyph.HasValue && _previousGlyph.Value.FontRegion != null) { int amount; if (_previousGlyph.Value.FontRegion.Kernings.TryGetValue(character, out amount)) _positionDelta.X += amount; } _previousGlyph = _currentGlyph; if (character != '\n') return true; _positionDelta.Y += _font.LineHeight; _positionDelta.X = 0; _previousGlyph = null; return true; } private static int GetUnicodeCodePoint(string text, ref int index) { return char.IsHighSurrogate(text[index]) && ++index < text.Length ? char.ConvertToUtf32(text[index - 1], text[index]) : text[index]; } public void Dispose() { } public void Reset() { _positionDelta = new Point2(); _index = -1; _previousGlyph = null; } } public struct StringBuilderGlyphEnumerable : IEnumerable<BitmapFontGlyph> { private readonly StringBuilderGlyphEnumerator _enumerator; public StringBuilderGlyphEnumerable(BitmapFont font, StringBuilder text, Point2? position) { _enumerator = new StringBuilderGlyphEnumerator(font, text, position); } public StringBuilderGlyphEnumerator GetEnumerator() { return _enumerator; } IEnumerator<BitmapFontGlyph> IEnumerable<BitmapFontGlyph>.GetEnumerator() { return _enumerator; } IEnumerator IEnumerable.GetEnumerator() { return _enumerator; } } public struct StringBuilderGlyphEnumerator : IEnumerator<BitmapFontGlyph> { private readonly BitmapFont _font; private readonly StringBuilder _text; private int _index; private Point2 _position; private Vector2 _positionDelta; private BitmapFontGlyph _currentGlyph; private BitmapFontGlyph? _previousGlyph; object IEnumerator.Current { get { // casting a struct to object will box it, behaviour we want to avoid... throw new InvalidOperationException(); } } public BitmapFontGlyph Current => _currentGlyph; public StringBuilderGlyphEnumerator(BitmapFont font, StringBuilder text, Point2? position) { _font = font; _text = text; _index = -1; _position = position ?? new Point2(); _positionDelta = new Vector2(); _currentGlyph = new BitmapFontGlyph(); _previousGlyph = null; } public bool MoveNext() { if (++_index >= _text.Length) return false; var character = GetUnicodeCodePoint(_text, ref _index); _currentGlyph = new BitmapFontGlyph { Character = character, FontRegion = _font.GetCharacterRegion(character), Position = _position + _positionDelta }; if (_currentGlyph.FontRegion != null) { _currentGlyph.Position.X += _currentGlyph.FontRegion.XOffset; _currentGlyph.Position.Y += _currentGlyph.FontRegion.YOffset; _positionDelta.X += _currentGlyph.FontRegion.XAdvance + _font.LetterSpacing; } if (UseKernings && _previousGlyph.HasValue && _previousGlyph.Value.FontRegion != null) { int amount; if (_previousGlyph.Value.FontRegion.Kernings.TryGetValue(character, out amount)) _positionDelta.X += amount; } _previousGlyph = _currentGlyph; if (character != '\n') return true; _positionDelta.Y += _font.LineHeight; _positionDelta.X = _position.X; _previousGlyph = null; return true; } private static int GetUnicodeCodePoint(StringBuilder text, ref int index) { return char.IsHighSurrogate(text[index]) && ++index < text.Length ? char.ConvertToUtf32(text[index - 1], text[index]) : text[index]; } public void Dispose() { } public void Reset() { _positionDelta = new Point2(); _index = -1; _previousGlyph = null; } } } public struct BitmapFontGlyph { public int Character; public Vector2 Position; public BitmapFontRegion FontRegion; } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: [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 = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// BulkEnvelope /// </summary> [DataContract] public partial class BulkEnvelope : IEquatable<BulkEnvelope>, IValidatableObject { public BulkEnvelope() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="BulkEnvelope" /> class. /// </summary> /// <param name="BulkRecipientRow">Reserved: TBD.</param> /// <param name="BulkStatus">Indicates the status of the bulk send operation. Returned values can be: * queued * processing * sent * failed.</param> /// <param name="Email">Email.</param> /// <param name="EnvelopeId">The envelope ID of the envelope status that failed to post..</param> /// <param name="EnvelopeUri">Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes..</param> /// <param name="ErrorDetails">ErrorDetails.</param> /// <param name="Name">Name.</param> /// <param name="SubmittedDateTime">SubmittedDateTime.</param> /// <param name="TransactionId"> Used to identify an envelope. The id is a sender-generated value and is valid in the DocuSign system for 7 days. It is recommended that a transaction ID is used for offline signing to ensure that an envelope is not sent multiple times. The &#x60;transactionId&#x60; property can be used determine an envelope&#39;s status (i.e. was it created or not) in cases where the internet connection was lost before the envelope status was returned..</param> public BulkEnvelope(string BulkRecipientRow = default(string), string BulkStatus = default(string), string Email = default(string), string EnvelopeId = default(string), string EnvelopeUri = default(string), ErrorDetails ErrorDetails = default(ErrorDetails), string Name = default(string), string SubmittedDateTime = default(string), string TransactionId = default(string)) { this.BulkRecipientRow = BulkRecipientRow; this.BulkStatus = BulkStatus; this.Email = Email; this.EnvelopeId = EnvelopeId; this.EnvelopeUri = EnvelopeUri; this.ErrorDetails = ErrorDetails; this.Name = Name; this.SubmittedDateTime = SubmittedDateTime; this.TransactionId = TransactionId; } /// <summary> /// Reserved: TBD /// </summary> /// <value>Reserved: TBD</value> [DataMember(Name="bulkRecipientRow", EmitDefaultValue=false)] public string BulkRecipientRow { get; set; } /// <summary> /// Indicates the status of the bulk send operation. Returned values can be: * queued * processing * sent * failed /// </summary> /// <value>Indicates the status of the bulk send operation. Returned values can be: * queued * processing * sent * failed</value> [DataMember(Name="bulkStatus", EmitDefaultValue=false)] public string BulkStatus { get; set; } /// <summary> /// Gets or Sets Email /// </summary> [DataMember(Name="email", EmitDefaultValue=false)] public string Email { get; set; } /// <summary> /// The envelope ID of the envelope status that failed to post. /// </summary> /// <value>The envelope ID of the envelope status that failed to post.</value> [DataMember(Name="envelopeId", EmitDefaultValue=false)] public string EnvelopeId { get; set; } /// <summary> /// Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes. /// </summary> /// <value>Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes.</value> [DataMember(Name="envelopeUri", EmitDefaultValue=false)] public string EnvelopeUri { get; set; } /// <summary> /// Gets or Sets ErrorDetails /// </summary> [DataMember(Name="errorDetails", EmitDefaultValue=false)] public ErrorDetails ErrorDetails { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets SubmittedDateTime /// </summary> [DataMember(Name="submittedDateTime", EmitDefaultValue=false)] public string SubmittedDateTime { get; set; } /// <summary> /// Used to identify an envelope. The id is a sender-generated value and is valid in the DocuSign system for 7 days. It is recommended that a transaction ID is used for offline signing to ensure that an envelope is not sent multiple times. The &#x60;transactionId&#x60; property can be used determine an envelope&#39;s status (i.e. was it created or not) in cases where the internet connection was lost before the envelope status was returned. /// </summary> /// <value> Used to identify an envelope. The id is a sender-generated value and is valid in the DocuSign system for 7 days. It is recommended that a transaction ID is used for offline signing to ensure that an envelope is not sent multiple times. The &#x60;transactionId&#x60; property can be used determine an envelope&#39;s status (i.e. was it created or not) in cases where the internet connection was lost before the envelope status was returned.</value> [DataMember(Name="transactionId", EmitDefaultValue=false)] public string TransactionId { 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 BulkEnvelope {\n"); sb.Append(" BulkRecipientRow: ").Append(BulkRecipientRow).Append("\n"); sb.Append(" BulkStatus: ").Append(BulkStatus).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" EnvelopeId: ").Append(EnvelopeId).Append("\n"); sb.Append(" EnvelopeUri: ").Append(EnvelopeUri).Append("\n"); sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" SubmittedDateTime: ").Append(SubmittedDateTime).Append("\n"); sb.Append(" TransactionId: ").Append(TransactionId).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 BulkEnvelope); } /// <summary> /// Returns true if BulkEnvelope instances are equal /// </summary> /// <param name="other">Instance of BulkEnvelope to be compared</param> /// <returns>Boolean</returns> public bool Equals(BulkEnvelope other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.BulkRecipientRow == other.BulkRecipientRow || this.BulkRecipientRow != null && this.BulkRecipientRow.Equals(other.BulkRecipientRow) ) && ( this.BulkStatus == other.BulkStatus || this.BulkStatus != null && this.BulkStatus.Equals(other.BulkStatus) ) && ( this.Email == other.Email || this.Email != null && this.Email.Equals(other.Email) ) && ( this.EnvelopeId == other.EnvelopeId || this.EnvelopeId != null && this.EnvelopeId.Equals(other.EnvelopeId) ) && ( this.EnvelopeUri == other.EnvelopeUri || this.EnvelopeUri != null && this.EnvelopeUri.Equals(other.EnvelopeUri) ) && ( this.ErrorDetails == other.ErrorDetails || this.ErrorDetails != null && this.ErrorDetails.Equals(other.ErrorDetails) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.SubmittedDateTime == other.SubmittedDateTime || this.SubmittedDateTime != null && this.SubmittedDateTime.Equals(other.SubmittedDateTime) ) && ( this.TransactionId == other.TransactionId || this.TransactionId != null && this.TransactionId.Equals(other.TransactionId) ); } /// <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.BulkRecipientRow != null) hash = hash * 59 + this.BulkRecipientRow.GetHashCode(); if (this.BulkStatus != null) hash = hash * 59 + this.BulkStatus.GetHashCode(); if (this.Email != null) hash = hash * 59 + this.Email.GetHashCode(); if (this.EnvelopeId != null) hash = hash * 59 + this.EnvelopeId.GetHashCode(); if (this.EnvelopeUri != null) hash = hash * 59 + this.EnvelopeUri.GetHashCode(); if (this.ErrorDetails != null) hash = hash * 59 + this.ErrorDetails.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.SubmittedDateTime != null) hash = hash * 59 + this.SubmittedDateTime.GetHashCode(); if (this.TransactionId != null) hash = hash * 59 + this.TransactionId.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
//----------------------------------------------------------------------- // <copyright file="VideoOverlayProvider.cs" company="Google"> // // Copyright 2016 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. // // </copyright> //----------------------------------------------------------------------- namespace Tango { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using Tango; using UnityEngine; /// <summary> /// C API wrapper for the Tango video overlay interface. /// </summary> public class VideoOverlayProvider { private static readonly string CLASS_NAME = "VideoOverlayProvider"; private static IntPtr callbackContext = IntPtr.Zero; /// <summary> /// Tango video overlay C callback function signature. /// </summary> /// <param name="callbackContext">Callback context.</param> /// <param name="cameraId">Camera ID.</param> /// <param name="image">Image buffer.</param> [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void TangoService_onImageAvailable(IntPtr callbackContext, Tango.TangoEnums.TangoCameraId cameraId, [In, Out] TangoImageBuffer image); /// <summary> /// Experimental API only, subject to change. Tango depth C callback function signature. /// </summary> /// <param name="callbackContext">Callback context.</param> /// <param name="cameraId">Camera ID.</param> [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void TangoService_onUnityFrameAvailable(IntPtr callbackContext, Tango.TangoEnums.TangoCameraId cameraId); /// <summary> /// Connect a Texture ID to a camera; the camera is selected by specifying a TangoCameraId. /// /// Currently only TANGO_CAMERA_COLOR and TANGO_CAMERA_FISHEYE are supported. The texture must be the ID of a /// texture that has been allocated and initialized by the calling application. /// /// The first scan-line of the color image is reserved for metadata instead of image pixels. /// </summary> /// <param name="cameraId"> /// The ID of the camera to connect this texture to. Only TANGO_CAMERA_COLOR and TANGO_CAMERA_FISHEYE are /// supported. /// </param> /// <param name="textureId"> /// The texture ID of the texture to connect the camera to. Must be a valid texture in the applicaton. /// </param> public static void ConnectTexture(TangoEnums.TangoCameraId cameraId, int textureId) { int returnValue = VideoOverlayAPI.TangoService_connectTextureId(cameraId, textureId); if (returnValue != Common.ErrorType.TANGO_SUCCESS) { Debug.Log("VideoOverlayProvider.ConnectTexture() Texture was not connected to camera!"); } } /// <summary> /// Update the texture that has been connected to camera referenced by TangoCameraId with the latest image /// from the camera. /// </summary> /// <returns>The timestamp of the image that has been pushed to the connected texture.</returns> /// <param name="cameraId"> /// The ID of the camera to connect this texture to. Only <code>TANGO_CAMERA_COLOR</code> and /// <code>TANGO_CAMERA_FISHEYE</code> are supported. /// </param> public static double RenderLatestFrame(TangoEnums.TangoCameraId cameraId) { double timestamp = 0.0; int returnValue = VideoOverlayAPI.TangoService_updateTexture(cameraId, ref timestamp); if (returnValue != Common.ErrorType.TANGO_SUCCESS) { Debug.Log("VideoOverlayProvider.UpdateTexture() Texture was not updated by camera!"); } return timestamp; } /// <summary> /// Get the intrinsic calibration parameters for a given camera. /// /// The intrinsics are as specified by the TangoCameraIntrinsics struct. Intrinsics are read from the /// on-device intrinsics file (typically <code>/sdcard/config/calibration.xml</code>, but to ensure /// compatibility applications should only access these parameters via the API), or default internal model /// parameters corresponding to the device are used if the calibration.xml file is not found. /// </summary> /// <param name="cameraId">The camera ID to retrieve the calibration intrinsics for.</param> /// <param name="intrinsics">A TangoCameraIntrinsics filled with calibration intrinsics for the camera.</param> public static void GetIntrinsics(TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics) { int returnValue = VideoOverlayAPI.TangoService_getCameraIntrinsics(cameraId, intrinsics); if (returnValue != Common.ErrorType.TANGO_SUCCESS) { Debug.Log("IntrinsicsProviderAPI.TangoService_getCameraIntrinsics() failed!"); } } /// <summary> /// Experimental API only, subject to change. Connect a Texture IDs to a camera. /// /// The camera is selected via TangoCameraId. Currently only TANGO_CAMERA_COLOR is supported. The texture /// handles will be regenerated by the API on startup after which the application can use them, and will be /// packed RGBA8888 data containing bytes of the image (so a single RGBA8888 will pack 4 neighbouring pixels). /// If the config flag experimental_image_pixel_format is set to HAL_PIXEL_FORMAT_YCrCb_420_SP, texture_y will /// pack 1280x720 pixels into a 320x720 RGBA8888 texture. texture_Cb and texture_Cr will contain copies of /// the 2x2 downsampled interleaved UV planes packed similarly. If experimental_image_pixel_format is set to /// HAL_PIXEL_FORMAT_YV12 then texture_y will have a stride of 1536 containing 1280 columns of data, packed /// similarly in a RGBA8888 texture. texture_Cb and texture_Cr will be 2x2 downsampled versions of the same. /// See YV12 and NV21 formats for details. /// /// Note: The first scan-line of the color image is reserved for metadata instead of image pixels. /// </summary> /// <param name="cameraId"> /// The ID of the camera to connect this texture to. Only TANGO_CAMERA_COLOR and TANGO_CAMERA_FISHEYE are /// supported. /// </param> /// <param name="textures">The texture IDs to use for the Y, Cb, and Cr planes.</param> /// <param name="onUnityFrameAvailable">Callback method.</param> internal static void ExperimentalConnectTexture(TangoEnums.TangoCameraId cameraId, YUVTexture textures, TangoService_onUnityFrameAvailable onUnityFrameAvailable) { int returnValue = VideoOverlayAPI.TangoService_Experimental_connectTextureIdUnity(cameraId, (uint)textures.m_videoOverlayTextureY.GetNativeTextureID(), (uint)textures.m_videoOverlayTextureCb.GetNativeTextureID(), (uint)textures.m_videoOverlayTextureCr.GetNativeTextureID(), callbackContext, onUnityFrameAvailable); if (returnValue != Common.ErrorType.TANGO_SUCCESS) { Debug.Log("VideoOverlayProvider.ConnectTexture() Texture was not connected to camera!"); } } /// <summary> /// Connect a callback to a camera for access to the pixels. /// /// This is not recommended for display but for applications requiring access to the /// <code>HAL_PIXEL_FORMAT_YV12</code> pixel data. The camera is selected via TangoCameraId. Currently only /// <code>TANGO_CAMERA_COLOR</code> and <code>TANGO_CAMERA_FISHEYE</code> are supported. /// /// The <i>onImageAvailable</i> callback will be called when a new frame is available from the camera. The /// Enable Video Overlay option must be enabled for this to succeed. /// /// Note: The first scan-line of the color image is reserved for metadata instead of image pixels. /// </summary> /// <param name="cameraId"> /// The ID of the camera to connect this texture to. Only <code>TANGO_CAMERA_COLOR</code> and /// <code>TANGO_CAMERA_FISHEYE</code> are supported. /// </param> /// <param name="onImageAvailable">Function called when a new frame is available from the camera.</param> internal static void SetCallback(TangoEnums.TangoCameraId cameraId, TangoService_onImageAvailable onImageAvailable) { int returnValue = VideoOverlayAPI.TangoService_connectOnFrameAvailable(cameraId, callbackContext, onImageAvailable); if (returnValue == Tango.Common.ErrorType.TANGO_SUCCESS) { Debug.Log(CLASS_NAME + ".SetCallback() Callback was set."); } else { Debug.Log(CLASS_NAME + ".SetCallback() Callback was not set!"); } } #region NATIVE_FUNCTIONS [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "C API Wrapper.")] private struct VideoOverlayAPI { #if UNITY_ANDROID && !UNITY_EDITOR [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_connectTextureId(TangoEnums.TangoCameraId cameraId, int textureHandle); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_connectOnFrameAvailable(TangoEnums.TangoCameraId cameraId, IntPtr context, [In, Out] TangoService_onImageAvailable onImageAvailable); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_updateTexture(TangoEnums.TangoCameraId cameraId, ref double timestamp); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_getCameraIntrinsics(TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_Experimental_connectTextureIdUnity(TangoEnums.TangoCameraId id, uint texture_y, uint texture_Cb, uint texture_Cr, IntPtr context, TangoService_onUnityFrameAvailable onUnityFrameAvailable); #else public static int TangoService_connectTextureId(TangoEnums.TangoCameraId cameraId, int textureHandle) { return Tango.Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_updateTexture(TangoEnums.TangoCameraId cameraId, ref double timestamp) { return Tango.Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_getCameraIntrinsics(TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics) { return Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_connectOnFrameAvailable(TangoEnums.TangoCameraId cameraId, IntPtr context, [In, Out] TangoService_onImageAvailable onImageAvailable) { return Tango.Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_Experimental_connectTextureIdUnity(TangoEnums.TangoCameraId id, uint texture_y, uint texture_Cb, uint texture_Cr, IntPtr context, TangoService_onUnityFrameAvailable onUnityFrameAvailable) { return Tango.Common.ErrorType.TANGO_SUCCESS; } #endif #endregion } } /// <summary> /// Wraps separate textures for Y, U, and V planes. /// </summary> public class YUVTexture { /// <summary> /// The m_video overlay texture y. /// Columns 1280/4 [bytes packed in RGBA channels] /// Rows 720 /// This size is for a 1280x720 screen. /// </summary> public Texture2D m_videoOverlayTextureY; /// <summary> /// The m_video overlay texture cb. /// Columns 640/4 [bytes packed in RGBA channels] /// Rows 360 /// This size is for a 1280x720 screen. /// </summary> public Texture2D m_videoOverlayTextureCb; /// <summary> /// The m_video overlay texture cr. /// Columns 640 * 2 / 4 [bytes packed in RGBA channels] /// Rows 360 /// This size is for a 1280x720 screen. /// </summary> public Texture2D m_videoOverlayTextureCr; /// <summary> /// Initializes a new instance of the <see cref="Tango.YUVTexture"/> class. /// NOTE : Texture resolutions will be reset by the API. The sizes passed /// into the constructor are not guaranteed to persist when running on device. /// </summary> /// <param name="yPlaneWidth">Y plane width.</param> /// <param name="yPlaneHeight">Y plane height.</param> /// <param name="uvPlaneWidth">UV plane width.</param> /// <param name="uvPlaneHeight">UV plane height.</param> /// <param name="format">Texture format.</param> /// <param name="mipmap">If set to <c>true</c> mipmap.</param> public YUVTexture(int yPlaneWidth, int yPlaneHeight, int uvPlaneWidth, int uvPlaneHeight, TextureFormat format, bool mipmap) { m_videoOverlayTextureY = new Texture2D(yPlaneWidth, yPlaneHeight, format, mipmap); m_videoOverlayTextureY.filterMode = FilterMode.Point; m_videoOverlayTextureCb = new Texture2D(uvPlaneWidth, uvPlaneHeight, format, mipmap); m_videoOverlayTextureCb.filterMode = FilterMode.Point; m_videoOverlayTextureCr = new Texture2D(uvPlaneWidth, uvPlaneHeight, format, mipmap); m_videoOverlayTextureCr.filterMode = FilterMode.Point; } /// <summary> /// Resizes all yuv texture planes. /// </summary> /// <param name="yPlaneWidth">Y plane width.</param> /// <param name="yPlaneHeight">Y plane height.</param> /// <param name="uvPlaneWidth">Uv plane width.</param> /// <param name="uvPlaneHeight">Uv plane height.</param> public void ResizeAll(int yPlaneWidth, int yPlaneHeight, int uvPlaneWidth, int uvPlaneHeight) { m_videoOverlayTextureY.Resize(yPlaneWidth, yPlaneHeight); m_videoOverlayTextureCb.Resize(uvPlaneWidth, uvPlaneHeight); m_videoOverlayTextureCr.Resize(uvPlaneWidth, uvPlaneHeight); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #define TRACE using System.Reflection; using System.Management.Automation.Internal; namespace System.Management.Automation { /// <summary> /// An PSTraceSource is a representation of a System.Diagnostics.TraceSource instance /// that is used the the Monad components to produce trace output. /// </summary> /// <remarks> /// It is permitted to subclass <see cref="PSTraceSource"/> /// but there is no established scenario for doing this, nor has it been tested. /// </remarks> /// <!-- /// IF YOU ARE NOT PART OF THE MONAD DEVELOPMENT TEAM PLEASE /// DO NOT USE THIS CLASS!!!!! /// /// The PSTraceSource class is derived from Switch to provide granular /// control over the tracing in a program. An instance of PSTraceSource /// is created for each category of tracing such that separate flags /// (filters) can be set. Each flag enables one or more method for tracing. /// /// For instance, the Exception flag will enable tracing on these methods: /// TraceException. /// </summary> /// <remarks> /// To get an instance of this class a user should define a public static /// field of the type PSTraceSource, decorated it with an attribute of /// PSTraceSourceAttribute, and assign the results of GetTracer to it. /// <newpara/> /// <example> /// <code> /// [PSTraceSourceAttribute("category", "description")] /// public static PSTraceSource tracer = GetTracer("category", "description"); /// </code> /// </example> /// <newpara/> /// Other than initial creation of this class through the GetTracer method, /// this class should throw no exceptions. Any call to a PSTraceSource method /// that results in an exception being thrown will be ignored. /// --> public partial class PSTraceSource { /// <summary> /// Lock object for the GetTracer method. /// </summary> private static object s_getTracerLock = new object(); /// <summary> /// A helper to get an instance of the PSTraceSource class. /// </summary> /// <param name="name"> /// The name of the category that this class /// will control the tracing for. /// </param> /// <param name="description"> /// The description to describe what the category /// is used for. /// </param> /// <returns> /// An instance of the PSTraceSource class which is initialized /// to trace for the specified category. If multiple callers ask for the same category, /// the same PSTraceSource will be returned. /// </returns> internal static PSTraceSource GetTracer( string name, string description) { return PSTraceSource.GetTracer(name, description, true); } /// <summary> /// A helper to get an instance of the PSTraceSource class. /// </summary> /// <param name="name"> /// The name of the category that this class /// will control the tracing for. /// </param> /// <param name="description"> /// The description to describe what the category /// is used for. /// </param> /// <param name="traceHeaders"> /// If true, the line headers will be traced, if false, only the trace message will be traced. /// </param> /// <returns> /// An instance of the PSTraceSource class which is initialized /// to trace for the specified category. If multiple callers ask for the same category, /// the same PSTraceSource will be returned. /// </returns> internal static PSTraceSource GetTracer( string name, string description, bool traceHeaders) { if (string.IsNullOrEmpty(name)) { // 2005/04/13-JonN In theory this should be ArgumentException, // but I don't want to deal with loading the string in this // low-level code. throw new ArgumentNullException("name"); } lock (PSTraceSource.s_getTracerLock) { PSTraceSource result = null; // See if we can find an PSTraceSource for this category in the catalog. PSTraceSource.TraceCatalog.TryGetValue(name, out result); // If it's not already in the catalog, see if we can find it in the // pre-configured trace source list if (result == null) { string keyName = name; if (!PSTraceSource.PreConfiguredTraceSource.ContainsKey(keyName)) { if (keyName.Length > 16) { keyName = keyName.Substring(0, 16); if (!PSTraceSource.PreConfiguredTraceSource.ContainsKey(keyName)) { keyName = null; } } else { keyName = null; } } if (keyName != null) { // Get the pre-configured trace source from the catalog PSTraceSource preconfiguredSource = PSTraceSource.PreConfiguredTraceSource[keyName]; result = PSTraceSource.GetNewTraceSource(keyName, description, traceHeaders); result.Options = preconfiguredSource.Options; result.Listeners.Clear(); result.Listeners.AddRange(preconfiguredSource.Listeners); // Add it to the TraceCatalog PSTraceSource.TraceCatalog.Add(keyName, result); // Remove it from the pre-configured catalog PSTraceSource.PreConfiguredTraceSource.Remove(keyName); } } // Even if there was a PSTraceSource in the catalog, let's replace // it with an PSTraceSource to get the added functionality. Anyone using // a StructuredTraceSource should be able to do so even with the PSTraceSource // instance. if (result == null) { result = PSTraceSource.GetNewTraceSource(name, description, traceHeaders); PSTraceSource.TraceCatalog[result.FullName] = result; } if (result.Options != PSTraceSourceOptions.None && traceHeaders) { result.TraceGlobalAppDomainHeader(); // Trace the object specific tracer information result.TracerObjectHeader(Assembly.GetCallingAssembly()); } return result; } } internal static PSTraceSource GetNewTraceSource( string name, string description, bool traceHeaders) { if (string.IsNullOrEmpty(name)) { // Note, all callers should have already verified the name before calling this // API, so this exception should never be exposed to an end-user. throw new ArgumentException("name"); } // Keep the fullName as it was passed, but truncate or pad // the category name to 16 characters. This allows for // uniform output string fullName = name; /* // This is here to ensure all the trace category names are 16 characters, // the problem is that the app-config file would need to contain the same // trailing spaces if this actually does pad the name. name = string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0,-16}", name); */ PSTraceSource result = new PSTraceSource( fullName, name, description, traceHeaders); return result; } #region TraceFlags.New*Exception methods/helpers /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This is not allowed to call other /// Throw*Exception variants, since they call this. /// </summary> /// <param name="paramName"> /// The name of the parameter whose argument value was null /// </param> /// <returns>Exception instance ready to throw.</returns> internal static PSArgumentNullException NewArgumentNullException(string paramName) { if (string.IsNullOrEmpty(paramName)) { throw new ArgumentNullException("paramName"); } string message = StringUtil.Format(AutomationExceptions.ArgumentNull, paramName); var e = new PSArgumentNullException(paramName, message); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This variant allows the caller to /// specify alternate template text, but only in assembly S.M.A.Core. /// </summary> /// <param name="paramName"> /// The name of the parameter whose argument value was invalid /// </param> /// <param name="resourceString"> /// The template string for this error /// </param> /// <param name="args"> /// Objects corresponding to {0}, {1}, etc. in the resource string /// </param> /// <returns>Exception instance ready to throw.</returns> internal static PSArgumentNullException NewArgumentNullException( string paramName, string resourceString, params object[] args) { if (string.IsNullOrEmpty(paramName)) { throw NewArgumentNullException("paramName"); } if (string.IsNullOrEmpty(resourceString)) { throw NewArgumentNullException("resourceString"); } string message = StringUtil.Format(resourceString, args); // Note that the paramName param comes first var e = new PSArgumentNullException(paramName, message); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This variant uses the default /// ArgumentException template text. This is not allowed to call /// other Throw*Exception variants, since they call this. /// </summary> /// <param name="paramName"> /// The name of the parameter whose argument value was invalid /// </param> /// <returns>Exception instance ready to throw.</returns> internal static PSArgumentException NewArgumentException(string paramName) { if (string.IsNullOrEmpty(paramName)) { throw new ArgumentNullException("paramName"); } string message = StringUtil.Format(AutomationExceptions.Argument, paramName); // Note that the message param comes first var e = new PSArgumentException(message, paramName); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This variant allows the caller to /// specify alternate template text, but only in assembly S.M.A.Core. /// </summary> /// <param name="paramName"> /// The name of the parameter whose argument value was invalid /// </param> /// <param name="resourceString"> /// The template string for this error /// </param> /// <param name="args"> /// Objects corresponding to {0}, {1}, etc. in the resource string /// </param> /// <returns>Exception instance ready to throw.</returns> internal static PSArgumentException NewArgumentException( string paramName, string resourceString, params object[] args) { if (string.IsNullOrEmpty(paramName)) { throw NewArgumentNullException("paramName"); } if (string.IsNullOrEmpty(resourceString)) { throw NewArgumentNullException("resourceString"); } string message = StringUtil.Format(resourceString, args); // Note that the message param comes first var e = new PSArgumentException(message, paramName); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. /// </summary> /// <returns>Exception instance ready to throw.</returns> internal static PSInvalidOperationException NewInvalidOperationException() { string message = StringUtil.Format(AutomationExceptions.InvalidOperation, new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name); var e = new PSInvalidOperationException(message); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This variant allows the caller to /// specify alternate template text, but only in assembly S.M.A.Core. /// </summary> /// <param name="resourceString"> /// The template string for this error /// </param> /// <param name="args"> /// Objects corresponding to {0}, {1}, etc. in the resource string /// </param> /// <returns>Exception instance ready to throw.</returns> internal static PSInvalidOperationException NewInvalidOperationException( string resourceString, params object[] args) { if (string.IsNullOrEmpty(resourceString)) { throw NewArgumentNullException("resourceString"); } string message = StringUtil.Format(resourceString, args); var e = new PSInvalidOperationException(message); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This variant allows the caller to /// specify alternate template text, but only in assembly S.M.A.Core. /// </summary> /// <param name="innerException"> /// This is the InnerException for the InvalidOperationException /// </param> /// <param name="resourceString"> /// The template string for this error /// </param> /// <param name="args"> /// Objects corresponding to {0}, {1}, etc. in the resource string /// </param> /// <returns>Exception instance ready to throw.</returns> internal static PSInvalidOperationException NewInvalidOperationException( Exception innerException, string resourceString, params object[] args) { if (string.IsNullOrEmpty(resourceString)) { throw NewArgumentNullException("resourceString"); } string message = StringUtil.Format(resourceString, args); var e = new PSInvalidOperationException(message, innerException); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This is not allowed to call other /// Throw*Exception variants, since they call this. /// </summary> /// <returns>Exception instance ready to throw.</returns> internal static PSNotSupportedException NewNotSupportedException() { string message = StringUtil.Format(AutomationExceptions.NotSupported, new System.Diagnostics.StackTrace().GetFrame(0).ToString()); var e = new PSNotSupportedException(message); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This is not allowed to call other /// Throw*Exception variants, since they call this. /// </summary> /// <param name="resourceString"> /// The template string for this error /// </param> /// <param name="args"> /// Objects corresponding to {0}, {1}, etc. in the resource string /// </param> /// <returns>Exception instance ready to throw.</returns> internal static PSNotSupportedException NewNotSupportedException( string resourceString, params object[] args) { if (string.IsNullOrEmpty(resourceString)) { throw NewArgumentNullException("resourceString"); } string message = StringUtil.Format(resourceString, args); var e = new PSNotSupportedException(message); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This is not allowed to call other /// Throw*Exception variants, since they call this. /// </summary> /// <returns>Exception instance ready to throw.</returns> internal static PSNotImplementedException NewNotImplementedException() { string message = StringUtil.Format(AutomationExceptions.NotImplemented, new System.Diagnostics.StackTrace().GetFrame(0).ToString()); var e = new PSNotImplementedException(message); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This variant uses the default /// ArgumentOutOfRangeException template text. This is not allowed to call /// other Throw*Exception variants, since they call this. /// </summary> /// <param name="paramName"> /// The name of the parameter whose argument value was out of range /// </param> /// <param name="actualValue"> /// The value of the argument causing the exception /// </param> /// <returns>Exception instance ready to throw.</returns> internal static PSArgumentOutOfRangeException NewArgumentOutOfRangeException(string paramName, object actualValue) { if (string.IsNullOrEmpty(paramName)) { throw new ArgumentNullException("paramName"); } string message = StringUtil.Format(AutomationExceptions.ArgumentOutOfRange, paramName); var e = new PSArgumentOutOfRangeException(paramName, actualValue, message); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This variant allows the caller to /// specify alternate template text, but only in assembly S.M.A.Core. /// </summary> /// <param name="paramName"> /// The name of the parameter whose argument value was invalid /// </param> /// <param name="actualValue"> /// The value of the argument causing the exception /// </param> /// <param name="resourceString"> /// The template string for this error /// </param> /// <param name="args"> /// Objects corresponding to {0}, {1}, etc. in the resource string /// </param> /// <returns>Exception instance ready to throw.</returns> internal static PSArgumentOutOfRangeException NewArgumentOutOfRangeException( string paramName, object actualValue, string resourceString, params object[] args) { if (string.IsNullOrEmpty(paramName)) { throw NewArgumentNullException("paramName"); } if (string.IsNullOrEmpty(resourceString)) { throw NewArgumentNullException("resourceString"); } string message = StringUtil.Format(resourceString, args); var e = new PSArgumentOutOfRangeException(paramName, actualValue, message); return e; } /// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This variant uses the default /// ObjectDisposedException template text. This is not allowed to call /// other Throw*Exception variants, since they call this. /// </summary> /// <param name="objectName"> /// The name of the disposed object /// </param> /// <returns>Exception instance ready to throw.</returns> /// <remarks> /// Note that the parameter is the object name and not the message. /// </remarks> internal static PSObjectDisposedException NewObjectDisposedException(string objectName) { if (string.IsNullOrEmpty(objectName)) { throw NewArgumentNullException("objectName"); } string message = StringUtil.Format(AutomationExceptions.ObjectDisposed, objectName); var e = new PSObjectDisposedException(objectName, message); return e; } #endregion TraceFlags.New*Exception methods/helpers } }
#nullable disable namespace SharpCompress.Compressors.PPMd.I1 { /// <summary> /// The PPM context structure. This is tightly coupled with <see cref="Model"/>. /// </summary> /// <remarks> /// <para> /// This must be a structure rather than a class because several places in the associated code assume that /// <see cref="PpmContext"/> is a value type (meaning that assignment creates a completely new copy of /// the instance rather than just copying a reference to the same instance). /// </para> /// </remarks> internal partial class Model { /// <summary> /// The structure which represents the current PPM context. This is 12 bytes in size. /// </summary> internal struct PpmContext { public uint _address; public byte[] _memory; public static readonly PpmContext ZERO = new PpmContext(0, null); public const int SIZE = 12; /// <summary> /// Initializes a new instance of the <see cref="PpmContext"/> structure. /// </summary> public PpmContext(uint address, byte[] memory) { _address = address; _memory = memory; } /// <summary> /// Gets or sets the number statistics. /// </summary> public byte NumberStatistics { get => _memory[_address]; set => _memory[_address] = value; } /// <summary> /// Gets or sets the flags. /// </summary> public byte Flags { get => _memory[_address + 1]; set => _memory[_address + 1] = value; } /// <summary> /// Gets or sets the summary frequency. /// </summary> public ushort SummaryFrequency { get => (ushort)(_memory[_address + 2] | _memory[_address + 3] << 8); set { _memory[_address + 2] = (byte)value; _memory[_address + 3] = (byte)(value >> 8); } } /// <summary> /// Gets or sets the statistics. /// </summary> public PpmState Statistics { get => new PpmState( _memory[_address + 4] | ((uint)_memory[_address + 5]) << 8 | ((uint)_memory[_address + 6]) << 16 | ((uint)_memory[_address + 7]) << 24, _memory); set { _memory[_address + 4] = (byte)value._address; _memory[_address + 5] = (byte)(value._address >> 8); _memory[_address + 6] = (byte)(value._address >> 16); _memory[_address + 7] = (byte)(value._address >> 24); } } /// <summary> /// Gets or sets the suffix. /// </summary> public PpmContext Suffix { get => new PpmContext( _memory[_address + 8] | ((uint)_memory[_address + 9]) << 8 | ((uint)_memory[_address + 10]) << 16 | ((uint)_memory[_address + 11]) << 24, _memory); set { _memory[_address + 8] = (byte)value._address; _memory[_address + 9] = (byte)(value._address >> 8); _memory[_address + 10] = (byte)(value._address >> 16); _memory[_address + 11] = (byte)(value._address >> 24); } } /// <summary> /// The first PPM state associated with the PPM context. /// </summary> /// <remarks> /// <para> /// The first PPM state overlaps this PPM context instance (the context.SummaryFrequency and context.Statistics members /// of PpmContext use 6 bytes and so can therefore fit into the space used by the Symbol, Frequency and /// Successor members of PpmState, since they also add up to 6 bytes). /// </para> /// <para> /// PpmContext (context.SummaryFrequency and context.Statistics use 6 bytes) /// 1 context.NumberStatistics /// 1 context.Flags /// 2 context.SummaryFrequency /// 4 context.Statistics (pointer to PpmState) /// 4 context.Suffix (pointer to PpmContext) /// </para> /// <para> /// PpmState (total of 6 bytes) /// 1 Symbol /// 1 Frequency /// 4 Successor (pointer to PpmContext) /// </para> /// </remarks> /// <returns></returns> public PpmState FirstState => new PpmState(_address + 2, _memory); /// <summary> /// Gets or sets the symbol of the first PPM state. This is provided for convenience. The same /// information can be obtained using the Symbol property on the PPM state provided by the /// <see cref="FirstState"/> property. /// </summary> public byte FirstStateSymbol { get => _memory[_address + 2]; set => _memory[_address + 2] = value; } /// <summary> /// Gets or sets the frequency of the first PPM state. This is provided for convenience. The same /// information can be obtained using the Frequency property on the PPM state provided by the ///context.FirstState property. /// </summary> public byte FirstStateFrequency { get => _memory[_address + 3]; set => _memory[_address + 3] = value; } /// <summary> /// Gets or sets the successor of the first PPM state. This is provided for convenience. The same /// information can be obtained using the Successor property on the PPM state provided by the /// </summary> public PpmContext FirstStateSuccessor { get => new PpmContext( _memory[_address + 4] | ((uint)_memory[_address + 5]) << 8 | ((uint)_memory[_address + 6]) << 16 | ((uint)_memory[_address + 7]) << 24, _memory); set { _memory[_address + 4] = (byte)value._address; _memory[_address + 5] = (byte)(value._address >> 8); _memory[_address + 6] = (byte)(value._address >> 16); _memory[_address + 7] = (byte)(value._address >> 24); } } /// <summary> /// Allow a pointer to be implicitly converted to a PPM context. /// </summary> /// <param name="pointer"></param> /// <returns></returns> public static implicit operator PpmContext(Pointer pointer) { return new PpmContext(pointer._address, pointer._memory); } /// <summary> /// Allow pointer-like addition on a PPM context. /// </summary> /// <param name="context"></param> /// <param name="offset"></param> /// <returns></returns> public static PpmContext operator +(PpmContext context, int offset) { context._address = (uint)(context._address + offset * SIZE); return context; } /// <summary> /// Allow pointer-like subtraction on a PPM context. /// </summary> /// <param name="context"></param> /// <param name="offset"></param> /// <returns></returns> public static PpmContext operator -(PpmContext context, int offset) { context._address = (uint)(context._address - offset * SIZE); return context; } /// <summary> /// Compare two PPM contexts. /// </summary> /// <param name="context1"></param> /// <param name="context2"></param> /// <returns></returns> public static bool operator <=(PpmContext context1, PpmContext context2) { return context1._address <= context2._address; } /// <summary> /// Compare two PPM contexts. /// </summary> /// <param name="context1"></param> /// <param name="context2"></param> /// <returns></returns> public static bool operator >=(PpmContext context1, PpmContext context2) { return context1._address >= context2._address; } /// <summary> /// Compare two PPM contexts. /// </summary> /// <param name="context1"></param> /// <param name="context2"></param> /// <returns></returns> public static bool operator ==(PpmContext context1, PpmContext context2) { return context1._address == context2._address; } /// <summary> /// Compare two PPM contexts. /// </summary> /// <param name="context1"></param> /// <param name="context2"></param> /// <returns></returns> public static bool operator !=(PpmContext context1, PpmContext context2) { return context1._address != context2._address; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <returns>true if obj and this instance are the same type and represent the same value; otherwise, false.</returns> /// <param name="obj">Another object to compare to.</param> public override bool Equals(object obj) { if (obj is PpmContext) { PpmContext context = (PpmContext)obj; return context._address == _address; } return base.Equals(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 _address.GetHashCode(); } } private void EncodeBinarySymbol(int symbol, PpmContext context) { PpmState state = context.FirstState; int index1 = _probabilities[state.Frequency - 1]; int index2 = _numberStatisticsToBinarySummaryIndex[context.Suffix.NumberStatistics] + _previousSuccess + context.Flags + ((_runLength >> 26) & 0x20); if (state.Symbol == symbol) { _foundState = state; state.Frequency += (byte)((state.Frequency < 196) ? 1 : 0); _coder._lowCount = 0; _coder._highCount = _binarySummary[index1, index2]; _binarySummary[index1, index2] += (ushort)(INTERVAL - Mean(_binarySummary[index1, index2], PERIOD_BIT_COUNT, 2)); _previousSuccess = 1; _runLength++; } else { _coder._lowCount = _binarySummary[index1, index2]; _binarySummary[index1, index2] -= (ushort)Mean(_binarySummary[index1, index2], PERIOD_BIT_COUNT, 2); _coder._highCount = BINARY_SCALE; _initialEscape = EXPONENTIAL_ESCAPES[_binarySummary[index1, index2] >> 10]; _characterMask[state.Symbol] = _escapeCount; _previousSuccess = 0; _numberMasked = 0; _foundState = PpmState.ZERO; } } private void EncodeSymbol1(int symbol, PpmContext context) { uint lowCount; uint index = context.Statistics.Symbol; PpmState state = context.Statistics; _coder._scale = context.SummaryFrequency; if (index == symbol) { _coder._highCount = state.Frequency; _previousSuccess = (byte)((2 * _coder._highCount >= _coder._scale) ? 1 : 0); _foundState = state; _foundState.Frequency += 4; context.SummaryFrequency += 4; _runLength += _previousSuccess; if (state.Frequency > MAXIMUM_FREQUENCY) { Rescale(context); } _coder._lowCount = 0; return; } lowCount = state.Frequency; index = context.NumberStatistics; _previousSuccess = 0; while ((++state).Symbol != symbol) { lowCount += state.Frequency; if (--index == 0) { _coder._lowCount = lowCount; _characterMask[state.Symbol] = _escapeCount; _numberMasked = context.NumberStatistics; index = context.NumberStatistics; _foundState = PpmState.ZERO; do { _characterMask[(--state).Symbol] = _escapeCount; } while (--index != 0); _coder._highCount = _coder._scale; return; } } _coder._highCount = (_coder._lowCount = lowCount) + state.Frequency; Update1(state, context); } private void EncodeSymbol2(int symbol, PpmContext context) { See2Context see2Context = MakeEscapeFrequency(context); uint currentSymbol; uint lowCount = 0; uint index = (uint)(context.NumberStatistics - _numberMasked); PpmState state = context.Statistics - 1; do { do { currentSymbol = state[1].Symbol; state++; } while (_characterMask[currentSymbol] == _escapeCount); _characterMask[currentSymbol] = _escapeCount; if (currentSymbol == symbol) { goto SymbolFound; } lowCount += state.Frequency; } while (--index != 0); _coder._lowCount = lowCount; _coder._scale += _coder._lowCount; _coder._highCount = _coder._scale; see2Context._summary += (ushort)_coder._scale; _numberMasked = context.NumberStatistics; return; SymbolFound: _coder._lowCount = lowCount; lowCount += state.Frequency; _coder._highCount = lowCount; for (PpmState p1 = state; --index != 0;) { do { currentSymbol = p1[1].Symbol; p1++; } while (_characterMask[currentSymbol] == _escapeCount); lowCount += p1.Frequency; } _coder._scale += lowCount; see2Context.Update(); Update2(state, context); } private void DecodeBinarySymbol(PpmContext context) { PpmState state = context.FirstState; int index1 = _probabilities[state.Frequency - 1]; int index2 = _numberStatisticsToBinarySummaryIndex[context.Suffix.NumberStatistics] + _previousSuccess + context.Flags + ((_runLength >> 26) & 0x20); if (_coder.RangeGetCurrentShiftCount(TOTAL_BIT_COUNT) < _binarySummary[index1, index2]) { _foundState = state; state.Frequency += (byte)((state.Frequency < 196) ? 1 : 0); _coder._lowCount = 0; _coder._highCount = _binarySummary[index1, index2]; _binarySummary[index1, index2] += (ushort)(INTERVAL - Mean(_binarySummary[index1, index2], PERIOD_BIT_COUNT, 2)); _previousSuccess = 1; _runLength++; } else { _coder._lowCount = _binarySummary[index1, index2]; _binarySummary[index1, index2] -= (ushort)Mean(_binarySummary[index1, index2], PERIOD_BIT_COUNT, 2); _coder._highCount = BINARY_SCALE; _initialEscape = EXPONENTIAL_ESCAPES[_binarySummary[index1, index2] >> 10]; _characterMask[state.Symbol] = _escapeCount; _previousSuccess = 0; _numberMasked = 0; _foundState = PpmState.ZERO; } } private void DecodeSymbol1(PpmContext context) { uint index; uint count; uint highCount = context.Statistics.Frequency; PpmState state = context.Statistics; _coder._scale = context.SummaryFrequency; count = _coder.RangeGetCurrentCount(); if (count < highCount) { _coder._highCount = highCount; _previousSuccess = (byte)((2 * _coder._highCount >= _coder._scale) ? 1 : 0); _foundState = state; highCount += 4; _foundState.Frequency = (byte)highCount; context.SummaryFrequency += 4; _runLength += _previousSuccess; if (highCount > MAXIMUM_FREQUENCY) { Rescale(context); } _coder._lowCount = 0; return; } index = context.NumberStatistics; _previousSuccess = 0; while ((highCount += (++state).Frequency) <= count) { if (--index == 0) { _coder._lowCount = highCount; _characterMask[state.Symbol] = _escapeCount; _numberMasked = context.NumberStatistics; index = context.NumberStatistics; _foundState = PpmState.ZERO; do { _characterMask[(--state).Symbol] = _escapeCount; } while (--index != 0); _coder._highCount = _coder._scale; return; } } _coder._highCount = highCount; _coder._lowCount = _coder._highCount - state.Frequency; Update1(state, context); } private void DecodeSymbol2(PpmContext context) { See2Context see2Context = MakeEscapeFrequency(context); uint currentSymbol; uint count; uint highCount = 0; uint index = (uint)(context.NumberStatistics - _numberMasked); uint stateIndex = 0; PpmState state = context.Statistics - 1; do { do { currentSymbol = state[1].Symbol; state++; } while (_characterMask[currentSymbol] == _escapeCount); highCount += state.Frequency; _decodeStates[stateIndex++] = state; // note that decodeStates is a static array that is re-used on each call to this method (for performance reasons) } while (--index != 0); _coder._scale += highCount; count = _coder.RangeGetCurrentCount(); stateIndex = 0; state = _decodeStates[stateIndex]; if (count < highCount) { highCount = 0; while ((highCount += state.Frequency) <= count) { state = _decodeStates[++stateIndex]; } _coder._highCount = highCount; _coder._lowCount = _coder._highCount - state.Frequency; see2Context.Update(); Update2(state, context); } else { _coder._lowCount = highCount; _coder._highCount = _coder._scale; index = (uint)(context.NumberStatistics - _numberMasked); _numberMasked = context.NumberStatistics; do { _characterMask[_decodeStates[stateIndex].Symbol] = _escapeCount; stateIndex++; } while (--index != 0); see2Context._summary += (ushort)_coder._scale; } } private void Update1(PpmState state, PpmContext context) { _foundState = state; _foundState.Frequency += 4; context.SummaryFrequency += 4; if (state[0].Frequency > state[-1].Frequency) { Swap(state[0], state[-1]); _foundState = --state; if (state.Frequency > MAXIMUM_FREQUENCY) { Rescale(context); } } } private void Update2(PpmState state, PpmContext context) { _foundState = state; _foundState.Frequency += 4; context.SummaryFrequency += 4; if (state.Frequency > MAXIMUM_FREQUENCY) { Rescale(context); } _escapeCount++; _runLength = _initialRunLength; } private See2Context MakeEscapeFrequency(PpmContext context) { uint numberStatistics = (uint)2 * context.NumberStatistics; See2Context see2Context; if (context.NumberStatistics != 0xff) { // Note that context.Flags is always in the range 0 .. 28 (this ensures that the index used for the second // dimension of the see2Contexts array is always in the range 0 .. 31). numberStatistics = context.Suffix.NumberStatistics; int index1 = _probabilities[context.NumberStatistics + 2] - 3; int index2 = ((context.SummaryFrequency > 11 * (context.NumberStatistics + 1)) ? 1 : 0) + ((2 * context.NumberStatistics < numberStatistics + _numberMasked) ? 2 : 0) + context.Flags; see2Context = _see2Contexts[index1, index2]; _coder._scale = see2Context.Mean(); } else { see2Context = _emptySee2Context; _coder._scale = 1; } return see2Context; } private void Rescale(PpmContext context) { uint oldUnitCount; int adder; uint escapeFrequency; uint index = context.NumberStatistics; byte localSymbol; byte localFrequency; PpmContext localSuccessor; PpmState p1; PpmState state; for (state = _foundState; state != context.Statistics; state--) { Swap(state[0], state[-1]); } state.Frequency += 4; context.SummaryFrequency += 4; escapeFrequency = (uint)(context.SummaryFrequency - state.Frequency); adder = (_orderFall != 0 || _method > ModelRestorationMethod.Freeze) ? 1 : 0; state.Frequency = (byte)((state.Frequency + adder) >> 1); context.SummaryFrequency = state.Frequency; do { escapeFrequency -= (++state).Frequency; state.Frequency = (byte)((state.Frequency + adder) >> 1); context.SummaryFrequency += state.Frequency; if (state[0].Frequency > state[-1].Frequency) { p1 = state; localSymbol = p1.Symbol; localFrequency = p1.Frequency; localSuccessor = p1.Successor; do { Copy(p1[0], p1[-1]); } while (localFrequency > (--p1)[-1].Frequency); p1.Symbol = localSymbol; p1.Frequency = localFrequency; p1.Successor = localSuccessor; } } while (--index != 0); if (state.Frequency == 0) { do { index++; } while ((--state).Frequency == 0); escapeFrequency += index; oldUnitCount = (uint)((context.NumberStatistics + 2) >> 1); context.NumberStatistics -= (byte)index; if (context.NumberStatistics == 0) { localSymbol = context.Statistics.Symbol; localFrequency = context.Statistics.Frequency; localSuccessor = context.Statistics.Successor; localFrequency = (byte)((2 * localFrequency + escapeFrequency - 1) / escapeFrequency); if (localFrequency > MAXIMUM_FREQUENCY / 3) { localFrequency = (byte)(MAXIMUM_FREQUENCY / 3); } _allocator.FreeUnits(context.Statistics, oldUnitCount); context.FirstStateSymbol = localSymbol; context.FirstStateFrequency = localFrequency; context.FirstStateSuccessor = localSuccessor; context.Flags = (byte)((context.Flags & 0x10) + ((localSymbol >= 0x40) ? 0x08 : 0x00)); _foundState = context.FirstState; return; } context.Statistics = _allocator.ShrinkUnits(context.Statistics, oldUnitCount, (uint)((context.NumberStatistics + 2) >> 1)); context.Flags &= 0xf7; index = context.NumberStatistics; state = context.Statistics; context.Flags |= (byte)((state.Symbol >= 0x40) ? 0x08 : 0x00); do { context.Flags |= (byte)(((++state).Symbol >= 0x40) ? 0x08 : 0x00); } while (--index != 0); } escapeFrequency -= (escapeFrequency >> 1); context.SummaryFrequency += (ushort)escapeFrequency; context.Flags |= 0x04; _foundState = context.Statistics; } private void Refresh(uint oldUnitCount, bool scale, PpmContext context) { int index = context.NumberStatistics; int escapeFrequency; int scaleValue = (scale ? 1 : 0); context.Statistics = _allocator.ShrinkUnits(context.Statistics, oldUnitCount, (uint)((index + 2) >> 1)); PpmState statistics = context.Statistics; context.Flags = (byte)((context.Flags & (0x10 + (scale ? 0x04 : 0x00))) + ((statistics.Symbol >= 0x40) ? 0x08 : 0x00)); escapeFrequency = context.SummaryFrequency - statistics.Frequency; statistics.Frequency = (byte)((statistics.Frequency + scaleValue) >> scaleValue); context.SummaryFrequency = statistics.Frequency; do { escapeFrequency -= (++statistics).Frequency; statistics.Frequency = (byte)((statistics.Frequency + scaleValue) >> scaleValue); context.SummaryFrequency += statistics.Frequency; context.Flags |= (byte)((statistics.Symbol >= 0x40) ? 0x08 : 0x00); } while (--index != 0); escapeFrequency = (escapeFrequency + scaleValue) >> scaleValue; context.SummaryFrequency += (ushort)escapeFrequency; } private PpmContext CutOff(int order, PpmContext context) { int index; PpmState state; if (context.NumberStatistics == 0) { state = context.FirstState; if ((Pointer)state.Successor >= _allocator._baseUnit) { if (order < _modelOrder) { state.Successor = CutOff(order + 1, state.Successor); } else { state.Successor = PpmContext.ZERO; } if (state.Successor == PpmContext.ZERO && order > ORDER_BOUND) { _allocator.SpecialFreeUnits(context); return PpmContext.ZERO; } return context; } _allocator.SpecialFreeUnits(context); return PpmContext.ZERO; } uint unitCount = (uint)((context.NumberStatistics + 2) >> 1); context.Statistics = _allocator.MoveUnitsUp(context.Statistics, unitCount); index = context.NumberStatistics; for (state = context.Statistics + index; state >= context.Statistics; state--) { if (state.Successor < _allocator._baseUnit) { state.Successor = PpmContext.ZERO; Swap(state, context.Statistics[index--]); } else if (order < _modelOrder) { state.Successor = CutOff(order + 1, state.Successor); } else { state.Successor = PpmContext.ZERO; } } if (index != context.NumberStatistics && order != 0) { context.NumberStatistics = (byte)index; state = context.Statistics; if (index < 0) { _allocator.FreeUnits(state, unitCount); _allocator.SpecialFreeUnits(context); return PpmContext.ZERO; } if (index == 0) { context.Flags = (byte)((context.Flags & 0x10) + ((state.Symbol >= 0x40) ? 0x08 : 0x00)); Copy(context.FirstState, state); _allocator.FreeUnits(state, unitCount); context.FirstStateFrequency = (byte)((context.FirstStateFrequency + 11) >> 3); } else { Refresh(unitCount, context.SummaryFrequency > 16 * index, context); } } return context; } private PpmContext RemoveBinaryContexts(int order, PpmContext context) { if (context.NumberStatistics == 0) { PpmState state = context.FirstState; if ((Pointer)state.Successor >= _allocator._baseUnit && order < _modelOrder) { state.Successor = RemoveBinaryContexts(order + 1, state.Successor); } else { state.Successor = PpmContext.ZERO; } if ((state.Successor == PpmContext.ZERO) && (context.Suffix.NumberStatistics == 0 || context.Suffix.Flags == 0xff)) { _allocator.FreeUnits(context, 1); return PpmContext.ZERO; } return context; } for (PpmState state = context.Statistics + context.NumberStatistics; state >= context.Statistics; state--) { if ((Pointer)state.Successor >= _allocator._baseUnit && order < _modelOrder) { state.Successor = RemoveBinaryContexts(order + 1, state.Successor); } else { state.Successor = PpmContext.ZERO; } } return context; } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.ComTypes; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Malware.MDKAnalyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class ScriptAnalyzer : DiagnosticAnalyzer { const string DefaultNamespaceName = "IngameScript"; internal static readonly DiagnosticDescriptor NoWhitelistCacheRule = new DiagnosticDescriptor("MissingWhitelistRule", "Missing Or Corrupted Whitelist Cache", "The whitelist cache could not be loaded. Please run Tools | MDK | Refresh Whitelist Cache to attempt repair.", "Whitelist", DiagnosticSeverity.Error, true); internal static readonly DiagnosticDescriptor NoOptionsRule = new DiagnosticDescriptor("MissingOptionsRule", "Missing Or Corrupted Options", "The MDK.options could not be loaded.", "Whitelist", DiagnosticSeverity.Error, true); internal static readonly DiagnosticDescriptor ProhibitedMemberRule = new DiagnosticDescriptor("ProhibitedMemberRule", "Prohibited Type Or Member", "The type or member '{0}' is prohibited in Space Engineers", "Whitelist", DiagnosticSeverity.Error, true); internal static readonly DiagnosticDescriptor ProhibitedLanguageElementRule = new DiagnosticDescriptor("ProhibitedLanguageElement", "Prohibited Language Element", "The language element '{0}' is prohibited in Space Engineers", "Whitelist", DiagnosticSeverity.Error, true); internal static readonly DiagnosticDescriptor InconsistentNamespaceDeclarationRule = new DiagnosticDescriptor("InconsistentNamespaceDeclaration", "Inconsistent Namespace Declaration", "All ingame script code should be within the {0} namespace in order to avoid problems.", "Whitelist", DiagnosticSeverity.Warning, true); Whitelist _whitelist = new Whitelist(); List<Uri> _ignoredFolders = new List<Uri>(); List<Uri> _ignoredFiles = new List<Uri>(); Uri _basePath; string _namespaceName; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create( ProhibitedMemberRule, ProhibitedLanguageElementRule, NoWhitelistCacheRule, NoOptionsRule, InconsistentNamespaceDeclarationRule); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(LoadWhitelist); } void LoadWhitelist(CompilationStartAnalysisContext context) { var mdkOptions = context.Options.AdditionalFiles.FirstOrDefault(file => Path.GetFileName(file.Path).Equals("mdk.options", StringComparison.CurrentCultureIgnoreCase)); if (mdkOptions == null || !LoadOptions(context, mdkOptions)) { context.RegisterSemanticModelAction(c => { var diagnostic = Diagnostic.Create(NoOptionsRule, c.SemanticModel.SyntaxTree.GetRoot().GetLocation()); c.ReportDiagnostic(diagnostic); }); _whitelist.IsEnabled = false; return; } var whitelistCache = context.Options.AdditionalFiles.FirstOrDefault(file => Path.GetFileName(file.Path).Equals("whitelist.cache", StringComparison.CurrentCultureIgnoreCase)); if (whitelistCache != null) { var content = whitelistCache.GetText(context.CancellationToken); _whitelist.IsEnabled = true; _whitelist.Load(content.Lines.Select(l => l.ToString()).ToArray()); } else { context.RegisterSemanticModelAction(c => { var diagnostic = Diagnostic.Create(NoWhitelistCacheRule, c.SemanticModel.SyntaxTree.GetRoot().GetLocation()); c.ReportDiagnostic(diagnostic); }); _whitelist.IsEnabled = false; return; } context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.AliasQualifiedName, SyntaxKind.QualifiedName, SyntaxKind.GenericName, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(AnalyzeDeclaration, SyntaxKind.PropertyDeclaration, SyntaxKind.VariableDeclaration, SyntaxKind.Parameter); context.RegisterSyntaxNodeAction(AnalyzeNamespace, SyntaxKind.ClassDeclaration); } void AnalyzeNamespace(SyntaxNodeAnalysisContext context) { if (IsIgnorableNode(context)) return; var classDeclaration = (ClassDeclarationSyntax)context.Node; if (classDeclaration.Parent is TypeDeclarationSyntax) return; var namespaceDeclaration = classDeclaration.Parent as NamespaceDeclarationSyntax; var namespaceName = namespaceDeclaration?.Name.ToString(); if (!_namespaceName.Equals(namespaceName, StringComparison.Ordinal)) { var diagnostic = Diagnostic.Create(InconsistentNamespaceDeclarationRule, namespaceDeclaration?.Name.GetLocation() ?? classDeclaration.Identifier.GetLocation(), _namespaceName); context.ReportDiagnostic(diagnostic); } } #pragma warning disable RS1012 // Start action has no registered actions. bool LoadOptions(CompilationStartAnalysisContext context, AdditionalText mdkOptions) #pragma warning restore RS1012 // Start action has no registered actions. { try { var content = mdkOptions.GetText(context.CancellationToken); var document = XDocument.Parse(content.ToString()); var ignoredFolders = document.Element("mdk")?.Elements("ignore").SelectMany(e => e.Elements("folder")); var ignoredFiles = document.Element("mdk")?.Elements("ignore").SelectMany(e => e.Elements("file")).ToArray(); var basePath = Path.GetDirectoryName(mdkOptions.Path).TrimEnd('\\') + "\\..\\"; if (!basePath.EndsWith("\\")) basePath += "\\"; _basePath = new Uri(basePath); _namespaceName = (string)document.Element("mdk")?.Element("namespace") ?? DefaultNamespaceName; _ignoredFolders.Clear(); _ignoredFiles.Clear(); if (ignoredFolders != null) { foreach (var folderElement in ignoredFolders) { var folder = folderElement.Value; if (!folder.EndsWith("\\")) _ignoredFolders.Add(new Uri(_basePath, new Uri(folder + "\\", UriKind.RelativeOrAbsolute))); else _ignoredFolders.Add(new Uri(_basePath, new Uri(folder, UriKind.RelativeOrAbsolute))); } } if (ignoredFiles != null) { foreach (var fileElement in ignoredFiles) { var file = fileElement.Value; _ignoredFiles.Add(new Uri(_basePath, new Uri(file, UriKind.RelativeOrAbsolute))); } } return true; } catch (Exception) { return false; } } void AnalyzeDeclaration(SyntaxNodeAnalysisContext context) { var node = context.Node; if (IsIgnorableNode(context)) return; if (!_whitelist.IsEnabled) { var diagnostic = Diagnostic.Create(NoOptionsRule, context.SemanticModel.SyntaxTree.GetRoot().GetLocation()); context.ReportDiagnostic(diagnostic); return; } IdentifierNameSyntax identifier; switch (node.Kind()) { case SyntaxKind.PropertyDeclaration: identifier = ((PropertyDeclarationSyntax)node).Type as IdentifierNameSyntax; break; case SyntaxKind.VariableDeclaration: identifier = ((VariableDeclarationSyntax)node).Type as IdentifierNameSyntax; break; case SyntaxKind.Parameter: identifier = ((ParameterSyntax)node).Type as IdentifierNameSyntax; break; default: identifier = null; break; } if (identifier == null) return; var name = identifier.Identifier.ToString(); if (name == "dynamic") { var diagnostic = Diagnostic.Create(ProhibitedLanguageElementRule, identifier.Identifier.GetLocation(), name); context.ReportDiagnostic(diagnostic); } } void Analyze(SyntaxNodeAnalysisContext context) { var node = context.Node; if (IsIgnorableNode(context)) return; if (!_whitelist.IsEnabled) { var diagnostic = Diagnostic.Create(NoOptionsRule, context.SemanticModel.SyntaxTree.GetRoot().GetLocation()); context.ReportDiagnostic(diagnostic); return; } // The exception finally clause cannot be allowed ingame because it can be used // to circumvent the instruction counter exception and crash the game if (node.Kind() == SyntaxKind.FinallyClause) { var kw = ((FinallyClauseSyntax)node).FinallyKeyword; var diagnostic = Diagnostic.Create(ProhibitedLanguageElementRule, kw.GetLocation(), kw.ToString()); context.ReportDiagnostic(diagnostic); return; } // We'll check the qualified names on their own. if (IsQualifiedName(node.Parent)) { //if (node.Ancestors().Any(IsQualifiedName)) return; } var info = context.SemanticModel.GetSymbolInfo(node); if (info.Symbol == null) { return; } // If they wrote it, they can have it. if (info.Symbol.IsInSource()) { return; } if (!_whitelist.IsWhitelisted(info.Symbol)) { var diagnostic = Diagnostic.Create(ProhibitedMemberRule, node.GetLocation(), info.Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); context.ReportDiagnostic(diagnostic); } } bool IsIgnorableNode(SyntaxNodeAnalysisContext context) { if (!_whitelist.IsEnabled || _whitelist.IsEmpty()) return true; var fileName = Path.GetFileName(context.Node.SyntaxTree.FilePath); if (string.IsNullOrWhiteSpace(fileName)) return true; if (fileName.Contains(".NETFramework,Version=")) return true; if (fileName.EndsWith(".debug", StringComparison.CurrentCultureIgnoreCase)) return true; if (fileName.IndexOf(".debug.", StringComparison.CurrentCultureIgnoreCase) >= 0) return true; if (_basePath == null) return false; var uri = new Uri(_basePath, new Uri(context.Node.SyntaxTree.FilePath, UriKind.RelativeOrAbsolute)); foreach (var ignoredUri in _ignoredFiles) { if (string.Equals(uri.AbsolutePath, ignoredUri.AbsolutePath, StringComparison.CurrentCultureIgnoreCase)) return true; } foreach (var ignoredUri in _ignoredFolders) { if (uri.AbsolutePath.StartsWith(ignoredUri.AbsolutePath, StringComparison.CurrentCultureIgnoreCase)) return true; } return false; } bool IsQualifiedName(SyntaxNode arg) { switch (arg.Kind()) { case SyntaxKind.QualifiedName: case SyntaxKind.AliasQualifiedName: return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System.Tests { public partial class StringTests { [Theory] [InlineData(0, 0)] [InlineData(3, 1)] public static void Ctor_CharSpan_EmptyString(int length, int offset) { Assert.Same(string.Empty, new string(new ReadOnlySpan<char>(new char[length], offset, 0))); } [Fact] public static unsafe void Ctor_CharSpan_Empty() { Assert.Same(string.Empty, new string((ReadOnlySpan<char>)null)); Assert.Same(string.Empty, new string(ReadOnlySpan<char>.Empty)); } [Theory] [InlineData(new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0' }, 0, 8, "abcdefgh")] [InlineData(new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0', 'i', 'j', 'k' }, 0, 12, "abcdefgh\0ijk")] [InlineData(new char[] { 'a', 'b', 'c' }, 0, 0, "")] [InlineData(new char[] { 'a', 'b', 'c' }, 0, 1, "a")] [InlineData(new char[] { 'a', 'b', 'c' }, 2, 1, "c")] [InlineData(new char[] { '\u8001', '\u8002', '\ufffd', '\u1234', '\ud800', '\udfff' }, 0, 6, "\u8001\u8002\ufffd\u1234\ud800\udfff")] public static void Ctor_CharSpan(char[] valueArray, int startIndex, int length, string expected) { var span = new ReadOnlySpan<char>(valueArray, startIndex, length); Assert.Equal(expected, new string(span)); } [Fact] public static unsafe void Ctor_CharPtr_DoesNotAccessInvalidPage() { // Allocates a buffer of all 'x' followed by a null terminator, // then attempts to create a string instance from this at various offsets. const int MaxCharCount = 128; using BoundedMemory<char> boundedMemory = BoundedMemory.Allocate<char>(MaxCharCount); boundedMemory.Span.Fill('x'); boundedMemory.Span[MaxCharCount - 1] = '\0'; boundedMemory.MakeReadonly(); using MemoryHandle memoryHandle = boundedMemory.Memory.Pin(); for (int i = 0; i < MaxCharCount; i++) { string expectedString = new string('x', MaxCharCount - i - 1); string actualString = new string((char*)memoryHandle.Pointer + i); Assert.Equal(expectedString, actualString); } } [ConditionalFact(nameof(IsSimpleActiveCodePage))] public static unsafe void Ctor_SBytePtr_DoesNotAccessInvalidPage() { // Allocates a buffer of all ' ' followed by a null terminator, // then attempts to create a string instance from this at various offsets. // We use U+0020 SPACE instead of any other character because it lives // at offset 0x20 across every supported code page. const int MaxByteCount = 128; using BoundedMemory<sbyte> boundedMemory = BoundedMemory.Allocate<sbyte>(MaxByteCount); boundedMemory.Span.Fill((sbyte)' '); boundedMemory.Span[MaxByteCount - 1] = (sbyte)'\0'; boundedMemory.MakeReadonly(); using MemoryHandle memoryHandle = boundedMemory.Memory.Pin(); for (int i = 0; i < MaxByteCount; i++) { string expectedString = new string(' ', MaxByteCount - i - 1); string actualString = new string((sbyte*)memoryHandle.Pointer + i); Assert.Equal(expectedString, actualString); } } [Fact] public static void Create_InvalidArguments_Throw() { AssertExtensions.Throws<ArgumentNullException>("action", () => string.Create(-1, 0, null)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => string.Create(-1, 0, (span, state) => { })); } [Fact] public static void Create_Length0_ReturnsEmptyString() { bool actionInvoked = false; Assert.Same(string.Empty, string.Create(0, 0, (span, state) => actionInvoked = true)); Assert.False(actionInvoked); } [Fact] public static void Create_NullState_Allowed() { string result = string.Create(1, (object)null, (span, state) => { span[0] = 'a'; Assert.Null(state); }); Assert.Equal("a", result); } [Fact] public static void Create_ClearsMemory() { const int Length = 10; string result = string.Create(Length, (object)null, (span, state) => { for (int i = 0; i < span.Length; i++) { Assert.Equal('\0', span[i]); } }); Assert.Equal(new string('\0', Length), result); } [Theory] [InlineData("a")] [InlineData("this is a test")] [InlineData("\0\u8001\u8002\ufffd\u1234\ud800\udfff")] public static void Create_ReturnsExpectedString(string expected) { char[] input = expected.ToCharArray(); string result = string.Create(input.Length, input, (span, state) => { Assert.Same(input, state); for (int i = 0; i < state.Length; i++) { span[i] = state[i]; } }); Assert.Equal(expected, result); } [Theory] [InlineData("Hello", 'H', true)] [InlineData("Hello", 'Z', false)] [InlineData("Hello", 'e', true)] [InlineData("Hello", 'E', false)] [InlineData("", 'H', false)] public static void Contains(string s, char value, bool expected) { Assert.Equal(expected, s.Contains(value)); ReadOnlySpan<char> span = s.AsSpan(); Assert.Equal(expected, span.Contains(value)); } [Theory] // CurrentCulture [InlineData("Hello", 'H', StringComparison.CurrentCulture, true)] [InlineData("Hello", 'Z', StringComparison.CurrentCulture, false)] [InlineData("Hello", 'e', StringComparison.CurrentCulture, true)] [InlineData("Hello", 'E', StringComparison.CurrentCulture, false)] [InlineData("", 'H', StringComparison.CurrentCulture, false)] // CurrentCultureIgnoreCase [InlineData("Hello", 'H', StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", 'Z', StringComparison.CurrentCultureIgnoreCase, false)] [InlineData("Hello", 'e', StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", 'E', StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("", 'H', StringComparison.CurrentCultureIgnoreCase, false)] // InvariantCulture [InlineData("Hello", 'H', StringComparison.InvariantCulture, true)] [InlineData("Hello", 'Z', StringComparison.InvariantCulture, false)] [InlineData("Hello", 'e', StringComparison.InvariantCulture, true)] [InlineData("Hello", 'E', StringComparison.InvariantCulture, false)] [InlineData("", 'H', StringComparison.InvariantCulture, false)] // InvariantCultureIgnoreCase [InlineData("Hello", 'H', StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", 'Z', StringComparison.InvariantCultureIgnoreCase, false)] [InlineData("Hello", 'e', StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", 'E', StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("", 'H', StringComparison.InvariantCultureIgnoreCase, false)] // Ordinal [InlineData("Hello", 'H', StringComparison.Ordinal, true)] [InlineData("Hello", 'Z', StringComparison.Ordinal, false)] [InlineData("Hello", 'e', StringComparison.Ordinal, true)] [InlineData("Hello", 'E', StringComparison.Ordinal, false)] [InlineData("", 'H', StringComparison.Ordinal, false)] // OrdinalIgnoreCase [InlineData("Hello", 'H', StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", 'Z', StringComparison.OrdinalIgnoreCase, false)] [InlineData("Hello", 'e', StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", 'E', StringComparison.OrdinalIgnoreCase, true)] [InlineData("", 'H', StringComparison.OrdinalIgnoreCase, false)] public static void Contains(string s, char value, StringComparison comparisionType, bool expected) { Assert.Equal(expected, s.Contains(value, comparisionType)); } [Theory] // CurrentCulture [InlineData("Hello", "ello", StringComparison.CurrentCulture, true)] [InlineData("Hello", "ELL", StringComparison.CurrentCulture, false)] [InlineData("Hello", "ElLo", StringComparison.CurrentCulture, false)] [InlineData("Hello", "Larger Hello", StringComparison.CurrentCulture, false)] [InlineData("Hello", "Goodbye", StringComparison.CurrentCulture, false)] [InlineData("", "", StringComparison.CurrentCulture, true)] [InlineData("", "hello", StringComparison.CurrentCulture, false)] [InlineData("Hello", "", StringComparison.CurrentCulture, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.CurrentCulture, true)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.CurrentCulture, false)] // CurrentCultureIgnoreCase [InlineData("Hello", "ello", StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", "ELL", StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", "ElLo", StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", "Larger Hello", StringComparison.CurrentCultureIgnoreCase, false)] [InlineData("Hello", "Goodbye", StringComparison.CurrentCultureIgnoreCase, false)] [InlineData("", "", StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("", "hello", StringComparison.CurrentCultureIgnoreCase, false)] [InlineData("Hello", "", StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.CurrentCultureIgnoreCase, true)] // InvariantCulture [InlineData("Hello", "ello", StringComparison.InvariantCulture, true)] [InlineData("Hello", "ELL", StringComparison.InvariantCulture, false)] [InlineData("Hello", "ElLo", StringComparison.InvariantCulture, false)] [InlineData("Hello", "Larger Hello", StringComparison.InvariantCulture, false)] [InlineData("Hello", "Goodbye", StringComparison.InvariantCulture, false)] [InlineData("", "", StringComparison.InvariantCulture, true)] [InlineData("", "hello", StringComparison.InvariantCulture, false)] [InlineData("Hello", "", StringComparison.InvariantCulture, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.InvariantCulture, true)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.InvariantCulture, false)] // InvariantCultureIgnoreCase [InlineData("Hello", "ello", StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", "ELL", StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", "ElLo", StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", "Larger Hello", StringComparison.InvariantCultureIgnoreCase, false)] [InlineData("Hello", "Goodbye", StringComparison.InvariantCultureIgnoreCase, false)] [InlineData("", "", StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("", "hello", StringComparison.InvariantCultureIgnoreCase, false)] [InlineData("Hello", "", StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.InvariantCultureIgnoreCase, true)] // Ordinal [InlineData("Hello", "ello", StringComparison.Ordinal, true)] [InlineData("Hello", "ELL", StringComparison.Ordinal, false)] [InlineData("Hello", "ElLo", StringComparison.Ordinal, false)] [InlineData("Hello", "Larger Hello", StringComparison.Ordinal, false)] [InlineData("Hello", "Goodbye", StringComparison.Ordinal, false)] [InlineData("", "", StringComparison.Ordinal, true)] [InlineData("", "hello", StringComparison.Ordinal, false)] [InlineData("Hello", "", StringComparison.Ordinal, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.Ordinal, false)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.Ordinal, false)] // OrdinalIgnoreCase [InlineData("Hello", "ello", StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", "ELL", StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", "ElLo", StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", "Larger Hello", StringComparison.OrdinalIgnoreCase, false)] [InlineData("Hello", "Goodbye", StringComparison.OrdinalIgnoreCase, false)] [InlineData("", "", StringComparison.OrdinalIgnoreCase, true)] [InlineData("", "hello", StringComparison.OrdinalIgnoreCase, false)] [InlineData("Hello", "", StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.OrdinalIgnoreCase, false)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.OrdinalIgnoreCase, false)] public static void Contains(string s, string value, StringComparison comparisonType, bool expected) { Assert.Equal(expected, s.Contains(value, comparisonType)); Assert.Equal(expected, s.AsSpan().Contains(value, comparisonType)); } [Fact] public static void Contains_StringComparison_TurkishI() { string str = "\u0069\u0130"; RemoteInvoke((source) => { CultureInfo.CurrentCulture = new CultureInfo("tr-TR"); Assert.True(source.Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase)); Assert.True(source.AsSpan().Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }, str).Dispose(); RemoteInvoke((source) => { CultureInfo.CurrentCulture = new CultureInfo("en-US"); Assert.False(source.Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase)); Assert.False(source.AsSpan().Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }, str).Dispose(); } [Fact] public static void Contains_Match_Char() { Assert.False("".Contains('a')); Assert.False("".AsSpan().Contains('a')); // Use a long-enough string to incur vectorization code const int max = 250; for (var length = 1; length < max; length++) { char[] ca = new char[length]; for (int i = 0; i < length; i++) { ca[i] = (char)(i + 1); } var span = new Span<char>(ca); var ros = new ReadOnlySpan<char>(ca); var str = new string(ca); for (var targetIndex = 0; targetIndex < length; targetIndex++) { char target = ca[targetIndex]; // Span bool found = span.Contains(target); Assert.True(found); // ReadOnlySpan found = ros.Contains(target); Assert.True(found); // String found = str.Contains(target); Assert.True(found); } } } [Fact] public static void Contains_ZeroLength_Char() { // Span var span = new Span<char>(Array.Empty<char>()); bool found = span.Contains((char)0); Assert.False(found); span = Span<char>.Empty; found = span.Contains((char)0); Assert.False(found); // ReadOnlySpan var ros = new ReadOnlySpan<char>(Array.Empty<char>()); found = ros.Contains((char)0); Assert.False(found); ros = ReadOnlySpan<char>.Empty; found = ros.Contains((char)0); Assert.False(found); // String found = string.Empty.Contains((char)0); Assert.False(found); } [Fact] public static void Contains_MultipleMatches_Char() { for (int length = 2; length < 32; length++) { var ca = new char[length]; for (int i = 0; i < length; i++) { ca[i] = (char)(i + 1); } ca[length - 1] = (char)200; ca[length - 2] = (char)200; // Span var span = new Span<char>(ca); bool found = span.Contains((char)200); Assert.True(found); // ReadOnlySpan var ros = new ReadOnlySpan<char>(ca); found = ros.Contains((char)200); Assert.True(found); // String var str = new string(ca); found = str.Contains((char)200); Assert.True(found); } } [Fact] public static void Contains_EnsureNoChecksGoOutOfRange_Char() { for (int length = 0; length < 100; length++) { var ca = new char[length + 2]; ca[0] = '9'; ca[length + 1] = '9'; // Span var span = new Span<char>(ca, 1, length); bool found = span.Contains('9'); Assert.False(found); // ReadOnlySpan var ros = new ReadOnlySpan<char>(ca, 1, length); found = ros.Contains('9'); Assert.False(found); // String var str = new string(ca, 1, length); found = str.Contains('9'); Assert.False(found); } } [Theory] [InlineData(StringComparison.CurrentCulture)] [InlineData(StringComparison.CurrentCultureIgnoreCase)] [InlineData(StringComparison.InvariantCulture)] [InlineData(StringComparison.InvariantCultureIgnoreCase)] [InlineData(StringComparison.Ordinal)] [InlineData(StringComparison.OrdinalIgnoreCase)] public static void Contains_NullValue_ThrowsArgumentNullException(StringComparison comparisonType) { AssertExtensions.Throws<ArgumentNullException>("value", () => "foo".Contains(null, comparisonType)); } [Theory] [InlineData(StringComparison.CurrentCulture - 1)] [InlineData(StringComparison.OrdinalIgnoreCase + 1)] public static void Contains_InvalidComparisonType_ThrowsArgumentOutOfRangeException(StringComparison comparisonType) { AssertExtensions.Throws<ArgumentException>("comparisonType", () => "ab".Contains("a", comparisonType)); } [Theory] [InlineData("Hello", 'o', true)] [InlineData("Hello", 'O', false)] [InlineData("o", 'o', true)] [InlineData("o", 'O', false)] [InlineData("Hello", 'e', false)] [InlineData("Hello", '\0', false)] [InlineData("", '\0', false)] [InlineData("\0", '\0', true)] [InlineData("", 'a', false)] [InlineData("abcdefghijklmnopqrstuvwxyz", 'z', true)] public static void EndsWith(string s, char value, bool expected) { Assert.Equal(expected, s.EndsWith(value)); } [Theory] [InlineData(new char[0], new int[0])] // empty [InlineData(new char[] { 'x', 'y', 'z' }, new int[] { 'x', 'y', 'z' })] [InlineData(new char[] { 'x', '\uD86D', '\uDF54', 'y' }, new int[] { 'x', 0x2B754, 'y' })] // valid surrogate pair [InlineData(new char[] { 'x', '\uD86D', 'y' }, new int[] { 'x', 0xFFFD, 'y' })] // standalone high surrogate [InlineData(new char[] { 'x', '\uDF54', 'y' }, new int[] { 'x', 0xFFFD, 'y' })] // standalone low surrogate [InlineData(new char[] { 'x', '\uD86D' }, new int[] { 'x', 0xFFFD })] // standalone high surrogate at end of string [InlineData(new char[] { 'x', '\uDF54' }, new int[] { 'x', 0xFFFD })] // standalone low surrogate at end of string [InlineData(new char[] { 'x', '\uD86D', '\uD86D', 'y' }, new int[] { 'x', 0xFFFD, 0xFFFD, 'y' })] // two high surrogates should be two replacement chars [InlineData(new char[] { 'x', '\uFFFD', 'y' }, new int[] { 'x', 0xFFFD, 'y' })] // literal U+FFFD public static void EnumerateRunes(char[] chars, int[] expected) { // Test data is smuggled as char[] instead of straight-up string since the test framework // doesn't like invalid UTF-16 literals. string asString = new string(chars); // First, use a straight-up foreach keyword to ensure pattern matching works as expected List<int> enumeratedScalarValues = new List<int>(); foreach (Rune rune in asString.EnumerateRunes()) { enumeratedScalarValues.Add(rune.Value); } Assert.Equal(expected, enumeratedScalarValues.ToArray()); // Then use LINQ to ensure IEnumerator<...> works as expected int[] enumeratedValues = new string(chars).EnumerateRunes().Select(r => r.Value).ToArray(); Assert.Equal(expected, enumeratedValues); } [Theory] [InlineData("Hello", 'H', true)] [InlineData("Hello", 'h', false)] [InlineData("H", 'H', true)] [InlineData("H", 'h', false)] [InlineData("Hello", 'e', false)] [InlineData("Hello", '\0', false)] [InlineData("", '\0', false)] [InlineData("\0", '\0', true)] [InlineData("", 'a', false)] [InlineData("abcdefghijklmnopqrstuvwxyz", 'a', true)] public static void StartsWith(string s, char value, bool expected) { Assert.Equal(expected, s.StartsWith(value)); } public static IEnumerable<object[]> Join_Char_StringArray_TestData() { yield return new object[] { '|', new string[0], 0, 0, "" }; yield return new object[] { '|', new string[] { "a" }, 0, 1, "a" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 3, "a|b|c" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 2, "a|b" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 1, 1, "b" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 1, 2, "b|c" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 3, 0, "" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 0, "" }; yield return new object[] { '|', new string[] { "", "", "" }, 0, 3, "||" }; yield return new object[] { '|', new string[] { null, null, null }, 0, 3, "||" }; } [Theory] [MemberData(nameof(Join_Char_StringArray_TestData))] public static void Join_Char_StringArray(char separator, string[] values, int startIndex, int count, string expected) { if (startIndex == 0 && count == values.Length) { Assert.Equal(expected, string.Join(separator, values)); Assert.Equal(expected, string.Join(separator, (IEnumerable<string>)values)); Assert.Equal(expected, string.Join(separator, (object[])values)); Assert.Equal(expected, string.Join(separator, (IEnumerable<object>)values)); } Assert.Equal(expected, string.Join(separator, values, startIndex, count)); Assert.Equal(expected, string.Join(separator.ToString(), values, startIndex, count)); } public static IEnumerable<object[]> Join_Char_ObjectArray_TestData() { yield return new object[] { '|', new object[0], "" }; yield return new object[] { '|', new object[] { 1 }, "1" }; yield return new object[] { '|', new object[] { 1, 2, 3 }, "1|2|3" }; yield return new object[] { '|', new object[] { new ObjectWithNullToString(), 2, new ObjectWithNullToString() }, "|2|" }; yield return new object[] { '|', new object[] { "1", null, "3" }, "1||3" }; yield return new object[] { '|', new object[] { "", "", "" }, "||" }; yield return new object[] { '|', new object[] { "", null, "" }, "||" }; yield return new object[] { '|', new object[] { null, null, null }, "||" }; } [Theory] [MemberData(nameof(Join_Char_ObjectArray_TestData))] public static void Join_Char_ObjectArray(char separator, object[] values, string expected) { Assert.Equal(expected, string.Join(separator, values)); Assert.Equal(expected, string.Join(separator, (IEnumerable<object>)values)); } [Fact] public static void Join_Char_NullValues_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => string.Join('|', (string[])null)); AssertExtensions.Throws<ArgumentNullException>("value", () => string.Join('|', (string[])null, 0, 0)); AssertExtensions.Throws<ArgumentNullException>("values", () => string.Join('|', (object[])null)); AssertExtensions.Throws<ArgumentNullException>("values", () => string.Join('|', (IEnumerable<object>)null)); } [Fact] public static void Join_Char_NegativeStartIndex_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => string.Join('|', new string[] { "Foo" }, -1, 0)); } [Fact] public static void Join_Char_NegativeCount_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => string.Join('|', new string[] { "Foo" }, 0, -1)); } [Theory] [InlineData(2, 1)] [InlineData(2, 0)] [InlineData(1, 2)] [InlineData(1, 1)] [InlineData(0, 2)] [InlineData(-1, 0)] public static void Join_Char_InvalidStartIndexCount_ThrowsArgumentOutOfRangeException(int startIndex, int count) { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => string.Join('|', new string[] { "Foo" }, startIndex, count)); } public static IEnumerable<object[]> Replace_StringComparison_TestData() { yield return new object[] { "abc", "abc", "def", StringComparison.CurrentCulture, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.CurrentCulture, "abc" }; yield return new object[] { "abc", "abc", "", StringComparison.CurrentCulture, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.CurrentCulture, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.CurrentCulture, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.CurrentCulture, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.CurrentCulture, "def" }; yield return new object[] { "abc", "abc", "def", StringComparison.CurrentCultureIgnoreCase, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.CurrentCultureIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "", StringComparison.CurrentCultureIgnoreCase, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.CurrentCultureIgnoreCase, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.CurrentCultureIgnoreCase, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.CurrentCultureIgnoreCase, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.CurrentCultureIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "def", StringComparison.Ordinal, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.Ordinal, "abc" }; yield return new object[] { "abc", "abc", "", StringComparison.Ordinal, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.Ordinal, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.Ordinal, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.Ordinal, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.Ordinal, "abc" }; yield return new object[] { "abc", "abc", "def", StringComparison.OrdinalIgnoreCase, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.OrdinalIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "", StringComparison.OrdinalIgnoreCase, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.OrdinalIgnoreCase, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.OrdinalIgnoreCase, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.OrdinalIgnoreCase, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.OrdinalIgnoreCase, "abc" }; yield return new object[] { "abc", "abc", "def", StringComparison.InvariantCulture, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.InvariantCulture, "abc" }; yield return new object[] { "abc", "abc", "", StringComparison.InvariantCulture, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.InvariantCulture, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.InvariantCulture, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.InvariantCulture, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.InvariantCulture, "def" }; yield return new object[] { "abc", "abc", "def", StringComparison.InvariantCultureIgnoreCase, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.InvariantCultureIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "", StringComparison.InvariantCultureIgnoreCase, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.InvariantCultureIgnoreCase, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.InvariantCultureIgnoreCase, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.InvariantCultureIgnoreCase, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.InvariantCultureIgnoreCase, "def" }; string turkishSource = "\u0069\u0130"; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.Ordinal, "a\u0130" }; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.OrdinalIgnoreCase, "a\u0130" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.Ordinal, "\u0069a" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.OrdinalIgnoreCase, "\u0069a" }; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.InvariantCulture, "a\u0130" }; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.InvariantCultureIgnoreCase, "a\u0130" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.InvariantCulture, "\u0069a" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.InvariantCultureIgnoreCase, "\u0069a" }; } [Theory] [MemberData(nameof(Replace_StringComparison_TestData))] public void Replace_StringComparison_ReturnsExpected(string original, string oldValue, string newValue, StringComparison comparisonType, string expected) { Assert.Equal(expected, original.Replace(oldValue, newValue, comparisonType)); } [Fact] public void Replace_StringComparison_TurkishI() { string src = "\u0069\u0130"; RemoteInvoke((source) => { CultureInfo.CurrentCulture = new CultureInfo("tr-TR"); Assert.True("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture)); Assert.Equal("aa", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture)); Assert.Equal("aa", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }, src).Dispose(); RemoteInvoke((source) => { CultureInfo.CurrentCulture = new CultureInfo("en-US"); Assert.False("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture)); Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture)); Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }, src).Dispose(); } public static IEnumerable<object[]> Replace_StringComparisonCulture_TestData() { yield return new object[] { "abc", "abc", "def", false, null, "def" }; yield return new object[] { "abc", "ABC", "def", false, null, "abc" }; yield return new object[] { "abc", "abc", "def", false, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "ABC", "def", false, CultureInfo.InvariantCulture, "abc" }; yield return new object[] { "abc", "abc", "def", true, null, "def" }; yield return new object[] { "abc", "ABC", "def", true, null, "def" }; yield return new object[] { "abc", "abc", "def", true, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "ABC", "def", true, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", false, null, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", true, null, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", false, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", true, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", false, new CultureInfo("tr-TR"), "a\u0130" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", true, new CultureInfo("tr-TR"), "aa" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", false, CultureInfo.InvariantCulture, "a\u0130" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", true, CultureInfo.InvariantCulture, "a\u0130" }; } [Theory] [MemberData(nameof(Replace_StringComparisonCulture_TestData))] public void Replace_StringComparisonCulture_ReturnsExpected(string original, string oldValue, string newValue, bool ignoreCase, CultureInfo culture, string expected) { Assert.Equal(expected, original.Replace(oldValue, newValue, ignoreCase, culture)); if (culture == null) { Assert.Equal(expected, original.Replace(oldValue, newValue, ignoreCase, CultureInfo.CurrentCulture)); } } [Fact] public void Replace_StringComparison_NullOldValue_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentNullException>("oldValue", () => "abc".Replace(null, "def", StringComparison.CurrentCulture)); AssertExtensions.Throws<ArgumentNullException>("oldValue", () => "abc".Replace(null, "def", true, CultureInfo.CurrentCulture)); } [Fact] public void Replace_StringComparison_EmptyOldValue_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("oldValue", () => "abc".Replace("", "def", StringComparison.CurrentCulture)); AssertExtensions.Throws<ArgumentException>("oldValue", () => "abc".Replace("", "def", true, CultureInfo.CurrentCulture)); } [Theory] [InlineData(StringComparison.CurrentCulture - 1)] [InlineData(StringComparison.OrdinalIgnoreCase + 1)] public void Replace_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType) { AssertExtensions.Throws<ArgumentException>("comparisonType", () => "abc".Replace("abc", "def", comparisonType)); } private static readonly StringComparison[] StringComparisons = (StringComparison[])Enum.GetValues(typeof(StringComparison)); [Fact] public static void GetHashCode_OfSpan_EmbeddedNull_ReturnsDifferentHashCodes() { Assert.NotEqual(string.GetHashCode("\0AAAAAAAAA".AsSpan()), string.GetHashCode("\0BBBBBBBBBBBB".AsSpan())); } [Fact] public static void GetHashCode_OfSpan_MatchesOfString() { // parameterless should be ordinal only Assert.Equal("abc".GetHashCode(), string.GetHashCode("abc".AsSpan())); Assert.NotEqual("abc".GetHashCode(), string.GetHashCode("ABC".AsSpan())); // case differences } [Fact] public static void GetHashCode_CompareInfo() { // ordinal Assert.Equal("abc".GetHashCode(), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("abc", CompareOptions.Ordinal)); Assert.NotEqual("abc".GetHashCode(), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("ABC", CompareOptions.Ordinal)); // ordinal ignore case Assert.Equal("abc".GetHashCode(StringComparison.OrdinalIgnoreCase), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("abc", CompareOptions.OrdinalIgnoreCase)); Assert.Equal("abc".GetHashCode(StringComparison.OrdinalIgnoreCase), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("ABC", CompareOptions.OrdinalIgnoreCase)); // culture-aware Assert.Equal("aeiXXabc".GetHashCode(StringComparison.CurrentCulture), CultureInfo.CurrentCulture.CompareInfo.GetHashCode("aeiXXabc", CompareOptions.None)); Assert.Equal("aeiXXabc".GetHashCode(StringComparison.CurrentCultureIgnoreCase), CultureInfo.CurrentCulture.CompareInfo.GetHashCode("aeiXXabc", CompareOptions.IgnoreCase)); // invariant culture Assert.Equal("aeiXXabc".GetHashCode(StringComparison.InvariantCulture), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("aeiXXabc", CompareOptions.None)); Assert.Equal("aeiXXabc".GetHashCode(StringComparison.InvariantCultureIgnoreCase), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("aeiXXabc", CompareOptions.IgnoreCase)); } [Fact] public static void GetHashCode_CompareInfo_OfSpan() { // ordinal Assert.Equal("abc".GetHashCode(), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("abc".AsSpan(), CompareOptions.Ordinal)); Assert.NotEqual("abc".GetHashCode(), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("ABC".AsSpan(), CompareOptions.Ordinal)); // ordinal ignore case Assert.Equal("abc".GetHashCode(StringComparison.OrdinalIgnoreCase), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("abc".AsSpan(), CompareOptions.OrdinalIgnoreCase)); Assert.Equal("abc".GetHashCode(StringComparison.OrdinalIgnoreCase), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("ABC".AsSpan(), CompareOptions.OrdinalIgnoreCase)); // culture-aware Assert.Equal("aeiXXabc".GetHashCode(StringComparison.CurrentCulture), CultureInfo.CurrentCulture.CompareInfo.GetHashCode("aeiXXabc".AsSpan(), CompareOptions.None)); Assert.Equal("aeiXXabc".GetHashCode(StringComparison.CurrentCultureIgnoreCase), CultureInfo.CurrentCulture.CompareInfo.GetHashCode("aeiXXabc".AsSpan(), CompareOptions.IgnoreCase)); // invariant culture Assert.Equal("aeiXXabc".GetHashCode(StringComparison.InvariantCulture), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("aeiXXabc".AsSpan(), CompareOptions.None)); Assert.Equal("aeiXXabc".GetHashCode(StringComparison.InvariantCultureIgnoreCase), CultureInfo.InvariantCulture.CompareInfo.GetHashCode("aeiXXabc".AsSpan(), CompareOptions.IgnoreCase)); } public static IEnumerable<object[]> GetHashCode_StringComparison_Data => StringComparisons.Select(value => new object[] { value }); [Theory] [MemberData(nameof(GetHashCode_StringComparison_Data))] public static void GetHashCode_StringComparison(StringComparison comparisonType) { int hashCodeFromStringComparer = StringComparer.FromComparison(comparisonType).GetHashCode("abc"); int hashCodeFromStringGetHashCode = "abc".GetHashCode(comparisonType); int hashCodeFromStringGetHashCodeOfSpan = string.GetHashCode("abc".AsSpan(), comparisonType); Assert.Equal(hashCodeFromStringComparer, hashCodeFromStringGetHashCode); Assert.Equal(hashCodeFromStringComparer, hashCodeFromStringGetHashCodeOfSpan); } public static IEnumerable<object[]> GetHashCode_NoSuchStringComparison_ThrowsArgumentException_Data => new[] { new object[] { StringComparisons.Min() - 1 }, new object[] { StringComparisons.Max() + 1 }, }; [Theory] [MemberData(nameof(GetHashCode_NoSuchStringComparison_ThrowsArgumentException_Data))] public static void GetHashCode_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType) { AssertExtensions.Throws<ArgumentException>("comparisonType", () => "abc".GetHashCode(comparisonType)); AssertExtensions.Throws<ArgumentException>("comparisonType", () => string.GetHashCode("abc".AsSpan(), comparisonType)); } [Theory] [InlineData("")] [InlineData("a")] [InlineData("\0")] [InlineData("abc")] public static unsafe void ImplicitCast_ResultingSpanMatches(string s) { ReadOnlySpan<char> span = s; Assert.Equal(s.Length, span.Length); fixed (char* stringPtr = s) fixed (char* spanPtr = &MemoryMarshal.GetReference(span)) { Assert.Equal((IntPtr)stringPtr, (IntPtr)spanPtr); } } [Fact] public static void ImplicitCast_NullString_ReturnsDefaultSpan() { ReadOnlySpan<char> span = (string)null; Assert.True(span == default); } [Theory] [InlineData("Hello", 'l', StringComparison.Ordinal, 2)] [InlineData("Hello", 'x', StringComparison.Ordinal, -1)] [InlineData("Hello", 'h', StringComparison.Ordinal, -1)] [InlineData("Hello", 'o', StringComparison.Ordinal, 4)] [InlineData("Hello", 'h', StringComparison.OrdinalIgnoreCase, 0)] [InlineData("HelLo", 'L', StringComparison.OrdinalIgnoreCase, 2)] [InlineData("HelLo", 'L', StringComparison.Ordinal, 3)] [InlineData("HelLo", '\0', StringComparison.Ordinal, -1)] [InlineData("!@#$%", '%', StringComparison.Ordinal, 4)] [InlineData("!@#$", '!', StringComparison.Ordinal, 0)] [InlineData("!@#$", '@', StringComparison.Ordinal, 1)] [InlineData("!@#$%", '%', StringComparison.OrdinalIgnoreCase, 4)] [InlineData("!@#$", '!', StringComparison.OrdinalIgnoreCase, 0)] [InlineData("!@#$", '@', StringComparison.OrdinalIgnoreCase, 1)] [InlineData("_____________\u807f", '\u007f', StringComparison.Ordinal, -1)] [InlineData("_____________\u807f__", '\u007f', StringComparison.Ordinal, -1)] [InlineData("_____________\u807f\u007f_", '\u007f', StringComparison.Ordinal, 14)] [InlineData("__\u807f_______________", '\u007f', StringComparison.Ordinal, -1)] [InlineData("__\u807f___\u007f___________", '\u007f', StringComparison.Ordinal, 6)] [InlineData("_____________\u807f", '\u007f', StringComparison.OrdinalIgnoreCase, -1)] [InlineData("_____________\u807f__", '\u007f', StringComparison.OrdinalIgnoreCase, -1)] [InlineData("_____________\u807f\u007f_", '\u007f', StringComparison.OrdinalIgnoreCase, 14)] [InlineData("__\u807f_______________", '\u007f', StringComparison.OrdinalIgnoreCase, -1)] [InlineData("__\u807f___\u007f___________", '\u007f', StringComparison.OrdinalIgnoreCase, 6)] public static void IndexOf_SingleLetter(string s, char target, StringComparison stringComparison, int expected) { Assert.Equal(expected, s.IndexOf(target, stringComparison)); var charArray = new char[1]; charArray[0] = target; Assert.Equal(expected, s.AsSpan().IndexOf(charArray, stringComparison)); } [Fact] public static void IndexOf_TurkishI_TurkishCulture_Char() { RemoteInvoke(() => { CultureInfo.CurrentCulture = new CultureInfo("tr-TR"); string s = "Turkish I \u0131s TROUBL\u0130NG!"; char value = '\u0130'; Assert.Equal(19, s.IndexOf(value)); Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(19, s.IndexOf(value, StringComparison.Ordinal)); Assert.Equal(19, s.IndexOf(value, StringComparison.OrdinalIgnoreCase)); ReadOnlySpan<char> span = s.AsSpan(); Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.CurrentCulture)); Assert.Equal(4, span.IndexOf(new char[] { value }, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.Ordinal)); Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.OrdinalIgnoreCase)); value = '\u0131'; Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal)); Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase)); Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.CurrentCulture)); Assert.Equal(8, span.IndexOf(new char[] { value }, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.Ordinal)); Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.OrdinalIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_TurkishI_InvariantCulture_Char() { RemoteInvoke(() => { CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; string s = "Turkish I \u0131s TROUBL\u0130NG!"; char value = '\u0130'; Assert.Equal(19, s.IndexOf(value)); Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); value = '\u0131'; Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_TurkishI_EnglishUSCulture_Char() { RemoteInvoke(() => { CultureInfo.CurrentCulture = new CultureInfo("en-US"); string s = "Turkish I \u0131s TROUBL\u0130NG!"; char value = '\u0130'; Assert.Equal(19, s.IndexOf(value)); Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); value = '\u0131'; Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_EquivalentDiacritics_EnglishUSCulture_Char() { RemoteInvoke(() => { string s = "Exhibit a\u0300\u00C0"; char value = '\u00C0'; CultureInfo.CurrentCulture = new CultureInfo("en-US"); Assert.Equal(10, s.IndexOf(value)); Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal)); Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_EquivalentDiacritics_InvariantCulture_Char() { RemoteInvoke(() => { string s = "Exhibit a\u0300\u00C0"; char value = '\u00C0'; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal(10, s.IndexOf(value)); Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_CyrillicE_EnglishUSCulture_Char() { RemoteInvoke(() => { string s = "Foo\u0400Bar"; char value = '\u0400'; CultureInfo.CurrentCulture = new CultureInfo("en-US"); Assert.Equal(3, s.IndexOf(value)); Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(3, s.IndexOf(value, StringComparison.Ordinal)); Assert.Equal(3, s.IndexOf(value, StringComparison.OrdinalIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_CyrillicE_InvariantCulture_Char() { RemoteInvoke(() => { string s = "Foo\u0400Bar"; char value = '\u0400'; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal(3, s.IndexOf(value)); Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_Invalid_Char() { // Invalid comparison type AssertExtensions.Throws<ArgumentException>("comparisonType", () => "foo".IndexOf('o', StringComparison.CurrentCulture - 1)); AssertExtensions.Throws<ArgumentException>("comparisonType", () => "foo".IndexOf('o', StringComparison.OrdinalIgnoreCase + 1)); } [Theory] [MemberData(nameof(Concat_Strings_2_3_4_TestData))] public static void Concat_Spans(string[] values, string expected) { Assert.InRange(values.Length, 2, 4); string result = values.Length == 2 ? string.Concat(values[0].AsSpan(), values[1].AsSpan()) : values.Length == 3 ? string.Concat(values[0].AsSpan(), values[1].AsSpan(), values[2].AsSpan()) : string.Concat(values[0].AsSpan(), values[1].AsSpan(), values[2].AsSpan(), values[3].AsSpan()); if (result.Length == 0) { Assert.Same(string.Empty, result); } Assert.Equal(expected, result); } // [Fact] // public static void IndexerUsingIndexTest() // { // Index index; // string s = "0123456789ABCDEF"; // for (int i = 0; i < s.Length; i++) // { // index = Index.FromStart(i); // Assert.Equal(s[i], s[index]); // index = Index.FromEnd(i + 1); // Assert.Equal(s[s.Length - i - 1], s[index]); // } // index = Index.FromStart(s.Length + 1); // char c; // Assert.Throws<IndexOutOfRangeException>(() => c = s[index]); // index = Index.FromEnd(s.Length + 1); // Assert.Throws<IndexOutOfRangeException>(() => c = s[index]); // } // [Fact] // public static void IndexerUsingRangeTest() // { // Range range; // string s = "0123456789ABCDEF"; // for (int i = 0; i < s.Length; i++) // { // range = new Range(Index.FromStart(0), Index.FromStart(i)); // Assert.Equal(s.Substring(0, i), s[range]); // range = new Range(Index.FromEnd(s.Length), Index.FromEnd(i)); // Assert.Equal(s.Substring(0, s.Length - i), s[range]); // } // range = new Range(Index.FromStart(s.Length - 2), Index.FromStart(s.Length + 1)); // string s1; // Assert.Throws<ArgumentOutOfRangeException>(() => s1 = s[range]); // range = new Range(Index.FromEnd(s.Length + 1), Index.FromEnd(0)); // Assert.Throws<ArgumentOutOfRangeException>(() => s1 = s[range]); // } [Fact] public static void SubstringUsingIndexTest() { string s = "0123456789ABCDEF"; for (int i = 0; i < s.Length; i++) { Assert.Equal(s.Substring(i), s.Substring(Index.FromStart(i))); Assert.Equal(s.Substring(s.Length - i - 1), s.Substring(Index.FromEnd(i + 1))); } // String.Substring allows the string length as a valid input. Assert.Equal(s.Substring(s.Length), s.Substring(Index.FromStart(s.Length))); Assert.Throws<ArgumentOutOfRangeException>(() => s.Substring(Index.FromStart(s.Length + 1))); Assert.Throws<ArgumentOutOfRangeException>(() => s.Substring(Index.FromEnd(s.Length + 1))); } [Fact] public static void SubstringUsingRangeTest() { string s = "0123456789ABCDEF"; Range range; for (int i = 0; i < s.Length; i++) { range = new Range(Index.FromStart(0), Index.FromStart(i)); Assert.Equal(s.Substring(0, i), s.Substring(range)); range = new Range(Index.FromEnd(s.Length), Index.FromEnd(i)); Assert.Equal(s.Substring(0, s.Length - i), s.Substring(range)); } range = new Range(Index.FromStart(s.Length - 2), Index.FromStart(s.Length + 1)); string s1; Assert.Throws<ArgumentOutOfRangeException>(() => s1 = s.Substring(range)); range = new Range(Index.FromEnd(s.Length + 1), Index.FromEnd(0)); Assert.Throws<ArgumentOutOfRangeException>(() => s1 = s.Substring(range)); } /// <summary> /// Returns true only if U+0020 SPACE is represented as the single byte 0x20 in the active code page. /// </summary> public unsafe static bool IsSimpleActiveCodePage { get { IntPtr pAnsiStr = IntPtr.Zero; try { pAnsiStr = Marshal.StringToHGlobalAnsi(" "); return ((byte*)pAnsiStr)[0] == (byte)' ' && ((byte*)pAnsiStr)[1] == (byte)'\0'; } finally { if (pAnsiStr != IntPtr.Zero) { Marshal.FreeHGlobal(pAnsiStr); } } } } } }
using EpisodeInformer.Data.Information; using Ionic.Zip; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Threading; using System.Windows.Forms; namespace ServiceManager { public partial class frmBackupDB : Form { private ZipFile zF; private string cmt; public frmBackupDB() { this.InitializeComponent(); this.zF = new ZipFile(); this.zF.SaveProgress += new EventHandler<SaveProgressEventArgs>(this.zF_SaveProgress); this.lblDBVersion.Text = DBInformation.GetDBVersion().ToString(); this.lblTime.Text = DBInformation.GetLastBackUp(); } private void InitializeComponent() { ComponentResourceManager resources = new ComponentResourceManager(typeof(frmBackupDB)); this.statusStrip1 = new StatusStrip(); this.lblStatus = new ToolStripStatusLabel(); this.prgStatus = new ToolStripProgressBar(); this.groupBox1 = new GroupBox(); this.btnBrowse = new Button(); this.txtBkfLoc = new TextBox(); this.label1 = new Label(); this.groupBox2 = new GroupBox(); this.btnClose = new Button(); this.btnBkf = new Button(); this.groupBox3 = new GroupBox(); this.lblDBVersion = new Label(); this.lblTime = new Label(); this.label3 = new Label(); this.label2 = new Label(); this.statusStrip1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); this.statusStrip1.Items.AddRange(new ToolStripItem[2] { (ToolStripItem) this.lblStatus, (ToolStripItem) this.prgStatus }); this.statusStrip1.Location = new Point(0, 283); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new Size(370, 22); this.statusStrip1.SizingGrip = false; this.statusStrip1.TabIndex = 0; this.statusStrip1.Text = "statusStrip1"; this.lblStatus.Name = "lblStatus"; this.lblStatus.Size = new Size(39, 17); this.lblStatus.Text = "Status"; this.prgStatus.Name = "prgStatus"; this.prgStatus.Size = new Size(100, 16); this.groupBox1.Controls.Add((Control)this.btnBrowse); this.groupBox1.Controls.Add((Control)this.txtBkfLoc); this.groupBox1.Controls.Add((Control)this.label1); this.groupBox1.Location = new Point(12, 118); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new Size(346, 85); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.btnBrowse.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.btnBrowse.Location = new Point(309, 14); this.btnBrowse.Name = "btnBrowse"; this.btnBrowse.Size = new Size(31, 23); this.btnBrowse.TabIndex = 2; this.btnBrowse.Text = "...."; this.btnBrowse.UseVisualStyleBackColor = true; this.btnBrowse.Click += new EventHandler(this.btnBrowse_Click); this.txtBkfLoc.Font = new Font("Segoe UI", 8.25f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.txtBkfLoc.Location = new Point(62, 16); this.txtBkfLoc.Multiline = true; this.txtBkfLoc.Name = "txtBkfLoc"; this.txtBkfLoc.ReadOnly = true; this.txtBkfLoc.ScrollBars = ScrollBars.Vertical; this.txtBkfLoc.Size = new Size(241, 56); this.txtBkfLoc.TabIndex = 1; this.txtBkfLoc.TextChanged += new EventHandler(this.txtBkfLoc_TextChanged); this.label1.AutoSize = true; this.label1.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label1.Location = new Point(8, 19); this.label1.Name = "label1"; this.label1.Size = new Size(47, 13); this.label1.TabIndex = 0; this.label1.Text = "Save To"; this.groupBox2.Controls.Add((Control)this.btnClose); this.groupBox2.Controls.Add((Control)this.btnBkf); this.groupBox2.Location = new Point(12, 209); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new Size(346, 61); this.groupBox2.TabIndex = 2; this.groupBox2.TabStop = false; this.btnClose.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.btnClose.Location = new Point(265, 19); this.btnClose.Name = "btnClose"; this.btnClose.Size = new Size(75, 23); this.btnClose.TabIndex = 1; this.btnClose.Text = "Close"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new EventHandler(this.btnClose_Click); this.btnBkf.Enabled = false; this.btnBkf.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.btnBkf.Location = new Point(184, 19); this.btnBkf.Name = "btnBkf"; this.btnBkf.Size = new Size(75, 23); this.btnBkf.TabIndex = 0; this.btnBkf.Text = "Backup"; this.btnBkf.UseVisualStyleBackColor = true; this.btnBkf.Click += new EventHandler(this.btnBkf_Click); this.groupBox3.Controls.Add((Control)this.lblDBVersion); this.groupBox3.Controls.Add((Control)this.lblTime); this.groupBox3.Controls.Add((Control)this.label3); this.groupBox3.Controls.Add((Control)this.label2); this.groupBox3.Location = new Point(12, 12); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new Size(346, 100); this.groupBox3.TabIndex = 3; this.groupBox3.TabStop = false; this.lblDBVersion.AutoSize = true; this.lblDBVersion.Font = new Font("Segoe UI Semibold", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.lblDBVersion.Location = new Point(129, 58); this.lblDBVersion.Name = "lblDBVersion"; this.lblDBVersion.Size = new Size(24, 13); this.lblDBVersion.TabIndex = 3; this.lblDBVersion.Text = "Ver"; this.lblTime.AutoSize = true; this.lblTime.Font = new Font("Segoe UI Semibold", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.lblTime.Location = new Point(129, 30); this.lblTime.Name = "lblTime"; this.lblTime.Size = new Size(32, 13); this.lblTime.TabIndex = 2; this.lblTime.Text = "Time"; this.label3.AutoSize = true; this.label3.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label3.Location = new Point(23, 58); this.label3.Name = "label3"; this.label3.Size = new Size(103, 13); this.label3.TabIndex = 1; this.label3.Text = "Database Version :"; this.label2.AutoSize = true; this.label2.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label2.Location = new Point(33, 30); this.label2.Name = "label2"; this.label2.Size = new Size(93, 13); this.label2.TabIndex = 0; this.label2.Text = "Last Backup On :"; this.AutoScaleDimensions = new SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new Size(370, 305); this.Controls.Add((Control)this.groupBox3); this.Controls.Add((Control)this.groupBox2); this.Controls.Add((Control)this.groupBox1); this.Controls.Add((Control)this.statusStrip1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = (Icon)resources.GetObject("$this.Icon"); this.MaximizeBox = false; this.Name = "frmBackupDB"; this.StartPosition = FormStartPosition.CenterParent; this.Text = "Backup Database"; this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } private void zF_SaveProgress(object sender, SaveProgressEventArgs e) { if (e.EventType != ZipProgressEventType.Saving_Completed) return; this.ResetForm(); } private void btnBkf_Click(object sender, EventArgs e) { this.cmt = DateTime.Now.ToString() + "|" + this.lblDBVersion.Text; this.prgStatus.Style = ProgressBarStyle.Marquee; if (File.Exists(this.txtBkfLoc.Text)) { try { File.Delete(this.txtBkfLoc.Text); } catch (Exception) { } } new Thread(new ThreadStart(this.DOProcess)).Start(); } private void btnBrowse_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "ZipFile (*.zip)|*.zip"; saveFileDialog.FileName = "EpisodeInformerDBBKF.zip"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { this.txtBkfLoc.Text = saveFileDialog.FileName; this.lblStatus.Text = "Waiting"; } else { this.txtBkfLoc.Text = ""; this.lblStatus.Text = "Status"; } } private void btnClose_Click(object sender, EventArgs e) { this.Close(); } private void txtBkfLoc_TextChanged(object sender, EventArgs e) { if (this.txtBkfLoc.Text.Length > 0) this.btnBkf.Enabled = true; else this.btnBkf.Enabled = false; } private void DOProcess() { this.zF.Password = "HMLROCKX"; string path1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data"); string path2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data\\Overviews"); string[] files1 = Directory.GetFiles(path1, "*.mdb", SearchOption.TopDirectoryOnly); string[] files2 = Directory.GetFiles(path2); this.zF.AddFile(files1[0], "Data"); this.zF.AddFiles(Enumerable.AsEnumerable<string>((IEnumerable<string>)files2), "Data\\Overviews"); this.zF.Comment = this.cmt; this.zF.Save(this.txtBkfLoc.Text); this.ResetZipFile(); } private void ResetForm() { if (this.txtBkfLoc.InvokeRequired) { this.Invoke((Delegate)new frmBackupDB.DoneProcess(this.ResetForm)); } else { this.prgStatus.Style = ProgressBarStyle.Blocks; DBInformation.SetLastBackUp(DateTime.Now); this.lblTime.Text = DateTime.Now.ToString(); this.txtBkfLoc.Text = ""; this.lblStatus.Text = "Done"; int num = (int)MessageBox.Show("Backup completed.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } private void ResetZipFile() { this.zF = new ZipFile(); this.zF.SaveProgress += new EventHandler<SaveProgressEventArgs>(this.zF_SaveProgress); } private bool isEpisodeInformerWorking() { bool flag = false; Process[] processesByName1 = Process.GetProcessesByName("EpisodeInformer"); Process[] processesByName2 = Process.GetProcessesByName("EpisodeInformerServices"); Process[] processesByName3 = Process.GetProcessesByName("EpisodeInformerADVServices"); if (processesByName1.Length > 0) flag = true; else if (processesByName2.Length > 0) flag = true; else if (processesByName3.Length > 0) flag = true; return flag; } private delegate void DoneProcess(); } }
// This file has been generated by the GUI designer. Do not modify. namespace ShadowrunGui { public partial class CombatPageWidget { private global::Gtk.VBox Combat_Box1; private global::Gtk.HBox Combat_Box2; private global::Gtk.Frame Initiative_Frame1; private global::Gtk.Alignment GtkAlignment5; private global::Gtk.ScrolledWindow InitiativeTree_ScrolledWindow; private global::Gtk.TreeView Initiative_TreeView; private global::Gtk.Label InitiativeFrame_Label; private global::Gtk.Frame CharacterStatus_Frame; private global::Gtk.Alignment GtkAlignment4; private global::Gtk.TreeView CharacterStatus_TreeView; private global::Gtk.Label CharacterStatus_Label; private global::Gtk.VBox Controls_Box; private global::Gtk.Frame Status_Frame; private global::Gtk.Alignment GtkAlignment3; private global::Gtk.VBox vbox10; private global::Gtk.Button Reload_Button; private global::Gtk.HSeparator hseparator12; private global::Gtk.Label Characters_Label; private global::Gtk.Frame Initiative_Frame; private global::Gtk.Alignment GtkAlignment; private global::Gtk.VBox vbox5; private global::Gtk.Button NewInitiative_Button; private global::Gtk.HSeparator hseparator5; private global::Gtk.Button NextCharacter_Button; private global::Gtk.HSeparator hseparator6; private global::Gtk.Button PreviousCharacter_Button; private global::Gtk.HSeparator hseparator11; private global::Gtk.Button NextPass_Button; private global::Gtk.HSeparator hseparator1; private global::Gtk.Button SetCharacterInitiative_Button; private global::Gtk.Label Initiative_Label; private global::Gtk.Frame Defend_Frame; private global::Gtk.Alignment GtkAlignment1; private global::Gtk.VBox vbox9; private global::Gtk.Button DefendRanged_Button; private global::Gtk.HSeparator hseparator7; private global::Gtk.Button DefendMelee_Button; private global::Gtk.HSeparator hseparator8; private global::Gtk.Label Defend_Label; private global::Gtk.Frame Attack_Frame; private global::Gtk.Alignment GtkAlignment2; private global::Gtk.VBox vbox8; private global::Gtk.Button AttackRanged_Button; private global::Gtk.HSeparator hseparator9; private global::Gtk.Button AttackMelee_Button; private global::Gtk.HSeparator hseparator10; private global::Gtk.Label Attack_Label; private global::Gtk.Frame LogArea_Frame; private global::Gtk.Alignment GtkAlignment6; private global::Gtk.ScrolledWindow GtkScrolledWindow; private global::Gtk.TextView Log_Textview; private global::Gtk.Label LogFrame_Label; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget ShadowrunGui.CombatPageWidget global::Stetic.BinContainer.Attach (this); this.Name = "ShadowrunGui.CombatPageWidget"; // Container child ShadowrunGui.CombatPageWidget.Gtk.Container+ContainerChild this.Combat_Box1 = new global::Gtk.VBox (); this.Combat_Box1.Name = "Combat_Box1"; this.Combat_Box1.Spacing = 6; // Container child Combat_Box1.Gtk.Box+BoxChild this.Combat_Box2 = new global::Gtk.HBox (); this.Combat_Box2.Name = "Combat_Box2"; this.Combat_Box2.Spacing = 6; // Container child Combat_Box2.Gtk.Box+BoxChild this.Initiative_Frame1 = new global::Gtk.Frame (); this.Initiative_Frame1.Name = "Initiative_Frame1"; this.Initiative_Frame1.ShadowType = ((global::Gtk.ShadowType)(0)); // Container child Initiative_Frame1.Gtk.Container+ContainerChild this.GtkAlignment5 = new global::Gtk.Alignment (0F, 0F, 1F, 1F); this.GtkAlignment5.Name = "GtkAlignment5"; this.GtkAlignment5.LeftPadding = ((uint)(12)); // Container child GtkAlignment5.Gtk.Container+ContainerChild this.InitiativeTree_ScrolledWindow = new global::Gtk.ScrolledWindow (); this.InitiativeTree_ScrolledWindow.Name = "InitiativeTree_ScrolledWindow"; this.InitiativeTree_ScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child InitiativeTree_ScrolledWindow.Gtk.Container+ContainerChild this.Initiative_TreeView = new global::Gtk.TreeView (); this.Initiative_TreeView.CanFocus = true; this.Initiative_TreeView.Name = "Initiative_TreeView"; this.InitiativeTree_ScrolledWindow.Add (this.Initiative_TreeView); this.GtkAlignment5.Add (this.InitiativeTree_ScrolledWindow); this.Initiative_Frame1.Add (this.GtkAlignment5); this.InitiativeFrame_Label = new global::Gtk.Label (); this.InitiativeFrame_Label.Name = "InitiativeFrame_Label"; this.InitiativeFrame_Label.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Initiative</b>"); this.InitiativeFrame_Label.UseMarkup = true; this.Initiative_Frame1.LabelWidget = this.InitiativeFrame_Label; this.Combat_Box2.Add (this.Initiative_Frame1); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.Combat_Box2 [this.Initiative_Frame1])); w4.Position = 0; // Container child Combat_Box2.Gtk.Box+BoxChild this.CharacterStatus_Frame = new global::Gtk.Frame (); this.CharacterStatus_Frame.WidthRequest = 300; this.CharacterStatus_Frame.Name = "CharacterStatus_Frame"; this.CharacterStatus_Frame.ShadowType = ((global::Gtk.ShadowType)(0)); // Container child CharacterStatus_Frame.Gtk.Container+ContainerChild this.GtkAlignment4 = new global::Gtk.Alignment (0F, 0F, 1F, 1F); this.GtkAlignment4.Name = "GtkAlignment4"; this.GtkAlignment4.LeftPadding = ((uint)(12)); // Container child GtkAlignment4.Gtk.Container+ContainerChild this.CharacterStatus_TreeView = new global::Gtk.TreeView (); this.CharacterStatus_TreeView.CanFocus = true; this.CharacterStatus_TreeView.Name = "CharacterStatus_TreeView"; this.GtkAlignment4.Add (this.CharacterStatus_TreeView); this.CharacterStatus_Frame.Add (this.GtkAlignment4); this.CharacterStatus_Label = new global::Gtk.Label (); this.CharacterStatus_Label.Name = "CharacterStatus_Label"; this.CharacterStatus_Label.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Character Status</b>"); this.CharacterStatus_Label.UseMarkup = true; this.CharacterStatus_Frame.LabelWidget = this.CharacterStatus_Label; this.Combat_Box2.Add (this.CharacterStatus_Frame); global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.Combat_Box2 [this.CharacterStatus_Frame])); w7.Position = 1; w7.Expand = false; // Container child Combat_Box2.Gtk.Box+BoxChild this.Controls_Box = new global::Gtk.VBox (); this.Controls_Box.Name = "Controls_Box"; this.Controls_Box.Spacing = 6; // Container child Controls_Box.Gtk.Box+BoxChild this.Status_Frame = new global::Gtk.Frame (); this.Status_Frame.Name = "Status_Frame"; this.Status_Frame.ShadowType = ((global::Gtk.ShadowType)(0)); // Container child Status_Frame.Gtk.Container+ContainerChild this.GtkAlignment3 = new global::Gtk.Alignment (0F, 0F, 1F, 1F); this.GtkAlignment3.Name = "GtkAlignment3"; this.GtkAlignment3.LeftPadding = ((uint)(12)); // Container child GtkAlignment3.Gtk.Container+ContainerChild this.vbox10 = new global::Gtk.VBox (); this.vbox10.Name = "vbox10"; this.vbox10.Spacing = 6; // Container child vbox10.Gtk.Box+BoxChild this.Reload_Button = new global::Gtk.Button (); this.Reload_Button.CanFocus = true; this.Reload_Button.Name = "Reload_Button"; this.Reload_Button.UseUnderline = true; this.Reload_Button.Label = global::Mono.Unix.Catalog.GetString ("Reload"); this.vbox10.Add (this.Reload_Button); global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.vbox10 [this.Reload_Button])); w8.Position = 0; w8.Expand = false; w8.Fill = false; // Container child vbox10.Gtk.Box+BoxChild this.hseparator12 = new global::Gtk.HSeparator (); this.hseparator12.Name = "hseparator12"; this.vbox10.Add (this.hseparator12); global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.vbox10 [this.hseparator12])); w9.Position = 1; w9.Expand = false; w9.Fill = false; this.GtkAlignment3.Add (this.vbox10); this.Status_Frame.Add (this.GtkAlignment3); this.Characters_Label = new global::Gtk.Label (); this.Characters_Label.Name = "Characters_Label"; this.Characters_Label.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Characters</b>"); this.Characters_Label.UseMarkup = true; this.Status_Frame.LabelWidget = this.Characters_Label; this.Controls_Box.Add (this.Status_Frame); global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.Controls_Box [this.Status_Frame])); w12.Position = 0; w12.Expand = false; w12.Fill = false; // Container child Controls_Box.Gtk.Box+BoxChild this.Initiative_Frame = new global::Gtk.Frame (); this.Initiative_Frame.Name = "Initiative_Frame"; this.Initiative_Frame.ShadowType = ((global::Gtk.ShadowType)(0)); // Container child Initiative_Frame.Gtk.Container+ContainerChild this.GtkAlignment = new global::Gtk.Alignment (0F, 0F, 1F, 1F); this.GtkAlignment.Name = "GtkAlignment"; this.GtkAlignment.LeftPadding = ((uint)(12)); // Container child GtkAlignment.Gtk.Container+ContainerChild this.vbox5 = new global::Gtk.VBox (); this.vbox5.Name = "vbox5"; this.vbox5.Spacing = 6; // Container child vbox5.Gtk.Box+BoxChild this.NewInitiative_Button = new global::Gtk.Button (); this.NewInitiative_Button.CanFocus = true; this.NewInitiative_Button.Name = "NewInitiative_Button"; this.NewInitiative_Button.UseUnderline = true; this.NewInitiative_Button.Label = global::Mono.Unix.Catalog.GetString ("New Initiative"); this.vbox5.Add (this.NewInitiative_Button); global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.NewInitiative_Button])); w13.Position = 0; w13.Expand = false; w13.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.hseparator5 = new global::Gtk.HSeparator (); this.hseparator5.Name = "hseparator5"; this.vbox5.Add (this.hseparator5); global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.hseparator5])); w14.Position = 1; w14.Expand = false; w14.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.NextCharacter_Button = new global::Gtk.Button (); this.NextCharacter_Button.CanFocus = true; this.NextCharacter_Button.Name = "NextCharacter_Button"; this.NextCharacter_Button.UseUnderline = true; this.NextCharacter_Button.Label = global::Mono.Unix.Catalog.GetString ("Next Character"); this.vbox5.Add (this.NextCharacter_Button); global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.NextCharacter_Button])); w15.Position = 2; w15.Expand = false; w15.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.hseparator6 = new global::Gtk.HSeparator (); this.hseparator6.Name = "hseparator6"; this.vbox5.Add (this.hseparator6); global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.hseparator6])); w16.Position = 3; w16.Expand = false; w16.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.PreviousCharacter_Button = new global::Gtk.Button (); this.PreviousCharacter_Button.CanFocus = true; this.PreviousCharacter_Button.Name = "PreviousCharacter_Button"; this.PreviousCharacter_Button.UseUnderline = true; this.PreviousCharacter_Button.Label = global::Mono.Unix.Catalog.GetString ("Previous Character"); this.vbox5.Add (this.PreviousCharacter_Button); global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.PreviousCharacter_Button])); w17.Position = 4; w17.Expand = false; w17.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.hseparator11 = new global::Gtk.HSeparator (); this.hseparator11.Name = "hseparator11"; this.vbox5.Add (this.hseparator11); global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.hseparator11])); w18.Position = 5; w18.Expand = false; w18.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.NextPass_Button = new global::Gtk.Button (); this.NextPass_Button.CanFocus = true; this.NextPass_Button.Name = "NextPass_Button"; this.NextPass_Button.UseUnderline = true; this.NextPass_Button.Label = global::Mono.Unix.Catalog.GetString ("Next Pass"); this.vbox5.Add (this.NextPass_Button); global::Gtk.Box.BoxChild w19 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.NextPass_Button])); w19.Position = 6; w19.Expand = false; w19.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.hseparator1 = new global::Gtk.HSeparator (); this.hseparator1.Name = "hseparator1"; this.vbox5.Add (this.hseparator1); global::Gtk.Box.BoxChild w20 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.hseparator1])); w20.Position = 7; w20.Expand = false; w20.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.SetCharacterInitiative_Button = new global::Gtk.Button (); this.SetCharacterInitiative_Button.CanFocus = true; this.SetCharacterInitiative_Button.Name = "SetCharacterInitiative_Button"; this.SetCharacterInitiative_Button.UseUnderline = true; this.SetCharacterInitiative_Button.Label = global::Mono.Unix.Catalog.GetString ("Set Initiative"); this.vbox5.Add (this.SetCharacterInitiative_Button); global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.SetCharacterInitiative_Button])); w21.Position = 8; w21.Expand = false; w21.Fill = false; this.GtkAlignment.Add (this.vbox5); this.Initiative_Frame.Add (this.GtkAlignment); this.Initiative_Label = new global::Gtk.Label (); this.Initiative_Label.Name = "Initiative_Label"; this.Initiative_Label.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Initiative</b>"); this.Initiative_Label.UseMarkup = true; this.Initiative_Frame.LabelWidget = this.Initiative_Label; this.Controls_Box.Add (this.Initiative_Frame); global::Gtk.Box.BoxChild w24 = ((global::Gtk.Box.BoxChild)(this.Controls_Box [this.Initiative_Frame])); w24.Position = 1; w24.Expand = false; w24.Fill = false; // Container child Controls_Box.Gtk.Box+BoxChild this.Defend_Frame = new global::Gtk.Frame (); this.Defend_Frame.Name = "Defend_Frame"; this.Defend_Frame.ShadowType = ((global::Gtk.ShadowType)(0)); // Container child Defend_Frame.Gtk.Container+ContainerChild this.GtkAlignment1 = new global::Gtk.Alignment (0F, 0F, 1F, 1F); this.GtkAlignment1.Name = "GtkAlignment1"; this.GtkAlignment1.LeftPadding = ((uint)(12)); // Container child GtkAlignment1.Gtk.Container+ContainerChild this.vbox9 = new global::Gtk.VBox (); this.vbox9.Name = "vbox9"; this.vbox9.Spacing = 6; // Container child vbox9.Gtk.Box+BoxChild this.DefendRanged_Button = new global::Gtk.Button (); this.DefendRanged_Button.CanFocus = true; this.DefendRanged_Button.Name = "DefendRanged_Button"; this.DefendRanged_Button.UseUnderline = true; this.DefendRanged_Button.Label = global::Mono.Unix.Catalog.GetString ("Ranged"); this.vbox9.Add (this.DefendRanged_Button); global::Gtk.Box.BoxChild w25 = ((global::Gtk.Box.BoxChild)(this.vbox9 [this.DefendRanged_Button])); w25.Position = 0; w25.Expand = false; w25.Fill = false; // Container child vbox9.Gtk.Box+BoxChild this.hseparator7 = new global::Gtk.HSeparator (); this.hseparator7.Name = "hseparator7"; this.vbox9.Add (this.hseparator7); global::Gtk.Box.BoxChild w26 = ((global::Gtk.Box.BoxChild)(this.vbox9 [this.hseparator7])); w26.Position = 1; w26.Expand = false; w26.Fill = false; // Container child vbox9.Gtk.Box+BoxChild this.DefendMelee_Button = new global::Gtk.Button (); this.DefendMelee_Button.CanFocus = true; this.DefendMelee_Button.Name = "DefendMelee_Button"; this.DefendMelee_Button.UseUnderline = true; this.DefendMelee_Button.Label = global::Mono.Unix.Catalog.GetString ("Melee"); this.vbox9.Add (this.DefendMelee_Button); global::Gtk.Box.BoxChild w27 = ((global::Gtk.Box.BoxChild)(this.vbox9 [this.DefendMelee_Button])); w27.Position = 2; w27.Expand = false; w27.Fill = false; // Container child vbox9.Gtk.Box+BoxChild this.hseparator8 = new global::Gtk.HSeparator (); this.hseparator8.Name = "hseparator8"; this.vbox9.Add (this.hseparator8); global::Gtk.Box.BoxChild w28 = ((global::Gtk.Box.BoxChild)(this.vbox9 [this.hseparator8])); w28.Position = 3; w28.Expand = false; w28.Fill = false; this.GtkAlignment1.Add (this.vbox9); this.Defend_Frame.Add (this.GtkAlignment1); this.Defend_Label = new global::Gtk.Label (); this.Defend_Label.Name = "Defend_Label"; this.Defend_Label.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Defend-Misc</b>"); this.Defend_Label.UseMarkup = true; this.Defend_Frame.LabelWidget = this.Defend_Label; this.Controls_Box.Add (this.Defend_Frame); global::Gtk.Box.BoxChild w31 = ((global::Gtk.Box.BoxChild)(this.Controls_Box [this.Defend_Frame])); w31.Position = 2; w31.Expand = false; w31.Fill = false; // Container child Controls_Box.Gtk.Box+BoxChild this.Attack_Frame = new global::Gtk.Frame (); this.Attack_Frame.Name = "Attack_Frame"; this.Attack_Frame.ShadowType = ((global::Gtk.ShadowType)(0)); // Container child Attack_Frame.Gtk.Container+ContainerChild this.GtkAlignment2 = new global::Gtk.Alignment (0F, 0F, 1F, 1F); this.GtkAlignment2.Name = "GtkAlignment2"; this.GtkAlignment2.LeftPadding = ((uint)(12)); // Container child GtkAlignment2.Gtk.Container+ContainerChild this.vbox8 = new global::Gtk.VBox (); this.vbox8.Name = "vbox8"; this.vbox8.Spacing = 6; // Container child vbox8.Gtk.Box+BoxChild this.AttackRanged_Button = new global::Gtk.Button (); this.AttackRanged_Button.CanFocus = true; this.AttackRanged_Button.Name = "AttackRanged_Button"; this.AttackRanged_Button.UseUnderline = true; this.AttackRanged_Button.Label = global::Mono.Unix.Catalog.GetString ("Ranged"); this.vbox8.Add (this.AttackRanged_Button); global::Gtk.Box.BoxChild w32 = ((global::Gtk.Box.BoxChild)(this.vbox8 [this.AttackRanged_Button])); w32.Position = 0; w32.Expand = false; w32.Fill = false; // Container child vbox8.Gtk.Box+BoxChild this.hseparator9 = new global::Gtk.HSeparator (); this.hseparator9.Name = "hseparator9"; this.vbox8.Add (this.hseparator9); global::Gtk.Box.BoxChild w33 = ((global::Gtk.Box.BoxChild)(this.vbox8 [this.hseparator9])); w33.Position = 1; w33.Expand = false; w33.Fill = false; // Container child vbox8.Gtk.Box+BoxChild this.AttackMelee_Button = new global::Gtk.Button (); this.AttackMelee_Button.CanFocus = true; this.AttackMelee_Button.Name = "AttackMelee_Button"; this.AttackMelee_Button.UseUnderline = true; this.AttackMelee_Button.Label = global::Mono.Unix.Catalog.GetString ("Melee"); this.vbox8.Add (this.AttackMelee_Button); global::Gtk.Box.BoxChild w34 = ((global::Gtk.Box.BoxChild)(this.vbox8 [this.AttackMelee_Button])); w34.Position = 2; w34.Expand = false; w34.Fill = false; // Container child vbox8.Gtk.Box+BoxChild this.hseparator10 = new global::Gtk.HSeparator (); this.hseparator10.Name = "hseparator10"; this.vbox8.Add (this.hseparator10); global::Gtk.Box.BoxChild w35 = ((global::Gtk.Box.BoxChild)(this.vbox8 [this.hseparator10])); w35.Position = 3; w35.Expand = false; w35.Fill = false; this.GtkAlignment2.Add (this.vbox8); this.Attack_Frame.Add (this.GtkAlignment2); this.Attack_Label = new global::Gtk.Label (); this.Attack_Label.Name = "Attack_Label"; this.Attack_Label.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Attack</b>"); this.Attack_Label.UseMarkup = true; this.Attack_Frame.LabelWidget = this.Attack_Label; this.Controls_Box.Add (this.Attack_Frame); global::Gtk.Box.BoxChild w38 = ((global::Gtk.Box.BoxChild)(this.Controls_Box [this.Attack_Frame])); w38.Position = 3; w38.Expand = false; w38.Fill = false; this.Combat_Box2.Add (this.Controls_Box); global::Gtk.Box.BoxChild w39 = ((global::Gtk.Box.BoxChild)(this.Combat_Box2 [this.Controls_Box])); w39.Position = 2; w39.Expand = false; w39.Fill = false; this.Combat_Box1.Add (this.Combat_Box2); global::Gtk.Box.BoxChild w40 = ((global::Gtk.Box.BoxChild)(this.Combat_Box1 [this.Combat_Box2])); w40.Position = 0; // Container child Combat_Box1.Gtk.Box+BoxChild this.LogArea_Frame = new global::Gtk.Frame (); this.LogArea_Frame.Name = "LogArea_Frame"; this.LogArea_Frame.ShadowType = ((global::Gtk.ShadowType)(0)); // Container child LogArea_Frame.Gtk.Container+ContainerChild this.GtkAlignment6 = new global::Gtk.Alignment (0F, 0F, 1F, 1F); this.GtkAlignment6.Name = "GtkAlignment6"; this.GtkAlignment6.LeftPadding = ((uint)(12)); // Container child GtkAlignment6.Gtk.Container+ContainerChild this.GtkScrolledWindow = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow.Name = "GtkScrolledWindow"; this.GtkScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow.Gtk.Container+ContainerChild this.Log_Textview = new global::Gtk.TextView (); this.Log_Textview.CanFocus = true; this.Log_Textview.Name = "Log_Textview"; this.Log_Textview.Editable = false; this.Log_Textview.CursorVisible = false; this.GtkScrolledWindow.Add (this.Log_Textview); this.GtkAlignment6.Add (this.GtkScrolledWindow); this.LogArea_Frame.Add (this.GtkAlignment6); this.LogFrame_Label = new global::Gtk.Label (); this.LogFrame_Label.Name = "LogFrame_Label"; this.LogFrame_Label.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Log</b>"); this.LogFrame_Label.UseMarkup = true; this.LogArea_Frame.LabelWidget = this.LogFrame_Label; this.Combat_Box1.Add (this.LogArea_Frame); global::Gtk.Box.BoxChild w44 = ((global::Gtk.Box.BoxChild)(this.Combat_Box1 [this.LogArea_Frame])); w44.PackType = ((global::Gtk.PackType)(1)); w44.Position = 1; this.Add (this.Combat_Box1); if ((this.Child != null)) { this.Child.ShowAll (); } this.Hide (); } } }
// 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.Sql { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// BackupLongTermRetentionVaultsOperations operations. /// </summary> internal partial class BackupLongTermRetentionVaultsOperations : IServiceOperations<SqlManagementClient>, IBackupLongTermRetentionVaultsOperations { /// <summary> /// Initializes a new instance of the BackupLongTermRetentionVaultsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BackupLongTermRetentionVaultsOperations(SqlManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SqlManagementClient /// </summary> public SqlManagementClient Client { get; private set; } /// <summary> /// Gets a server backup long term retention vault /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BackupLongTermRetentionVault>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serverName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serverName"); } string apiVersion = "2014-04-01"; string backupLongTermRetentionVaultName = "RegisteredVault"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("backupLongTermRetentionVaultName", backupLongTermRetentionVaultName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/backupLongTermRetentionVaults/{backupLongTermRetentionVaultName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName)); _url = _url.Replace("{backupLongTermRetentionVaultName}", System.Uri.EscapeDataString(backupLongTermRetentionVaultName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BackupLongTermRetentionVault>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BackupLongTermRetentionVault>(_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; } /// <summary> /// Updates a server backup long term retention vault /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='parameters'> /// The required parameters to update a backup long term retention vault /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<BackupLongTermRetentionVault>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, BackupLongTermRetentionVault parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<BackupLongTermRetentionVault> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updates a server backup long term retention vault /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='parameters'> /// The required parameters to update a backup long term retention vault /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BackupLongTermRetentionVault>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, BackupLongTermRetentionVault parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serverName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serverName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } string apiVersion = "2014-04-01"; string backupLongTermRetentionVaultName = "RegisteredVault"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("backupLongTermRetentionVaultName", backupLongTermRetentionVaultName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", 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.Sql/servers/{serverName}/backupLongTermRetentionVaults/{backupLongTermRetentionVaultName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName)); _url = _url.Replace("{backupLongTermRetentionVaultName}", System.Uri.EscapeDataString(backupLongTermRetentionVaultName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BackupLongTermRetentionVault>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BackupLongTermRetentionVault>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BackupLongTermRetentionVault>(_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) 2006-2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using OpenMetaverse.Packets; using System.Reflection; namespace OpenMetaverse { /// <summary> /// Static helper functions and global variables /// </summary> public static class Helpers { /// <summary>This header flag signals that ACKs are appended to the packet</summary> public const byte MSG_APPENDED_ACKS = 0x10; /// <summary>This header flag signals that this packet has been sent before</summary> public const byte MSG_RESENT = 0x20; /// <summary>This header flags signals that an ACK is expected for this packet</summary> public const byte MSG_RELIABLE = 0x40; /// <summary>This header flag signals that the message is compressed using zerocoding</summary> public const byte MSG_ZEROCODED = 0x80; /// <summary> /// Passed to Logger.Log() to identify the severity of a log entry /// </summary> public enum LogLevel { /// <summary>No logging information will be output</summary> None, /// <summary>Non-noisy useful information, may be helpful in /// debugging a problem</summary> Info, /// <summary>A non-critical error occurred. A warning will not /// prevent the rest of the library from operating as usual, /// although it may be indicative of an underlying issue</summary> Warning, /// <summary>A critical error has occurred. Generally this will /// be followed by the network layer shutting down, although the /// stability of the library after an error is uncertain</summary> Error, /// <summary>Used for internal testing, this logging level can /// generate very noisy (long and/or repetitive) messages. Don't /// pass this to the Log() function, use DebugLog() instead. /// </summary> Debug }; /// <summary> /// /// </summary> /// <param name="offset"></param> /// <returns></returns> public static short TEOffsetShort(float offset) { offset = Utils.Clamp(offset, -1.0f, 1.0f); offset *= 32767.0f; return (short)Math.Round(offset); } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <returns></returns> public static float TEOffsetFloat(byte[] bytes, int pos) { float offset = (float)BitConverter.ToInt16(bytes, pos); return offset / 32767.0f; } /// <summary> /// /// </summary> /// <param name="rotation"></param> /// <returns></returns> public static short TERotationShort(float rotation) { const float TWO_PI = 6.283185307179586476925286766559f; return (short)Math.Round(((Math.IEEERemainder(rotation, TWO_PI) / TWO_PI) * 32768.0f) + 0.5f); } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <returns></returns> public static float TERotationFloat(byte[] bytes, int pos) { const float TWO_PI = 6.283185307179586476925286766559f; return ((float)(bytes[pos] | (bytes[pos + 1] << 8)) / 32768.0f) * TWO_PI; } public static byte TEGlowByte(float glow) { return (byte)(glow * 255.0f); } public static float TEGlowFloat(byte[] bytes, int pos) { return (float)bytes[pos] / 255.0f; } /// <summary> /// Given an X/Y location in absolute (grid-relative) terms, a region /// handle is returned along with the local X/Y location in that region /// </summary> /// <param name="globalX">The absolute X location, a number such as /// 255360.35</param> /// <param name="globalY">The absolute Y location, a number such as /// 255360.35</param> /// <param name="localX">The sim-local X position of the global X /// position, a value from 0.0 to 256.0</param> /// <param name="localY">The sim-local Y position of the global Y /// position, a value from 0.0 to 256.0</param> /// <returns>A 64-bit region handle that can be used to teleport to</returns> public static ulong GlobalPosToRegionHandle(float globalX, float globalY, out float localX, out float localY) { uint x = ((uint)globalX / 256) * 256; uint y = ((uint)globalY / 256) * 256; localX = globalX - (float)x; localY = globalY - (float)y; return Utils.UIntsToLong(x, y); } /// <summary> /// Converts a floating point number to a terse string format used for /// transmitting numbers in wearable asset files /// </summary> /// <param name="val">Floating point number to convert to a string</param> /// <returns>A terse string representation of the input number</returns> public static string FloatToTerseString(float val) { string s = string.Format(Utils.EnUsCulture, "{0:.00}", val); if (val == 0) return ".00"; // Trim trailing zeroes while (s[s.Length - 1] == '0') s = s.Remove(s.Length - 1, 1); // Remove superfluous decimal places after the trim if (s[s.Length - 1] == '.') s = s.Remove(s.Length - 1, 1); // Remove leading zeroes after a negative sign else if (s[0] == '-' && s[1] == '0') s = s.Remove(1, 1); // Remove leading zeroes in positive numbers else if (s[0] == '0') s = s.Remove(0, 1); return s; } /// <summary> /// Convert a variable length field (byte array) to a string, with a /// field name prepended to each line of the output /// </summary> /// <remarks>If the byte array has unprintable characters in it, a /// hex dump will be written instead</remarks> /// <param name="output">The StringBuilder object to write to</param> /// <param name="bytes">The byte array to convert to a string</param> /// <param name="fieldName">A field name to prepend to each line of output</param> internal static void FieldToString(StringBuilder output, byte[] bytes, string fieldName) { // Check for a common case if (bytes.Length == 0) return; bool printable = true; for (int i = 0; i < bytes.Length; ++i) { // Check if there are any unprintable characters in the array if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09 && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00) { printable = false; break; } } if (printable) { if (fieldName.Length > 0) { output.Append(fieldName); output.Append(": "); } if (bytes[bytes.Length - 1] == 0x00) output.Append(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1)); else output.Append(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length)); } else { for (int i = 0; i < bytes.Length; i += 16) { if (i != 0) output.Append('\n'); if (fieldName.Length > 0) { output.Append(fieldName); output.Append(": "); } for (int j = 0; j < 16; j++) { if ((i + j) < bytes.Length) output.Append(String.Format("{0:X2} ", bytes[i + j])); else output.Append(" "); } } } } /// <summary> /// Decode a zerocoded byte array, used to decompress packets marked /// with the zerocoded flag /// </summary> /// <remarks>Any time a zero is encountered, the next byte is a count /// of how many zeroes to expand. One zero is encoded with 0x00 0x01, /// two zeroes is 0x00 0x02, three zeroes is 0x00 0x03, etc. The /// first four bytes are copied directly to the output buffer. /// </remarks> /// <param name="src">The byte array to decode</param> /// <param name="srclen">The length of the byte array to decode. This /// would be the length of the packet up to (but not including) any /// appended ACKs</param> /// <param name="dest">The output byte array to decode to</param> /// <returns>The length of the output buffer</returns> public static int ZeroDecode(byte[] src, int srclen, byte[] dest) { if (srclen > src.Length) throw new ArgumentException("srclen cannot be greater than src.Length"); uint zerolen = 0; int bodylen = 0; uint i = 0; try { Buffer.BlockCopy(src, 0, dest, 0, 6); zerolen = 6; bodylen = srclen; for (i = zerolen; i < bodylen; i++) { if (src[i] == 0x00) { for (byte j = 0; j < src[i + 1]; j++) { dest[zerolen++] = 0x00; } i++; } else { dest[zerolen++] = src[i]; } } // Copy appended ACKs for (; i < srclen; i++) { dest[zerolen++] = src[i]; } return (int)zerolen; } catch (Exception ex) { Logger.Log(String.Format("Zerodecoding error: i={0}, srclen={1}, bodylen={2}, zerolen={3}\n{4}\n{5}", i, srclen, bodylen, zerolen, Utils.BytesToHexString(src, srclen, null), ex), LogLevel.Error); throw new IndexOutOfRangeException(String.Format("Zerodecoding error: i={0}, srclen={1}, bodylen={2}, zerolen={3}\n{4}\n{5}", i, srclen, bodylen, zerolen, Utils.BytesToHexString(src, srclen, null), ex.InnerException)); } } /// <summary> /// Encode a byte array with zerocoding. Used to compress packets marked /// with the zerocoded flag. Any zeroes in the array are compressed down /// to a single zero byte followed by a count of how many zeroes to expand /// out. A single zero becomes 0x00 0x01, two zeroes becomes 0x00 0x02, /// three zeroes becomes 0x00 0x03, etc. The first four bytes are copied /// directly to the output buffer. /// </summary> /// <param name="src">The byte array to encode</param> /// <param name="srclen">The length of the byte array to encode</param> /// <param name="dest">The output byte array to encode to</param> /// <returns>The length of the output buffer</returns> public static int ZeroEncode(byte[] src, int srclen, byte[] dest) { uint zerolen = 0; byte zerocount = 0; Buffer.BlockCopy(src, 0, dest, 0, 6); zerolen += 6; int bodylen; if ((src[0] & MSG_APPENDED_ACKS) == 0) { bodylen = srclen; } else { bodylen = srclen - src[srclen - 1] * 4 - 1; } uint i; for (i = zerolen; i < bodylen; i++) { if (src[i] == 0x00) { zerocount++; if (zerocount == 0) { dest[zerolen++] = 0x00; dest[zerolen++] = 0xff; zerocount++; } } else { if (zerocount != 0) { dest[zerolen++] = 0x00; dest[zerolen++] = (byte)zerocount; zerocount = 0; } dest[zerolen++] = src[i]; } } if (zerocount != 0) { dest[zerolen++] = 0x00; dest[zerolen++] = (byte)zerocount; } // copy appended ACKs for (; i < srclen; i++) { dest[zerolen++] = src[i]; } return (int)zerolen; } /// <summary> /// Calculates the CRC (cyclic redundancy check) needed to upload inventory. /// </summary> /// <param name="creationDate">Creation date</param> /// <param name="saleType">Sale type</param> /// <param name="invType">Inventory type</param> /// <param name="type">Type</param> /// <param name="assetID">Asset ID</param> /// <param name="groupID">Group ID</param> /// <param name="salePrice">Sale price</param> /// <param name="ownerID">Owner ID</param> /// <param name="creatorID">Creator ID</param> /// <param name="itemID">Item ID</param> /// <param name="folderID">Folder ID</param> /// <param name="everyoneMask">Everyone mask (permissions)</param> /// <param name="flags">Flags</param> /// <param name="nextOwnerMask">Next owner mask (permissions)</param> /// <param name="groupMask">Group mask (permissions)</param> /// <param name="ownerMask">Owner mask (permissions)</param> /// <returns>The calculated CRC</returns> public static uint InventoryCRC(int creationDate, byte saleType, sbyte invType, sbyte type, UUID assetID, UUID groupID, int salePrice, UUID ownerID, UUID creatorID, UUID itemID, UUID folderID, uint everyoneMask, uint flags, uint nextOwnerMask, uint groupMask, uint ownerMask) { uint CRC = 0; // IDs CRC += assetID.CRC(); // AssetID CRC += folderID.CRC(); // FolderID CRC += itemID.CRC(); // ItemID // Permission stuff CRC += creatorID.CRC(); // CreatorID CRC += ownerID.CRC(); // OwnerID CRC += groupID.CRC(); // GroupID // CRC += another 4 words which always seem to be zero -- unclear if this is a UUID or what CRC += ownerMask; CRC += nextOwnerMask; CRC += everyoneMask; CRC += groupMask; // The rest of the CRC fields CRC += flags; // Flags CRC += (uint)invType; // InvType CRC += (uint)type; // Type CRC += (uint)creationDate; // CreationDate CRC += (uint)salePrice; // SalePrice CRC += (uint)((uint)saleType * 0x07073096); // SaleType return CRC; } /// <summary> /// Attempts to load a file embedded in the assembly /// </summary> /// <param name="resourceName">The filename of the resource to load</param> /// <returns>A Stream for the requested file, or null if the resource /// was not successfully loaded</returns> public static System.IO.Stream GetResourceStream(string resourceName) { return GetResourceStream(resourceName, "openmetaverse_data"); } /// <summary> /// Attempts to load a file either embedded in the assembly or found in /// a given search path /// </summary> /// <param name="resourceName">The filename of the resource to load</param> /// <param name="searchPath">An optional path that will be searched if /// the asset is not found embedded in the assembly</param> /// <returns>A Stream for the requested file, or null if the resource /// was not successfully loaded</returns> public static System.IO.Stream GetResourceStream(string resourceName, string searchPath) { if (searchPath != null) { Assembly gea = Assembly.GetEntryAssembly(); if (gea == null) gea = typeof (Helpers).Assembly; string dirname = "."; if (gea != null && gea.Location != null) { dirname = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(gea.Location), searchPath); } string filename = System.IO.Path.Combine(dirname, resourceName); try { return new System.IO.FileStream( filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); } catch (Exception ex) { Logger.Log(string.Format("Failed opening resource from file {0}: {1}", filename, ex.Message), LogLevel.Error); } } else { try { System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); if (a == null) a = typeof (Helpers).Assembly; System.IO.Stream s = a.GetManifestResourceStream("OpenMetaverse.Resources." + resourceName); if (s != null) return s; } catch (Exception ex) { Logger.Log(string.Format("Failed opening resource stream: {0}", ex.Message), LogLevel.Error); } } return null; } /// <summary> /// Converts a list of primitives to an object that can be serialized /// with the LLSD system /// </summary> /// <param name="prims">Primitives to convert to a serializable object</param> /// <returns>An object that can be serialized with LLSD</returns> public static StructuredData.OSD PrimListToOSD(List<Primitive> prims) { StructuredData.OSDMap map = new OpenMetaverse.StructuredData.OSDMap(prims.Count); for (int i = 0; i < prims.Count; i++) map.Add(prims[i].LocalID.ToString(), prims[i].GetOSD()); return map; } /// <summary> /// Deserializes OSD in to a list of primitives /// </summary> /// <param name="osd">Structure holding the serialized primitive list, /// must be of the SDMap type</param> /// <returns>A list of deserialized primitives</returns> public static List<Primitive> OSDToPrimList(StructuredData.OSD osd) { if (osd.Type != StructuredData.OSDType.Map) throw new ArgumentException("LLSD must be in the Map structure"); StructuredData.OSDMap map = (StructuredData.OSDMap)osd; List<Primitive> prims = new List<Primitive>(map.Count); foreach (KeyValuePair<string, StructuredData.OSD> kvp in map) { Primitive prim = Primitive.FromOSD(kvp.Value); prim.LocalID = UInt32.Parse(kvp.Key); prims.Add(prim); } return prims; } /// <summary> /// Converts a struct or class object containing fields only into a key value separated string /// </summary> /// <param name="t">The struct object</param> /// <returns>A string containing the struct fields as the keys, and the field value as the value separated</returns> /// <example> /// <code> /// // Add the following code to any struct or class containing only fields to override the ToString() /// // method to display the values of the passed object /// /// /// <summary>Print the struct data as a string</summary> /// ///<returns>A string containing the field name, and field value</returns> ///public override string ToString() ///{ /// return Helpers.StructToString(this); ///} /// </code> /// </example> public static string StructToString(object t) { StringBuilder result = new StringBuilder(); Type structType = t.GetType(); FieldInfo[] fields = structType.GetFields(); if (fields == null || fields.Length == 0) { foreach (PropertyInfo prop in structType.GetProperties()) { result.Append(prop.Name + ": " + prop.GetValue(t, null) + " "); } } else { foreach (FieldInfo field in fields) { result.Append(field.Name + ": " + field.GetValue(t) + " "); } } result.AppendLine(); return result.ToString().TrimEnd(); } } }
// 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. // // 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.Batch.Protocol { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for JobScheduleOperations. /// </summary> public static partial class JobScheduleOperationsExtensions { /// <summary> /// Checks the specified job schedule exists. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule which you want to check. /// </param> /// <param name='jobScheduleExistsOptions'> /// Additional parameters for the operation /// </param> public static bool Exists(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleExistsOptions jobScheduleExistsOptions = default(JobScheduleExistsOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).ExistsAsync(jobScheduleId, jobScheduleExistsOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks the specified job schedule exists. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule which you want to check. /// </param> /// <param name='jobScheduleExistsOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<bool> ExistsAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleExistsOptions jobScheduleExistsOptions = default(JobScheduleExistsOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ExistsWithHttpMessagesAsync(jobScheduleId, jobScheduleExistsOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a job schedule from the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to delete. /// </param> /// <param name='jobScheduleDeleteOptions'> /// Additional parameters for the operation /// </param> public static JobScheduleDeleteHeaders Delete(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleDeleteOptions jobScheduleDeleteOptions = default(JobScheduleDeleteOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).DeleteAsync(jobScheduleId, jobScheduleDeleteOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a job schedule from the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to delete. /// </param> /// <param name='jobScheduleDeleteOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobScheduleDeleteHeaders> DeleteAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleDeleteOptions jobScheduleDeleteOptions = default(JobScheduleDeleteOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(jobScheduleId, jobScheduleDeleteOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets information about the specified job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to get. /// </param> /// <param name='jobScheduleGetOptions'> /// Additional parameters for the operation /// </param> public static CloudJobSchedule Get(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleGetOptions jobScheduleGetOptions = default(JobScheduleGetOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).GetAsync(jobScheduleId, jobScheduleGetOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets information about the specified job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to get. /// </param> /// <param name='jobScheduleGetOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CloudJobSchedule> GetAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleGetOptions jobScheduleGetOptions = default(JobScheduleGetOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(jobScheduleId, jobScheduleGetOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the properties of the specified job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to update. /// </param> /// <param name='jobSchedulePatchParameter'> /// The parameters for the request. /// </param> /// <param name='jobSchedulePatchOptions'> /// Additional parameters for the operation /// </param> public static JobSchedulePatchHeaders Patch(this IJobScheduleOperations operations, string jobScheduleId, JobSchedulePatchParameter jobSchedulePatchParameter, JobSchedulePatchOptions jobSchedulePatchOptions = default(JobSchedulePatchOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).PatchAsync(jobScheduleId, jobSchedulePatchParameter, jobSchedulePatchOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the properties of the specified job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to update. /// </param> /// <param name='jobSchedulePatchParameter'> /// The parameters for the request. /// </param> /// <param name='jobSchedulePatchOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobSchedulePatchHeaders> PatchAsync(this IJobScheduleOperations operations, string jobScheduleId, JobSchedulePatchParameter jobSchedulePatchParameter, JobSchedulePatchOptions jobSchedulePatchOptions = default(JobSchedulePatchOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PatchWithHttpMessagesAsync(jobScheduleId, jobSchedulePatchParameter, jobSchedulePatchOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Updates the properties of the specified job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to update. /// </param> /// <param name='jobScheduleUpdateParameter'> /// The parameters for the request. /// </param> /// <param name='jobScheduleUpdateOptions'> /// Additional parameters for the operation /// </param> public static JobScheduleUpdateHeaders Update(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleUpdateParameter jobScheduleUpdateParameter, JobScheduleUpdateOptions jobScheduleUpdateOptions = default(JobScheduleUpdateOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).UpdateAsync(jobScheduleId, jobScheduleUpdateParameter, jobScheduleUpdateOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the properties of the specified job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to update. /// </param> /// <param name='jobScheduleUpdateParameter'> /// The parameters for the request. /// </param> /// <param name='jobScheduleUpdateOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobScheduleUpdateHeaders> UpdateAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleUpdateParameter jobScheduleUpdateParameter, JobScheduleUpdateOptions jobScheduleUpdateOptions = default(JobScheduleUpdateOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(jobScheduleId, jobScheduleUpdateParameter, jobScheduleUpdateOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Disables a job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to disable. /// </param> /// <param name='jobScheduleDisableOptions'> /// Additional parameters for the operation /// </param> public static JobScheduleDisableHeaders Disable(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleDisableOptions jobScheduleDisableOptions = default(JobScheduleDisableOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).DisableAsync(jobScheduleId, jobScheduleDisableOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Disables a job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to disable. /// </param> /// <param name='jobScheduleDisableOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobScheduleDisableHeaders> DisableAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleDisableOptions jobScheduleDisableOptions = default(JobScheduleDisableOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DisableWithHttpMessagesAsync(jobScheduleId, jobScheduleDisableOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Enables a job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to enable. /// </param> /// <param name='jobScheduleEnableOptions'> /// Additional parameters for the operation /// </param> public static JobScheduleEnableHeaders Enable(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleEnableOptions jobScheduleEnableOptions = default(JobScheduleEnableOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).EnableAsync(jobScheduleId, jobScheduleEnableOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enables a job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to enable. /// </param> /// <param name='jobScheduleEnableOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobScheduleEnableHeaders> EnableAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleEnableOptions jobScheduleEnableOptions = default(JobScheduleEnableOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.EnableWithHttpMessagesAsync(jobScheduleId, jobScheduleEnableOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Terminates a job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to terminates. /// </param> /// <param name='jobScheduleTerminateOptions'> /// Additional parameters for the operation /// </param> public static JobScheduleTerminateHeaders Terminate(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleTerminateOptions jobScheduleTerminateOptions = default(JobScheduleTerminateOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).TerminateAsync(jobScheduleId, jobScheduleTerminateOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Terminates a job schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleId'> /// The id of the job schedule to terminates. /// </param> /// <param name='jobScheduleTerminateOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobScheduleTerminateHeaders> TerminateAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleTerminateOptions jobScheduleTerminateOptions = default(JobScheduleTerminateOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.TerminateWithHttpMessagesAsync(jobScheduleId, jobScheduleTerminateOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Adds a job schedule to the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cloudJobSchedule'> /// The job schedule to be added. /// </param> /// <param name='jobScheduleAddOptions'> /// Additional parameters for the operation /// </param> public static JobScheduleAddHeaders Add(this IJobScheduleOperations operations, JobScheduleAddParameter cloudJobSchedule, JobScheduleAddOptions jobScheduleAddOptions = default(JobScheduleAddOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).AddAsync(cloudJobSchedule, jobScheduleAddOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Adds a job schedule to the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cloudJobSchedule'> /// The job schedule to be added. /// </param> /// <param name='jobScheduleAddOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobScheduleAddHeaders> AddAsync(this IJobScheduleOperations operations, JobScheduleAddParameter cloudJobSchedule, JobScheduleAddOptions jobScheduleAddOptions = default(JobScheduleAddOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.AddWithHttpMessagesAsync(cloudJobSchedule, jobScheduleAddOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Lists all of the job schedules in the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleListOptions'> /// Additional parameters for the operation /// </param> public static IPage<CloudJobSchedule> List(this IJobScheduleOperations operations, JobScheduleListOptions jobScheduleListOptions = default(JobScheduleListOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).ListAsync(jobScheduleListOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all of the job schedules in the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='jobScheduleListOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<CloudJobSchedule>> ListAsync(this IJobScheduleOperations operations, JobScheduleListOptions jobScheduleListOptions = default(JobScheduleListOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(jobScheduleListOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all of the job schedules in the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='jobScheduleListNextOptions'> /// Additional parameters for the operation /// </param> public static IPage<CloudJobSchedule> ListNext(this IJobScheduleOperations operations, string nextPageLink, JobScheduleListNextOptions jobScheduleListNextOptions = default(JobScheduleListNextOptions)) { return Task.Factory.StartNew(s => ((IJobScheduleOperations)s).ListNextAsync(nextPageLink, jobScheduleListNextOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all of the job schedules in the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='jobScheduleListNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<CloudJobSchedule>> ListNextAsync(this IJobScheduleOperations operations, string nextPageLink, JobScheduleListNextOptions jobScheduleListNextOptions = default(JobScheduleListNextOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, jobScheduleListNextOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using UnityEngine; public class Player : MonoBehaviour, IPausable, IPowerUpAble, IMortalFall, IReloadable { private static Player instance = null; private static bool duplicated = false; // usefull to avoid onDestroy() execution on duplicated instances being destroyed public float walkVelocity = 10f; public float lightJumpVelocity = 40f; public float gainJumpFactor = 1.4f; private Jump jump; private PlayerWalk walk; private PlayerDieAnim dieAnim; private Crouch crouch; private Idle idle; private Teleportable teleportable; private PowerUp powerUp; private LookDirections lookDirections; private ChipmunkBody body; private bool doNotResume; /// the position where the bullets start firing private Transform firePivot; private Vector2 rightFireDir, leftFireDir, fireDir; /// used for downwards ray casting private bool exitedFromScenery; private Vector2 queryOffset = Vector2.up * -3.2f; private string collisionGroupSkip; private uint collisionLayersSkip; public static Player Instance { get { if (instance == null) { instance = GameObject.FindObjectOfType(typeof(Player)) as Player; if (instance == null) { // instantiate the entire prefab. Don't assign to the instance variable because it is then assigned in Awake() GameObject.Instantiate(Resources.Load(KResources.MARIO)); } } return instance; } } void Awake () { if (instance != null && instance != this) { duplicated = true; Destroy(gameObject); } else { instance = this; DontDestroyOnLoad(gameObject); initialize(); } } void Start () { PauseGameManager.Instance.register(this as IPausable, gameObject); ReloadableManager.Instance.register(this as IReloadable, transform.position); } private void initialize () { jump = GetComponent<Jump>(); walk = GetComponent<PlayerWalk>(); firePivot = transform.FindChild("FirePivot"); teleportable = GetComponent<Teleportable>(); dieAnim = GetComponent<PlayerDieAnim>(); crouch = GetComponent<Crouch>(); idle = GetComponent<Idle>(); lookDirections = GetComponent<LookDirections>(); body = GetComponent<ChipmunkBody>(); rightFireDir.x = 1f; rightFireDir.y = -0.5f; leftFireDir.x = -1f; leftFireDir.y = -0.5f; fireDir = rightFireDir; collisionGroupSkip = GetComponent<ChipmunkShape>().collisionGroup; // not sure if ok: all layers except Player's layer collisionLayersSkip = unchecked((uint)(1 << KLayers.PLAYER)); //collisionLayers = 0; } void OnDestroy () { GameObjectTools.ChipmunkBodyDestroy(body, GetComponent<ChipmunkShape>()); // this is to avoid nullifying or destroying static variables. Intance variables can be destroyed before this check if (duplicated) { duplicated = false; // reset the flag for next time return; } PauseGameManager.Instance.remove(this as IPausable); instance = null; } public void onReloadLevel (Vector3 spawnPos) { enabled = true; // enable Update() and OnGUI() if (teleportable != null) teleportable.reset(); setPowerUp(null); jump.reset(); if (walk.isLookingRight()) fireDir = rightFireDir; else fireDir = leftFireDir; walk.reset(); } public bool DoNotResume { get {return doNotResume;} set {doNotResume = value;} } public void beforePause () {} public void afterResume () {} public bool isSceneOnly () { // used for allocation in subscriber lists managed by PauseGameManager return false; } // Update is called once per frame void Update () { bool isIdle = true; // This sets the correct jump status when the player without jumping enters on free fall state. // Also corrects a sprite animation flickering when walking because the animation starts again // constantly after jump.resetStatus() if (exitedFromScenery && !jump.isJumping()) { ChipmunkSegmentQueryInfo qinfo; // check if there is no shape below us Vector2 end = body.position + queryOffset; Chipmunk.SegmentQueryFirst(body.position, end, collisionLayersSkip, collisionGroupSkip, out qinfo); // if no handler it means no hit if (System.IntPtr.Zero == qinfo._shapeHandle) { jump.reset(); // set state as if were jumping } } // jump if (Gamepad.Instance.isA()) { walk.stop(); jump.jump(lightJumpVelocity); // apply gain jump power. Only once per jump (handled in Jump component) if (Gamepad.Instance.isHardPressed(EnumButton.A)) jump.applyGain(gainJumpFactor); isIdle = false; } // power up action if (powerUp != null && powerUp.ableToUse()) powerUp.action(gameObject); // walk if (Gamepad.Instance.isLeft()) { // is speed up button being pressed? if (Gamepad.Instance.isB()) walk.setGain(walk.speedUpFactor); else walk.setGain(1f); walk.walk(-walkVelocity); fireDir = leftFireDir; } else if (Gamepad.Instance.isRight()) { // is speed up button being pressed? if (Gamepad.Instance.isB()) walk.setGain(walk.speedUpFactor); else walk.setGain(1f); walk.walk(walkVelocity); fireDir = rightFireDir; } if (walk.isWalking()) isIdle = false; // crouch if (Gamepad.Instance.isDown()) { crouch.crouch(); isIdle = false; } else crouch.noCrouch(); // look upwards/downwards if (!jump.isJumping()) { if (Gamepad.Instance.isUp()) { lookDirections.lookUpwards(); isIdle = false; } else lookDirections.restore(); } else lookDirections.lockYWhenJumping(); // finally only if not doing any action then set idle state if (isIdle) idle.setIdle(false); } public void dieWhenFalling () { dieAnim.restorePlayerProps(); LevelManager.Instance.loseGame(false); } public void die () { // disable this componenet this.enabled = false; // do animation dieAnim.startAnimation(); } public bool isDying () { return dieAnim.isDying(); } public bool isJumping () { return jump.isJumping(); } /// <summary> /// Used when the player kills an enemy from above or similar situations /// </summary> public void forceJump () { jump.forceJump(lightJumpVelocity); } public void setPowerUp (PowerUp pPowerUp) { powerUp = pPowerUp; } public Transform getFirePivot () { return firePivot; } public Vector3 getFireDir () { return fireDir; } public void locateAt (Vector2 pos) { transform.position = pos; body._UpdatedTransform(); // update the body position } public static bool beginCollisionWithScenery (ChipmunkArbiter arbiter) { ChipmunkShape shape1, shape2; // The order of the arguments matches the order in the function name. arbiter.GetShapes(out shape1, out shape2); Player player = shape1.getOwnComponent<Player>(); if (player.isDying()) return false; // stop collision with scenery since this frame player.exitedFromScenery = false; // Avoid ground penetration (Y axis). Another way: see collisionBias and/or minPenetrationForPenalty config in CollisionManagerCP. // Currently is being addressed by AirGroundControlUpdater and in WalkAbs /*if (GameObjectTools.isGrounded(arbiter)) { Vector2 thePos = player.body.position; float depth = arbiter.GetDepth(0); thePos.y -= depth; player.body.position = thePos; }*/ // Returning false from a begin callback means to ignore the collision response for these two colliding shapes // until they separate. Also for current frame. Ignore() does the same but next fixed step. return true; } public static void endCollisionWithScenery (ChipmunkArbiter arbiter) { ChipmunkShape shape1, shape2; // The order of the arguments matches the order in the function name. arbiter.GetShapes(out shape1, out shape2); Player player = shape1.getOwnComponent<Player>(); player.exitedFromScenery = true; } public static bool beginCollisionWithOneway (ChipmunkArbiter arbiter) { ChipmunkShape shape1, shape2; // The order of the arguments matches the order in the function name. arbiter.GetShapes(out shape1, out shape2); // if collision starts from below then proceed to the oneway platform logic if (GameObjectTools.isHitFromBelow(arbiter)) { shape1.GetComponent<ClimbDownFromPlatform>().setTraversingUpwards(true); return true; // return true so the PreSolve condition continues } // collisiion from above, then player is on platform else { shape1.GetComponent<ClimbDownFromPlatform>().handleLanding(); } // oneway platform logic was not met return false; } public static bool presolveCollisionWithOneway (ChipmunkArbiter arbiter) { ChipmunkShape shape1, shape2; // The order of the arguments matches the order in the function name. arbiter.GetShapes(out shape1, out shape2); // if collision was from below then continue with oneway platform logic if (GameObjectTools.isHitFromBelow(arbiter)) { arbiter.Ignore(); return false; } Player player = shape1.getOwnComponent<Player>(); // if player wants to climb down (once it is over the platform) then disable the collision to start free fall if (player.GetComponent<ClimbDownFromPlatform>().isClimbingDown()) { player.jump.reset(); // set state as if were jumping arbiter.Ignore(); return false; } // let the collision happens return true; } public static void endCollisionWithOneway (ChipmunkArbiter arbiter) { ChipmunkShape shape1, shape2; // The order of the arguments matches the order in the function name. arbiter.GetShapes(out shape1, out shape2); Player player = shape1.getOwnComponent<Player>(); //player.jump.resetStatus(); // set state as if were jumping player.exitedFromScenery = true; // If was traversing the platform from below then the player is over the platform. // Correct inner state is treated by the invoked method player.GetComponent<ClimbDownFromPlatform>().handleSeparation(); } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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.Diagnostics; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Utils; using NUnit.Framework; namespace Grpc.Core.Tests { public class ClientServerTest { const string Host = "localhost"; const string ServiceName = "/tests.Test"; static readonly Method<string, string> EchoMethod = new Method<string, string>( MethodType.Unary, "/tests.Test/Echo", Marshallers.StringMarshaller, Marshallers.StringMarshaller); static readonly Method<string, string> ConcatAndEchoMethod = new Method<string, string>( MethodType.ClientStreaming, "/tests.Test/ConcatAndEcho", Marshallers.StringMarshaller, Marshallers.StringMarshaller); static readonly Method<string, string> NonexistentMethod = new Method<string, string>( MethodType.Unary, "/tests.Test/NonexistentMethod", Marshallers.StringMarshaller, Marshallers.StringMarshaller); static readonly ServerServiceDefinition ServiceDefinition = ServerServiceDefinition.CreateBuilder(ServiceName) .AddMethod(EchoMethod, EchoHandler) .AddMethod(ConcatAndEchoMethod, ConcatAndEchoHandler) .Build(); Server server; Channel channel; [SetUp] public void Init() { server = new Server(); server.AddServiceDefinition(ServiceDefinition); int port = server.AddListeningPort(Host, Server.PickUnusedPort); server.Start(); channel = new Channel(Host, port); } [TearDown] public void Cleanup() { channel.Dispose(); server.ShutdownAsync().Wait(); } [TestFixtureTearDown] public void CleanupClass() { GrpcEnvironment.Shutdown(); } [Test] public void UnaryCall() { var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); Assert.AreEqual("ABC", Calls.BlockingUnaryCall(call, "ABC", CancellationToken.None)); } [Test] public void UnaryCall_ServerHandlerThrows() { var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); try { Calls.BlockingUnaryCall(call, "THROW", CancellationToken.None); Assert.Fail(); } catch (RpcException e) { Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode); } } [Test] public void AsyncUnaryCall() { var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); var result = Calls.AsyncUnaryCall(call, "ABC", CancellationToken.None).Result; Assert.AreEqual("ABC", result); } [Test] public void AsyncUnaryCall_ServerHandlerThrows() { Task.Run(async () => { var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); try { await Calls.AsyncUnaryCall(call, "THROW", CancellationToken.None); Assert.Fail(); } catch (RpcException e) { Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode); } }).Wait(); } [Test] public void ClientStreamingCall() { Task.Run(async () => { var call = new Call<string, string>(ServiceName, ConcatAndEchoMethod, channel, Metadata.Empty); var callResult = Calls.AsyncClientStreamingCall(call, CancellationToken.None); await callResult.RequestStream.WriteAll(new string[] { "A", "B", "C" }); Assert.AreEqual("ABC", await callResult.Result); }).Wait(); } [Test] public void ClientStreamingCall_CancelAfterBegin() { Task.Run(async () => { var call = new Call<string, string>(ServiceName, ConcatAndEchoMethod, channel, Metadata.Empty); var cts = new CancellationTokenSource(); var callResult = Calls.AsyncClientStreamingCall(call, cts.Token); // TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it. await Task.Delay(1000); cts.Cancel(); try { await callResult.Result; } catch (RpcException e) { Assert.AreEqual(StatusCode.Cancelled, e.Status.StatusCode); } }).Wait(); } [Test] public void UnaryCall_DisposedChannel() { channel.Dispose(); var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); Assert.Throws(typeof(ObjectDisposedException), () => Calls.BlockingUnaryCall(call, "ABC", CancellationToken.None)); } [Test] public void UnaryCallPerformance() { var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); BenchmarkUtil.RunBenchmark(100, 100, () => { Calls.BlockingUnaryCall(call, "ABC", default(CancellationToken)); }); } [Test] public void UnknownMethodHandler() { var call = new Call<string, string>(ServiceName, NonexistentMethod, channel, Metadata.Empty); try { Calls.BlockingUnaryCall(call, "ABC", default(CancellationToken)); Assert.Fail(); } catch (RpcException e) { Assert.AreEqual(StatusCode.Unimplemented, e.Status.StatusCode); } } private static async Task<string> EchoHandler(ServerCallContext context, string request) { if (request == "THROW") { throw new Exception("This was thrown on purpose by a test"); } return request; } private static async Task<string> ConcatAndEchoHandler(ServerCallContext context, IAsyncStreamReader<string> requestStream) { string result = ""; await requestStream.ForEach(async (request) => { if (request == "THROW") { throw new Exception("This was thrown on purpose by a test"); } result += request; }); // simulate processing takes some time. await Task.Delay(250); return result; } } }
using System; using System.Collections.Generic; using System.Text; using Orleans.CodeGeneration; using Orleans.Serialization; using Orleans.Transactions; namespace Orleans.Runtime { internal class Message { public const int LENGTH_HEADER_SIZE = 8; public const int LENGTH_META_HEADER = 4; [NonSerialized] private string _targetHistory; [NonSerialized] private DateTime? _queuedTime; [NonSerialized] private int _retryCount; public string TargetHistory { get { return _targetHistory; } set { _targetHistory = value; } } public DateTime? QueuedTime { get { return _queuedTime; } set { _queuedTime = value; } } public int RetryCount { get { return _retryCount; } set { _retryCount = value; } } // Cache values of TargetAddess and SendingAddress as they are used very frequently private ActivationAddress targetAddress; private ActivationAddress sendingAddress; static Message() { } public enum Categories { Ping, System, Application, } public enum Directions { Request, Response, OneWay } public enum ResponseTypes { Success, Error, Rejection } public enum RejectionTypes { Transient, Overloaded, DuplicateRequest, Unrecoverable, GatewayTooBusy, CacheInvalidation } internal HeadersContainer Headers { get; set; } = new HeadersContainer(); public Categories Category { get { return Headers.Category; } set { Headers.Category = value; } } public Directions Direction { get { return Headers.Direction ?? default(Directions); } set { Headers.Direction = value; } } public bool HasDirection => Headers.Direction.HasValue; public bool IsReadOnly { get { return Headers.IsReadOnly; } set { Headers.IsReadOnly = value; } } public bool IsAlwaysInterleave { get { return Headers.IsAlwaysInterleave; } set { Headers.IsAlwaysInterleave = value; } } public bool IsUnordered { get { return Headers.IsUnordered; } set { Headers.IsUnordered = value; } } public bool IsReturnedFromRemoteCluster { get { return Headers.IsReturnedFromRemoteCluster; } set { Headers.IsReturnedFromRemoteCluster = value; } } public bool IsTransactionRequired { get { return Headers.IsTransactionRequired; } set { Headers.IsTransactionRequired = value; } } public CorrelationId Id { get { return Headers.Id; } set { Headers.Id = value; } } public int ForwardCount { get { return Headers.ForwardCount; } set { Headers.ForwardCount = value; } } public SiloAddress TargetSilo { get { return Headers.TargetSilo; } set { Headers.TargetSilo = value; targetAddress = null; } } public GrainId TargetGrain { get { return Headers.TargetGrain; } set { Headers.TargetGrain = value; targetAddress = null; } } public ActivationId TargetActivation { get { return Headers.TargetActivation; } set { Headers.TargetActivation = value; targetAddress = null; } } public ActivationAddress TargetAddress { get { if (targetAddress is object) return targetAddress; if (!TargetGrain.IsDefault) { return targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation); } return null; } set { TargetGrain = value.Grain; TargetActivation = value.Activation; TargetSilo = value.Silo; targetAddress = value; } } public SiloAddress SendingSilo { get { return Headers.SendingSilo; } set { Headers.SendingSilo = value; sendingAddress = null; } } public GrainId SendingGrain { get { return Headers.SendingGrain; } set { Headers.SendingGrain = value; sendingAddress = null; } } public ActivationId SendingActivation { get { return Headers.SendingActivation; } set { Headers.SendingActivation = value; sendingAddress = null; } } public CorrelationId CallChainId { get { return Headers.CallChainId; } set { Headers.CallChainId = value; } } public TraceContext TraceContext { get { return Headers.TraceContext; } set { Headers.TraceContext = value; } } public ActivationAddress SendingAddress { get { return sendingAddress ?? (sendingAddress = ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation)); } set { SendingGrain = value.Grain; SendingActivation = value.Activation; SendingSilo = value.Silo; sendingAddress = value; } } public bool IsNewPlacement { get { return Headers.IsNewPlacement; } set { Headers.IsNewPlacement = value; } } public ushort InterfaceVersion { get { return Headers.InterfaceVersion; } set { Headers.InterfaceVersion = value; } } public GrainInterfaceType InterfaceType { get { return Headers.InterfaceType; } set { Headers.InterfaceType = value; } } public ResponseTypes Result { get { return Headers.Result; } set { Headers.Result = value; } } public TimeSpan? TimeToLive { get { return Headers.TimeToLive; } set { Headers.TimeToLive = value; } } public bool IsExpired { get { if (!TimeToLive.HasValue) return false; return TimeToLive <= TimeSpan.Zero; } } public bool IsExpirableMessage(bool dropExpiredMessages) { if (!dropExpiredMessages) return false; GrainId id = TargetGrain; if (id == null) return false; // don't set expiration for one way, system target and system grain messages. return Direction != Directions.OneWay && !id.IsSystemTarget(); } public ITransactionInfo TransactionInfo { get { return Headers.TransactionInfo; } set { Headers.TransactionInfo = value; } } public List<ActivationAddress> CacheInvalidationHeader { get { return Headers.CacheInvalidationHeader; } set { Headers.CacheInvalidationHeader = value; } } public bool HasCacheInvalidationHeader => this.CacheInvalidationHeader != null && this.CacheInvalidationHeader.Count > 0; internal void AddToCacheInvalidationHeader(ActivationAddress address) { var list = new List<ActivationAddress>(); if (CacheInvalidationHeader != null) { list.AddRange(CacheInvalidationHeader); } list.Add(address); CacheInvalidationHeader = list; } public RejectionTypes RejectionType { get { return Headers.RejectionType; } set { Headers.RejectionType = value; } } public string RejectionInfo { get { return GetNotNullString(Headers.RejectionInfo); } set { Headers.RejectionInfo = value; } } public Dictionary<string, object> RequestContextData { get { return Headers.RequestContextData; } set { Headers.RequestContextData = value; } } public object BodyObject { get; set; } public void ClearTargetAddress() { targetAddress = null; } private static string GetNotNullString(string s) { return s ?? string.Empty; } /// <summary> /// Tell whether two messages are duplicates of one another /// </summary> /// <param name="other"></param> /// <returns></returns> public bool IsDuplicate(Message other) { return Equals(SendingSilo, other.SendingSilo) && Equals(Id, other.Id); } // For testing and logging/tracing public string ToLongString() { var sb = new StringBuilder(); AppendIfExists(HeadersContainer.Headers.CACHE_INVALIDATION_HEADER, sb, (m) => m.CacheInvalidationHeader); AppendIfExists(HeadersContainer.Headers.CATEGORY, sb, (m) => m.Category); AppendIfExists(HeadersContainer.Headers.DIRECTION, sb, (m) => m.Direction); AppendIfExists(HeadersContainer.Headers.TIME_TO_LIVE, sb, (m) => m.TimeToLive); AppendIfExists(HeadersContainer.Headers.FORWARD_COUNT, sb, (m) => m.ForwardCount); AppendIfExists(HeadersContainer.Headers.CORRELATION_ID, sb, (m) => m.Id); AppendIfExists(HeadersContainer.Headers.ALWAYS_INTERLEAVE, sb, (m) => m.IsAlwaysInterleave); AppendIfExists(HeadersContainer.Headers.IS_NEW_PLACEMENT, sb, (m) => m.IsNewPlacement); AppendIfExists(HeadersContainer.Headers.IS_RETURNED_FROM_REMOTE_CLUSTER, sb, (m) => m.IsReturnedFromRemoteCluster); AppendIfExists(HeadersContainer.Headers.READ_ONLY, sb, (m) => m.IsReadOnly); AppendIfExists(HeadersContainer.Headers.IS_UNORDERED, sb, (m) => m.IsUnordered); AppendIfExists(HeadersContainer.Headers.REJECTION_INFO, sb, (m) => m.RejectionInfo); AppendIfExists(HeadersContainer.Headers.REJECTION_TYPE, sb, (m) => m.RejectionType); AppendIfExists(HeadersContainer.Headers.REQUEST_CONTEXT, sb, (m) => m.RequestContextData); AppendIfExists(HeadersContainer.Headers.RESULT, sb, (m) => m.Result); AppendIfExists(HeadersContainer.Headers.SENDING_ACTIVATION, sb, (m) => m.SendingActivation); AppendIfExists(HeadersContainer.Headers.SENDING_GRAIN, sb, (m) => m.SendingGrain); AppendIfExists(HeadersContainer.Headers.SENDING_SILO, sb, (m) => m.SendingSilo); AppendIfExists(HeadersContainer.Headers.TARGET_ACTIVATION, sb, (m) => m.TargetActivation); AppendIfExists(HeadersContainer.Headers.TARGET_GRAIN, sb, (m) => m.TargetGrain); AppendIfExists(HeadersContainer.Headers.CALL_CHAIN_ID, sb, (m) => m.CallChainId); AppendIfExists(HeadersContainer.Headers.TRACE_CONTEXT, sb, (m) => m.TraceContext); AppendIfExists(HeadersContainer.Headers.TARGET_SILO, sb, (m) => m.TargetSilo); return sb.ToString(); } private void AppendIfExists(HeadersContainer.Headers header, StringBuilder sb, Func<Message, object> valueProvider) { // used only under log3 level if ((Headers.GetHeadersMask() & header) != HeadersContainer.Headers.NONE) { sb.AppendFormat("{0}={1};", header, valueProvider(this)); sb.AppendLine(); } } public override string ToString() { string response = String.Empty; if (Direction == Directions.Response) { switch (Result) { case ResponseTypes.Error: response = "Error "; break; case ResponseTypes.Rejection: response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo); break; default: break; } } return String.Format("{0}{1}{2}{3}{4} {5}->{6} #{7}{8}", IsReadOnly ? "ReadOnly " : "", //0 IsAlwaysInterleave ? "IsAlwaysInterleave " : "", //1 IsNewPlacement ? "NewPlacement " : "", // 2 response, //3 Direction, //4 $"[{SendingSilo} {SendingGrain} {SendingActivation}]", //5 $"[{TargetSilo} {TargetGrain} {TargetActivation}]", //6 Id, //7 ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : ""); //8 } internal void SetTargetPlacement(PlacementResult value) { TargetActivation = value.Activation; TargetSilo = value.Silo; if (value.IsNewPlacement) IsNewPlacement = true; } public string GetTargetHistory() { var history = new StringBuilder(); history.Append("<"); if (TargetSilo != null) { history.Append(TargetSilo).Append(":"); } if (TargetGrain != null) { history.Append(TargetGrain).Append(":"); } if (TargetActivation is object) { history.Append(TargetActivation); } history.Append(">"); if (!string.IsNullOrEmpty(TargetHistory)) { history.Append(" ").Append(TargetHistory); } return history.ToString(); } // For statistical measuring of time spent in queues. private ITimeInterval timeInterval; public void Start() { timeInterval = TimeIntervalFactory.CreateTimeInterval(true); timeInterval.Start(); } public void Stop() { timeInterval.Stop(); } public void Restart() { timeInterval.Restart(); } public TimeSpan Elapsed { get { return timeInterval.Elapsed; } } public static Message CreatePromptExceptionResponse(Message request, Exception exception) { return new Message { Category = request.Category, Direction = Message.Directions.Response, Result = Message.ResponseTypes.Error, BodyObject = Response.ExceptionResponse(exception) }; } private static int BufferLength(List<ArraySegment<byte>> buffer) { var result = 0; for (var i = 0; i < buffer.Count; i++) { result += buffer[i].Count; } return result; } [Serializable] public class HeadersContainer { [Flags] public enum Headers { NONE = 0, ALWAYS_INTERLEAVE = 1 << 0, CACHE_INVALIDATION_HEADER = 1 << 1, CATEGORY = 1 << 2, CORRELATION_ID = 1 << 3, DEBUG_CONTEXT = 1 << 4, // No longer used DIRECTION = 1 << 5, TIME_TO_LIVE = 1 << 6, FORWARD_COUNT = 1 << 7, NEW_GRAIN_TYPE = 1 << 8, GENERIC_GRAIN_TYPE = 1 << 9, RESULT = 1 << 10, REJECTION_INFO = 1 << 11, REJECTION_TYPE = 1 << 12, READ_ONLY = 1 << 13, RESEND_COUNT = 1 << 14, // Support removed. Value retained for backwards compatibility. SENDING_ACTIVATION = 1 << 15, SENDING_GRAIN = 1 <<16, SENDING_SILO = 1 << 17, IS_NEW_PLACEMENT = 1 << 18, TARGET_ACTIVATION = 1 << 19, TARGET_GRAIN = 1 << 20, TARGET_SILO = 1 << 21, TARGET_OBSERVER = 1 << 22, IS_UNORDERED = 1 << 23, REQUEST_CONTEXT = 1 << 24, IS_RETURNED_FROM_REMOTE_CLUSTER = 1 << 25, INTERFACE_VERSION = 1 << 26, // transactions TRANSACTION_INFO = 1 << 27, IS_TRANSACTION_REQUIRED = 1 << 28, CALL_CHAIN_ID = 1 << 29, TRACE_CONTEXT = 1 << 30, INTERFACE_TYPE = 1 << 31 // Do not add over int.MaxValue of these. } private Categories _category; private Directions? _direction; private bool _isReadOnly; private bool _isAlwaysInterleave; private bool _isUnordered; private bool _isReturnedFromRemoteCluster; private bool _isTransactionRequired; private CorrelationId _id; private int _forwardCount; private SiloAddress _targetSilo; private GrainId _targetGrain; private ActivationId _targetActivation; private SiloAddress _sendingSilo; private GrainId _sendingGrain; private ActivationId _sendingActivation; private bool _isNewPlacement; private ushort _interfaceVersion; private ResponseTypes _result; private ITransactionInfo _transactionInfo; private TimeSpan? _timeToLive; private List<ActivationAddress> _cacheInvalidationHeader; private RejectionTypes _rejectionType; private string _rejectionInfo; private Dictionary<string, object> _requestContextData; private CorrelationId _callChainId; private readonly DateTime _localCreationTime; private TraceContext _traceContext; private GrainInterfaceType interfaceType; public HeadersContainer() { _localCreationTime = DateTime.UtcNow; } public TraceContext TraceContext { get { return _traceContext; } set { _traceContext = value; } } public Categories Category { get { return _category; } set { _category = value; } } public Directions? Direction { get { return _direction; } set { _direction = value; } } public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; } } public bool IsAlwaysInterleave { get { return _isAlwaysInterleave; } set { _isAlwaysInterleave = value; } } public bool IsUnordered { get { return _isUnordered; } set { _isUnordered = value; } } public bool IsReturnedFromRemoteCluster { get { return _isReturnedFromRemoteCluster; } set { _isReturnedFromRemoteCluster = value; } } public bool IsTransactionRequired { get { return _isTransactionRequired; } set { _isTransactionRequired = value; } } public CorrelationId Id { get { return _id; } set { _id = value; } } public int ForwardCount { get { return _forwardCount; } set { _forwardCount = value; } } public SiloAddress TargetSilo { get { return _targetSilo; } set { _targetSilo = value; } } public GrainId TargetGrain { get { return _targetGrain; } set { _targetGrain = value; } } public ActivationId TargetActivation { get { return _targetActivation; } set { _targetActivation = value; } } public SiloAddress SendingSilo { get { return _sendingSilo; } set { _sendingSilo = value; } } public GrainId SendingGrain { get { return _sendingGrain; } set { _sendingGrain = value; } } public ActivationId SendingActivation { get { return _sendingActivation; } set { _sendingActivation = value; } } public bool IsNewPlacement { get { return _isNewPlacement; } set { _isNewPlacement = value; } } public ushort InterfaceVersion { get { return _interfaceVersion; } set { _interfaceVersion = value; } } public ResponseTypes Result { get { return _result; } set { _result = value; } } public ITransactionInfo TransactionInfo { get { return _transactionInfo; } set { _transactionInfo = value; } } public TimeSpan? TimeToLive { get { return _timeToLive - (DateTime.UtcNow - _localCreationTime); } set { _timeToLive = value; } } public List<ActivationAddress> CacheInvalidationHeader { get { return _cacheInvalidationHeader; } set { _cacheInvalidationHeader = value; } } public RejectionTypes RejectionType { get { return _rejectionType; } set { _rejectionType = value; } } public string RejectionInfo { get { return _rejectionInfo; } set { _rejectionInfo = value; } } public Dictionary<string, object> RequestContextData { get { return _requestContextData; } set { _requestContextData = value; } } public CorrelationId CallChainId { get { return _callChainId; } set { _callChainId = value; } } public GrainInterfaceType InterfaceType { get { return interfaceType; } set { interfaceType = value; } } internal Headers GetHeadersMask() { Headers headers = Headers.NONE; if(Category != default(Categories)) headers = headers | Headers.CATEGORY; headers = _direction == null ? headers & ~Headers.DIRECTION : headers | Headers.DIRECTION; if (IsReadOnly) headers = headers | Headers.READ_ONLY; if (IsAlwaysInterleave) headers = headers | Headers.ALWAYS_INTERLEAVE; if(IsUnordered) headers = headers | Headers.IS_UNORDERED; headers = _id == null ? headers & ~Headers.CORRELATION_ID : headers | Headers.CORRELATION_ID; if(_forwardCount != default (int)) headers = headers | Headers.FORWARD_COUNT; headers = _targetSilo == null ? headers & ~Headers.TARGET_SILO : headers | Headers.TARGET_SILO; headers = _targetGrain.IsDefault ? headers & ~Headers.TARGET_GRAIN : headers | Headers.TARGET_GRAIN; headers = _targetActivation is null ? headers & ~Headers.TARGET_ACTIVATION : headers | Headers.TARGET_ACTIVATION; headers = _sendingSilo is null ? headers & ~Headers.SENDING_SILO : headers | Headers.SENDING_SILO; headers = _sendingGrain.IsDefault ? headers & ~Headers.SENDING_GRAIN : headers | Headers.SENDING_GRAIN; headers = _sendingActivation is null ? headers & ~Headers.SENDING_ACTIVATION : headers | Headers.SENDING_ACTIVATION; headers = _isNewPlacement == default(bool) ? headers & ~Headers.IS_NEW_PLACEMENT : headers | Headers.IS_NEW_PLACEMENT; headers = _isReturnedFromRemoteCluster == default(bool) ? headers & ~Headers.IS_RETURNED_FROM_REMOTE_CLUSTER : headers | Headers.IS_RETURNED_FROM_REMOTE_CLUSTER; headers = _interfaceVersion == 0 ? headers & ~Headers.INTERFACE_VERSION : headers | Headers.INTERFACE_VERSION; headers = _result == default(ResponseTypes)? headers & ~Headers.RESULT : headers | Headers.RESULT; headers = _timeToLive == null ? headers & ~Headers.TIME_TO_LIVE : headers | Headers.TIME_TO_LIVE; headers = _cacheInvalidationHeader == null || _cacheInvalidationHeader.Count == 0 ? headers & ~Headers.CACHE_INVALIDATION_HEADER : headers | Headers.CACHE_INVALIDATION_HEADER; headers = _rejectionType == default(RejectionTypes) ? headers & ~Headers.REJECTION_TYPE : headers | Headers.REJECTION_TYPE; headers = string.IsNullOrEmpty(_rejectionInfo) ? headers & ~Headers.REJECTION_INFO : headers | Headers.REJECTION_INFO; headers = _requestContextData == null || _requestContextData.Count == 0 ? headers & ~Headers.REQUEST_CONTEXT : headers | Headers.REQUEST_CONTEXT; headers = _callChainId == null ? headers & ~Headers.CALL_CHAIN_ID : headers | Headers.CALL_CHAIN_ID; headers = _traceContext == null? headers & ~Headers.TRACE_CONTEXT : headers | Headers.TRACE_CONTEXT; headers = IsTransactionRequired ? headers | Headers.IS_TRANSACTION_REQUIRED : headers & ~Headers.IS_TRANSACTION_REQUIRED; headers = _transactionInfo == null ? headers & ~Headers.TRANSACTION_INFO : headers | Headers.TRANSACTION_INFO; headers = interfaceType.IsDefault ? headers & ~Headers.INTERFACE_TYPE : headers | Headers.INTERFACE_TYPE; return headers; } [CopierMethod] public static object DeepCopier(object original, ICopyContext context) { return original; } [SerializerMethod] public static void Serializer(object untypedInput, ISerializationContext context, Type expected) { HeadersContainer input = (HeadersContainer)untypedInput; var sm = context.GetSerializationManager(); var headers = input.GetHeadersMask(); var writer = context.StreamWriter; writer.Write((int)headers); if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE) { var count = input.CacheInvalidationHeader.Count; writer.Write(input.CacheInvalidationHeader.Count); for (int i = 0; i < count; i++) { WriteObj(sm, context, typeof(ActivationAddress), input.CacheInvalidationHeader[i]); } } if ((headers & Headers.CATEGORY) != Headers.NONE) { writer.Write((byte)input.Category); } if ((headers & Headers.DIRECTION) != Headers.NONE) writer.Write((byte)input.Direction.Value); if ((headers & Headers.TIME_TO_LIVE) != Headers.NONE) writer.Write(input.TimeToLive.Value); if ((headers & Headers.FORWARD_COUNT) != Headers.NONE) writer.Write(input.ForwardCount); if ((headers & Headers.CORRELATION_ID) != Headers.NONE) writer.Write(input.Id); if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE) writer.Write(input.IsAlwaysInterleave); if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE) writer.Write(input.IsNewPlacement); if ((headers & Headers.IS_RETURNED_FROM_REMOTE_CLUSTER) != Headers.NONE) writer.Write(input.IsReturnedFromRemoteCluster); if ((headers & Headers.INTERFACE_VERSION) != Headers.NONE) writer.Write(input.InterfaceVersion); if ((headers & Headers.READ_ONLY) != Headers.NONE) writer.Write(input.IsReadOnly); if ((headers & Headers.IS_UNORDERED) != Headers.NONE) writer.Write(input.IsUnordered); if ((headers & Headers.REJECTION_INFO) != Headers.NONE) writer.Write(input.RejectionInfo); if ((headers & Headers.REJECTION_TYPE) != Headers.NONE) writer.Write((byte)input.RejectionType); if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE) { var requestData = input.RequestContextData; var count = requestData.Count; writer.Write(count); foreach (var d in requestData) { writer.Write(d.Key); SerializationManager.SerializeInner(d.Value, context, typeof(object)); } } if ((headers & Headers.RESULT) != Headers.NONE) writer.Write((byte)input.Result); if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE) { writer.Write(input.SendingActivation); } if ((headers & Headers.SENDING_GRAIN) != Headers.NONE) { writer.Write(input.SendingGrain); } if ((headers & Headers.SENDING_SILO) != Headers.NONE) { writer.Write(input.SendingSilo); } if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE) { writer.Write(input.TargetActivation); } if ((headers & Headers.TARGET_GRAIN) != Headers.NONE) { writer.Write(input.TargetGrain); } if ((headers & Headers.CALL_CHAIN_ID) != Headers.NONE) { writer.Write(input.CallChainId); } if ((headers & Headers.TARGET_SILO) != Headers.NONE) { writer.Write(input.TargetSilo); } if ((headers & Headers.TRANSACTION_INFO) != Headers.NONE) SerializationManager.SerializeInner(input.TransactionInfo, context, typeof(ITransactionInfo)); if ((headers & Headers.TRACE_CONTEXT) != Headers.NONE) { SerializationManager.SerializeInner(input._traceContext, context, typeof(TraceContext)); } if ((headers & Headers.INTERFACE_TYPE) != Headers.NONE) { writer.Write(input.interfaceType); } } [DeserializerMethod] public static object Deserializer(Type expected, IDeserializationContext context) { var sm = context.GetSerializationManager(); var result = new HeadersContainer(); var reader = context.StreamReader; context.RecordObject(result); var headers = (Headers)reader.ReadInt(); if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE) { var n = reader.ReadInt(); if (n > 0) { var list = result.CacheInvalidationHeader = new List<ActivationAddress>(n); for (int i = 0; i < n; i++) { list.Add((ActivationAddress)ReadObj(sm, typeof(ActivationAddress), context)); } } } if ((headers & Headers.CATEGORY) != Headers.NONE) result.Category = (Categories)reader.ReadByte(); if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE) _ = reader.ReadString(); if ((headers & Headers.DIRECTION) != Headers.NONE) result.Direction = (Message.Directions)reader.ReadByte(); if ((headers & Headers.TIME_TO_LIVE) != Headers.NONE) result.TimeToLive = reader.ReadTimeSpan(); if ((headers & Headers.FORWARD_COUNT) != Headers.NONE) result.ForwardCount = reader.ReadInt(); if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE) _ = reader.ReadString(); if ((headers & Headers.CORRELATION_ID) != Headers.NONE) result.Id = (Orleans.Runtime.CorrelationId)ReadObj(sm, typeof(CorrelationId), context); if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE) result.IsAlwaysInterleave = ReadBool(reader); if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE) result.IsNewPlacement = ReadBool(reader); if ((headers & Headers.IS_RETURNED_FROM_REMOTE_CLUSTER) != Headers.NONE) result.IsReturnedFromRemoteCluster = ReadBool(reader); if ((headers & Headers.INTERFACE_VERSION) != Headers.NONE) result.InterfaceVersion = reader.ReadUShort(); if ((headers & Headers.READ_ONLY) != Headers.NONE) result.IsReadOnly = ReadBool(reader); if ((headers & Headers.IS_UNORDERED) != Headers.NONE) result.IsUnordered = ReadBool(reader); if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE) _ = reader.ReadString(); if ((headers & Headers.REJECTION_INFO) != Headers.NONE) result.RejectionInfo = reader.ReadString(); if ((headers & Headers.REJECTION_TYPE) != Headers.NONE) result.RejectionType = (RejectionTypes)reader.ReadByte(); if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE) { var c = reader.ReadInt(); var requestData = new Dictionary<string, object>(c); for (int i = 0; i < c; i++) { requestData[reader.ReadString()] = SerializationManager.DeserializeInner(null, context); } result.RequestContextData = requestData; } // Read for backwards compatibility but ignore the value. if ((headers & Headers.RESEND_COUNT) != Headers.NONE) reader.ReadInt(); if ((headers & Headers.RESULT) != Headers.NONE) result.Result = (Orleans.Runtime.Message.ResponseTypes)reader.ReadByte(); if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE) result.SendingActivation = reader.ReadActivationId(); if ((headers & Headers.SENDING_GRAIN) != Headers.NONE) result.SendingGrain = reader.ReadGrainId(); if ((headers & Headers.SENDING_SILO) != Headers.NONE) result.SendingSilo = reader.ReadSiloAddress(); if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE) result.TargetActivation = reader.ReadActivationId(); if ((headers & Headers.TARGET_GRAIN) != Headers.NONE) result.TargetGrain = reader.ReadGrainId(); if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE) _ = (GuidId)ReadObj(sm, typeof(GuidId), context); if ((headers & Headers.CALL_CHAIN_ID) != Headers.NONE) result.CallChainId = reader.ReadCorrelationId(); if ((headers & Headers.TARGET_SILO) != Headers.NONE) result.TargetSilo = reader.ReadSiloAddress(); result.IsTransactionRequired = (headers & Headers.IS_TRANSACTION_REQUIRED) != Headers.NONE; if ((headers & Headers.TRANSACTION_INFO) != Headers.NONE) result.TransactionInfo = SerializationManager.DeserializeInner<ITransactionInfo>(context); if ((headers & Headers.TRACE_CONTEXT) != Headers.NONE) result.TraceContext = SerializationManager.DeserializeInner<TraceContext>(context); if ((headers & Headers.INTERFACE_TYPE) != Headers.NONE) result.InterfaceType = reader.ReadGrainInterfaceType(); return result; } private static bool ReadBool(IBinaryTokenStreamReader stream) { return stream.ReadByte() == (byte) SerializationTokenType.True; } private static void WriteObj(SerializationManager sm, ISerializationContext context, Type type, object input) { var ser = sm.GetSerializer(type); ser.Invoke(input, context, type); } private static object ReadObj(SerializationManager sm, Type t, IDeserializationContext context) { var des = sm.GetDeserializer(t); return des.Invoke(t, context); } } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors; using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Update; using Microsoft.EntityFrameworkCore.ValueGeneration; using Microsoft.Extensions.DependencyInjection; using Remotion.Linq.Clauses; using Remotion.Linq.Parsing.ExpressionVisitors.TreeEvaluation; public class LocalOptionsExtension : IDbContextOptionsExtension { public string LogFragment => string.Empty; internal string RootFolder; public bool ApplyServices(IServiceCollection services) { services.AddLocalDatabase(); return true; } public long GetServiceProviderHashCode() => RootFolder?.GetHashCode() ?? 0L; public void Validate(IDbContextOptions options) { } } public class LocalValueGeneratorSelector : ValueGeneratorSelector { public LocalValueGeneratorSelector(ValueGeneratorSelectorDependencies dependencies) : base(dependencies) { } public override ValueGenerator Create(Microsoft.EntityFrameworkCore.Metadata.IProperty property, Microsoft.EntityFrameworkCore.Metadata.IEntityType entityType) { return base.Create(property, entityType); } } public interface ILocalDbDatabase : IDatabase { } public class LocalDbDatabase : Database, ILocalDbDatabase { protected LocalDbDatabase(DatabaseDependencies dependencies) : base(dependencies) { } public override int SaveChanges(IReadOnlyList<IUpdateEntry> entries) { return entries.Count; } public override Task<int> SaveChangesAsync(IReadOnlyList<IUpdateEntry> entries, CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult(SaveChanges(entries)); } } public class LocalDbTransaction : IDbContextTransaction { public Guid TransactionId { get; } = Guid.NewGuid(); public void Commit() { } public void Dispose() { } public void Rollback() { } } public class LocaDbTransactionManager : IDbContextTransactionManager { public IDbContextTransaction CurrentTransaction => null; private static readonly LocalDbTransaction _transaction = new LocalDbTransaction(); public IDbContextTransaction BeginTransaction() { return _transaction; } public Task<IDbContextTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult<IDbContextTransaction>(_transaction); } public void CommitTransaction() { } public void ResetState() { } public void RollbackTransaction() { } } public class LocalDbDatabaseCreator : IDatabaseCreator { private readonly ILocalDbDatabase _localDb; public LocalDbDatabaseCreator(ILocalDbDatabase localDb) { _localDb = localDb; } public bool EnsureCreated() { return true; } public Task<bool> EnsureCreatedAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult(EnsureCreated()); } public bool EnsureDeleted() { return true; } public Task<bool> EnsureDeletedAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult(EnsureDeleted()); } } public class LocalDbQueryContext : QueryContext { public LocalDbQueryContext(QueryContextDependencies dependencies, Func<IQueryBuffer> queryBufferFactory) : base(dependencies, queryBufferFactory) { } } public class LocalDbQueryContextFactory : QueryContextFactory { public LocalDbQueryContextFactory(QueryContextDependencies dependencies) : base(dependencies) { } public override QueryContext Create() => new LocalDbQueryContext(Dependencies, CreateQueryBuffer); } public class LocalDbEntityQueryModelVisitor : EntityQueryModelVisitor { public LocalDbEntityQueryModelVisitor(EntityQueryModelVisitorDependencies dependencies, QueryCompilationContext queryCompilationContext) : base(dependencies, queryCompilationContext) { } } public class LocalDbEntityQueryModelVisitorFactory : EntityQueryModelVisitorFactory { public LocalDbEntityQueryModelVisitorFactory(EntityQueryModelVisitorDependencies dependencies) : base(dependencies) { } public override EntityQueryModelVisitor Create(QueryCompilationContext queryCompilationContext, EntityQueryModelVisitor parentEntityQueryModelVisitor) => new LocalDbEntityQueryModelVisitor(Dependencies, queryCompilationContext); } public class LocalDbEntityQueryableExpressionVisitor : EntityQueryableExpressionVisitor { public LocalDbEntityQueryableExpressionVisitor(EntityQueryModelVisitor entityQueryModelVisitor) : base(entityQueryModelVisitor) { } protected override Expression VisitEntityQueryable(Type elementType) { return null; //var entityType = QueryModelVisitor.QueryCompilationContext.FindEntityType(_querySource) // ?? _model.FindEntityType(elementType); //if (QueryModelVisitor.QueryCompilationContext // .QuerySourceRequiresMaterialization(_querySource)) //{ // var materializer = _materializerFactory.CreateMaterializer(entityType); // return Expression.Call( // InMemoryQueryModelVisitor.EntityQueryMethodInfo.MakeGenericMethod(elementType), // EntityQueryModelVisitor.QueryContextParameter, // Expression.Constant(entityType), // Expression.Constant(entityType.FindPrimaryKey()), // materializer, // Expression.Constant(QueryModelVisitor.QueryCompilationContext.IsTrackingQuery)); //} //return Expression.Call( // InMemoryQueryModelVisitor.ProjectionQueryMethodInfo, // EntityQueryModelVisitor.QueryContextParameter, // Expression.Constant(entityType)); } } public class LocalDbEntityQueryableExpressionVisitorFactory : IEntityQueryableExpressionVisitorFactory { public ExpressionVisitor Create(EntityQueryModelVisitor entityQueryModelVisitor, IQuerySource querySource) => new LocalDbEntityQueryableExpressionVisitor(entityQueryModelVisitor); } public static class LocalServiceCollectionExtension { public static IServiceCollection AddLocalDatabase(this IServiceCollection serviceCollection) { var builder = new EntityFrameworkServicesBuilder(serviceCollection) .TryAdd<IDatabaseProvider, DatabaseProvider<LocalOptionsExtension>>() .TryAdd<IValueGeneratorSelector, LocalValueGeneratorSelector>() .TryAdd<IDatabase>(p => p.GetService<ILocalDbDatabase>()) .TryAdd<IDbContextTransactionManager, LocaDbTransactionManager>() .TryAdd<IDatabaseCreator, LocalDbDatabaseCreator>() .TryAdd<IQueryContextFactory, LocalDbQueryContextFactory>() .TryAdd<IEntityQueryModelVisitorFactory, LocalDbEntityQueryModelVisitorFactory>() .TryAdd<IEntityQueryableExpressionVisitorFactory, LocalDbEntityQueryableExpressionVisitorFactory>() .TryAdd<IEvaluatableExpressionFilter, EvaluatableExpressionFilter>() //.TryAdd<ISingletonOptions, IInMemorySingletonOptions>(p => p.GetService<IInMemorySingletonOptions>()) .TryAddProviderSpecificServices( b => b //.TryAddSingleton<IInMemorySingletonOptions, InMemorySingletonOptions>() //.TryAddSingleton<IInMemoryStoreCache, InMemoryStoreCache>() //.TryAddSingleton<IInMemoryTableFactory, InMemoryTableFactory>() .TryAddScoped<ILocalDbDatabase, LocalDbDatabase>() .TryAddScoped<IMaterializerFactory, MaterializerFactory>()); builder.TryAddCoreServices(); return serviceCollection; } } public static class LocalDbContextOptionsExtensions { public static DbContextOptionsBuilder UseLocalDatabase( this DbContextOptionsBuilder optionsBuilder, string rootFolder) { var extension = optionsBuilder.Options.FindExtension<LocalOptionsExtension>() ?? new LocalOptionsExtension(); if (rootFolder != null) { extension.RootFolder = rootFolder; } //ConfigureWarnings(optionsBuilder); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); //inMemoryOptionsAction?.Invoke(new InMemoryDbContextOptionsBuilder(optionsBuilder)); return optionsBuilder; } }
// // 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.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.SiteRecovery; using Microsoft.WindowsAzure.Management.SiteRecovery.Models; namespace Microsoft.WindowsAzure.Management.SiteRecovery { /// <summary> /// Definition of storage mapping operations for the Site Recovery /// extension. /// </summary> internal partial class StorageMappingOperations : IServiceOperations<SiteRecoveryManagementClient>, IStorageMappingOperations { /// <summary> /// Initializes a new instance of the StorageMappingOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal StorageMappingOperations(SiteRecoveryManagementClient client) { this._client = client; } private SiteRecoveryManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.SiteRecoveryManagementClient. /// </summary> public SiteRecoveryManagementClient Client { get { return this._client; } } /// <summary> /// Create storage mapping. /// </summary> /// <param name='parameters'> /// Required. Storage mapping input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public async Task<JobResponse> CreateAsync(StorageMappingInput parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.PrimaryServerId == null) { throw new ArgumentNullException("parameters.PrimaryServerId"); } if (parameters.PrimaryStorageId == null) { throw new ArgumentNullException("parameters.PrimaryStorageId"); } if (parameters.RecoveryServerId == null) { throw new ArgumentNullException("parameters.RecoveryServerId"); } if (parameters.RecoveryStorageId == null) { throw new ArgumentNullException("parameters.RecoveryStorageId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = ""; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + "WAHyperVRecoveryManager"; url = url + "/~/"; url = url + "HyperVRecoveryManagerVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/StorageMappings"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-04-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Agent-Authentication", customRequestHeaders.AgentAuthenticationHeader); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement storageMappingInputElement = new XElement(XName.Get("StorageMappingInput", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(storageMappingInputElement); XElement primaryServerIdElement = new XElement(XName.Get("PrimaryServerId", "http://schemas.microsoft.com/windowsazure")); primaryServerIdElement.Value = parameters.PrimaryServerId; storageMappingInputElement.Add(primaryServerIdElement); XElement primaryStorageIdElement = new XElement(XName.Get("PrimaryStorageId", "http://schemas.microsoft.com/windowsazure")); primaryStorageIdElement.Value = parameters.PrimaryStorageId; storageMappingInputElement.Add(primaryStorageIdElement); XElement recoveryServerIdElement = new XElement(XName.Get("RecoveryServerId", "http://schemas.microsoft.com/windowsazure")); recoveryServerIdElement.Value = parameters.RecoveryServerId; storageMappingInputElement.Add(recoveryServerIdElement); XElement recoveryStorageIdElement = new XElement(XName.Get("RecoveryStorageId", "http://schemas.microsoft.com/windowsazure")); recoveryStorageIdElement.Value = parameters.RecoveryStorageId; storageMappingInputElement.Add(recoveryStorageIdElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement jobElement = responseDoc.Element(XName.Get("Job", "http://schemas.microsoft.com/windowsazure")); if (jobElement != null) { Job jobInstance = new Job(); result.Job = jobInstance; XElement activityIdElement = jobElement.Element(XName.Get("ActivityId", "http://schemas.microsoft.com/windowsazure")); if (activityIdElement != null) { string activityIdInstance = activityIdElement.Value; jobInstance.ActivityId = activityIdInstance; } XElement startTimeElement = jobElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure")); if (startTimeElement != null && !string.IsNullOrEmpty(startTimeElement.Value)) { DateTime startTimeInstance = DateTime.Parse(startTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); jobInstance.StartTime = startTimeInstance; } XElement endTimeElement = jobElement.Element(XName.Get("EndTime", "http://schemas.microsoft.com/windowsazure")); if (endTimeElement != null && !string.IsNullOrEmpty(endTimeElement.Value)) { DateTime endTimeInstance = DateTime.Parse(endTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); jobInstance.EndTime = endTimeInstance; } XElement displayNameElement = jobElement.Element(XName.Get("DisplayName", "http://schemas.microsoft.com/windowsazure")); if (displayNameElement != null) { string displayNameInstance = displayNameElement.Value; jobInstance.DisplayName = displayNameInstance; } XElement targetObjectIdElement = jobElement.Element(XName.Get("TargetObjectId", "http://schemas.microsoft.com/windowsazure")); if (targetObjectIdElement != null) { string targetObjectIdInstance = targetObjectIdElement.Value; jobInstance.TargetObjectId = targetObjectIdInstance; } XElement targetObjectTypeElement = jobElement.Element(XName.Get("TargetObjectType", "http://schemas.microsoft.com/windowsazure")); if (targetObjectTypeElement != null) { string targetObjectTypeInstance = targetObjectTypeElement.Value; jobInstance.TargetObjectType = targetObjectTypeInstance; } XElement targetObjectNameElement = jobElement.Element(XName.Get("TargetObjectName", "http://schemas.microsoft.com/windowsazure")); if (targetObjectNameElement != null) { string targetObjectNameInstance = targetObjectNameElement.Value; jobInstance.TargetObjectName = targetObjectNameInstance; } XElement allowedActionsSequenceElement = jobElement.Element(XName.Get("AllowedActions", "http://schemas.microsoft.com/windowsazure")); if (allowedActionsSequenceElement != null) { foreach (XElement allowedActionsElement in allowedActionsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { jobInstance.AllowedActions.Add(allowedActionsElement.Value); } } XElement stateElement = jobElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; jobInstance.State = stateInstance; } XElement stateDescriptionElement = jobElement.Element(XName.Get("StateDescription", "http://schemas.microsoft.com/windowsazure")); if (stateDescriptionElement != null) { string stateDescriptionInstance = stateDescriptionElement.Value; jobInstance.StateDescription = stateDescriptionInstance; } XElement tasksSequenceElement = jobElement.Element(XName.Get("Tasks", "http://schemas.microsoft.com/windowsazure")); if (tasksSequenceElement != null) { foreach (XElement tasksElement in tasksSequenceElement.Elements(XName.Get("Task", "http://schemas.microsoft.com/windowsazure"))) { AsrTask taskInstance = new AsrTask(); jobInstance.Tasks.Add(taskInstance); XElement startTimeElement2 = tasksElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure")); if (startTimeElement2 != null) { DateTime startTimeInstance2 = DateTime.Parse(startTimeElement2.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); taskInstance.StartTime = startTimeInstance2; } XElement endTimeElement2 = tasksElement.Element(XName.Get("EndTime", "http://schemas.microsoft.com/windowsazure")); if (endTimeElement2 != null) { DateTime endTimeInstance2 = DateTime.Parse(endTimeElement2.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); taskInstance.EndTime = endTimeInstance2; } XElement actionsSequenceElement = tasksElement.Element(XName.Get("Actions", "http://schemas.microsoft.com/windowsazure")); if (actionsSequenceElement != null) { foreach (XElement actionsElement in actionsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { taskInstance.Actions.Add(actionsElement.Value); } } XElement taskTypeElement = tasksElement.Element(XName.Get("TaskType", "http://schemas.microsoft.com/windowsazure")); if (taskTypeElement != null) { string taskTypeInstance = taskTypeElement.Value; taskInstance.TaskType = taskTypeInstance; } XElement taskNameElement = tasksElement.Element(XName.Get("TaskName", "http://schemas.microsoft.com/windowsazure")); if (taskNameElement != null) { string taskNameInstance = taskNameElement.Value; taskInstance.TaskName = taskNameInstance; } XElement stateElement2 = tasksElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement2 != null) { string stateInstance2 = stateElement2.Value; taskInstance.State = stateInstance2; } XElement stateDescriptionElement2 = tasksElement.Element(XName.Get("StateDescription", "http://schemas.microsoft.com/windowsazure")); if (stateDescriptionElement2 != null) { string stateDescriptionInstance2 = stateDescriptionElement2.Value; taskInstance.StateDescription = stateDescriptionInstance2; } XElement extendedDetailsElement = tasksElement.Element(XName.Get("ExtendedDetails", "http://schemas.microsoft.com/windowsazure")); if (extendedDetailsElement != null) { string extendedDetailsInstance = extendedDetailsElement.Value; taskInstance.ExtendedDetails = extendedDetailsInstance; } XElement nameElement = tasksElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; taskInstance.Name = nameInstance; } XElement idElement = tasksElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; taskInstance.ID = idInstance; } } } XElement errorsSequenceElement = jobElement.Element(XName.Get("Errors", "http://schemas.microsoft.com/windowsazure")); if (errorsSequenceElement != null) { foreach (XElement errorsElement in errorsSequenceElement.Elements(XName.Get("ErrorDetails", "http://schemas.microsoft.com/windowsazure"))) { ErrorDetails errorDetailsInstance = new ErrorDetails(); jobInstance.Errors.Add(errorDetailsInstance); XElement serviceErrorDetailsElement = errorsElement.Element(XName.Get("ServiceErrorDetails", "http://schemas.microsoft.com/windowsazure")); if (serviceErrorDetailsElement != null) { ServiceError serviceErrorDetailsInstance = new ServiceError(); errorDetailsInstance.ServiceErrorDetails = serviceErrorDetailsInstance; XElement codeElement = serviceErrorDetailsElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; serviceErrorDetailsInstance.Code = codeInstance; } XElement messageElement = serviceErrorDetailsElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; serviceErrorDetailsInstance.Message = messageInstance; } XElement possibleCausesElement = serviceErrorDetailsElement.Element(XName.Get("PossibleCauses", "http://schemas.microsoft.com/windowsazure")); if (possibleCausesElement != null) { string possibleCausesInstance = possibleCausesElement.Value; serviceErrorDetailsInstance.PossibleCauses = possibleCausesInstance; } XElement recommendedActionElement = serviceErrorDetailsElement.Element(XName.Get("RecommendedAction", "http://schemas.microsoft.com/windowsazure")); if (recommendedActionElement != null) { string recommendedActionInstance = recommendedActionElement.Value; serviceErrorDetailsInstance.RecommendedAction = recommendedActionInstance; } XElement activityIdElement2 = serviceErrorDetailsElement.Element(XName.Get("ActivityId", "http://schemas.microsoft.com/windowsazure")); if (activityIdElement2 != null) { string activityIdInstance2 = activityIdElement2.Value; serviceErrorDetailsInstance.ActivityId = activityIdInstance2; } } XElement providerErrorDetailsElement = errorsElement.Element(XName.Get("ProviderErrorDetails", "http://schemas.microsoft.com/windowsazure")); if (providerErrorDetailsElement != null) { ProviderError providerErrorDetailsInstance = new ProviderError(); errorDetailsInstance.ProviderErrorDetails = providerErrorDetailsInstance; XElement errorCodeElement = providerErrorDetailsElement.Element(XName.Get("ErrorCode", "http://schemas.microsoft.com/windowsazure")); if (errorCodeElement != null) { int errorCodeInstance = int.Parse(errorCodeElement.Value, CultureInfo.InvariantCulture); providerErrorDetailsInstance.ErrorCode = errorCodeInstance; } XElement errorMessageElement = providerErrorDetailsElement.Element(XName.Get("ErrorMessage", "http://schemas.microsoft.com/windowsazure")); if (errorMessageElement != null) { string errorMessageInstance = errorMessageElement.Value; providerErrorDetailsInstance.ErrorMessage = errorMessageInstance; } XElement errorIdElement = providerErrorDetailsElement.Element(XName.Get("ErrorId", "http://schemas.microsoft.com/windowsazure")); if (errorIdElement != null) { string errorIdInstance = errorIdElement.Value; providerErrorDetailsInstance.ErrorId = errorIdInstance; } XElement workflowIdElement = providerErrorDetailsElement.Element(XName.Get("WorkflowId", "http://schemas.microsoft.com/windowsazure")); if (workflowIdElement != null) { string workflowIdInstance = workflowIdElement.Value; providerErrorDetailsInstance.WorkflowId = workflowIdInstance; } XElement creationTimeUtcElement = providerErrorDetailsElement.Element(XName.Get("CreationTimeUtc", "http://schemas.microsoft.com/windowsazure")); if (creationTimeUtcElement != null) { DateTime creationTimeUtcInstance = DateTime.Parse(creationTimeUtcElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); providerErrorDetailsInstance.CreationTimeUtc = creationTimeUtcInstance; } XElement errorLevelElement = providerErrorDetailsElement.Element(XName.Get("ErrorLevel", "http://schemas.microsoft.com/windowsazure")); if (errorLevelElement != null) { string errorLevelInstance = errorLevelElement.Value; providerErrorDetailsInstance.ErrorLevel = errorLevelInstance; } XElement affectedObjectsSequenceElement = providerErrorDetailsElement.Element(XName.Get("AffectedObjects", "http://schemas.microsoft.com/windowsazure")); if (affectedObjectsSequenceElement != null) { foreach (XElement affectedObjectsElement in affectedObjectsSequenceElement.Elements(XName.Get("KeyValueOfstringstring", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { string affectedObjectsKey = affectedObjectsElement.Element(XName.Get("Key", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value; string affectedObjectsValue = affectedObjectsElement.Element(XName.Get("Value", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value; providerErrorDetailsInstance.AffectedObjects.Add(affectedObjectsKey, affectedObjectsValue); } } } XElement taskIdElement = errorsElement.Element(XName.Get("TaskId", "http://schemas.microsoft.com/windowsazure")); if (taskIdElement != null) { string taskIdInstance = taskIdElement.Value; errorDetailsInstance.TaskId = taskIdInstance; } } } XElement nameElement2 = jobElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement2 != null) { string nameInstance2 = nameElement2.Value; jobInstance.Name = nameInstance2; } XElement idElement2 = jobElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement2 != null) { string idInstance2 = idElement2.Value; jobInstance.ID = idInstance2; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Delete storage mapping. /// </summary> /// <param name='parameters'> /// Required. Storage mapping input /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public async Task<JobResponse> DeleteAsync(StorageMappingInput parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.PrimaryServerId == null) { throw new ArgumentNullException("parameters.PrimaryServerId"); } if (parameters.PrimaryStorageId == null) { throw new ArgumentNullException("parameters.PrimaryStorageId"); } if (parameters.RecoveryServerId == null) { throw new ArgumentNullException("parameters.RecoveryServerId"); } if (parameters.RecoveryStorageId == null) { throw new ArgumentNullException("parameters.RecoveryStorageId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + "WAHyperVRecoveryManager"; url = url + "/~/"; url = url + "HyperVRecoveryManagerVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/StorageMappings"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-04-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Agent-Authentication", customRequestHeaders.AgentAuthenticationHeader); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement storageMappingInputElement = new XElement(XName.Get("StorageMappingInput", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(storageMappingInputElement); XElement primaryServerIdElement = new XElement(XName.Get("PrimaryServerId", "http://schemas.microsoft.com/windowsazure")); primaryServerIdElement.Value = parameters.PrimaryServerId; storageMappingInputElement.Add(primaryServerIdElement); XElement primaryStorageIdElement = new XElement(XName.Get("PrimaryStorageId", "http://schemas.microsoft.com/windowsazure")); primaryStorageIdElement.Value = parameters.PrimaryStorageId; storageMappingInputElement.Add(primaryStorageIdElement); XElement recoveryServerIdElement = new XElement(XName.Get("RecoveryServerId", "http://schemas.microsoft.com/windowsazure")); recoveryServerIdElement.Value = parameters.RecoveryServerId; storageMappingInputElement.Add(recoveryServerIdElement); XElement recoveryStorageIdElement = new XElement(XName.Get("RecoveryStorageId", "http://schemas.microsoft.com/windowsazure")); recoveryStorageIdElement.Value = parameters.RecoveryStorageId; storageMappingInputElement.Add(recoveryStorageIdElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement jobElement = responseDoc.Element(XName.Get("Job", "http://schemas.microsoft.com/windowsazure")); if (jobElement != null) { Job jobInstance = new Job(); result.Job = jobInstance; XElement activityIdElement = jobElement.Element(XName.Get("ActivityId", "http://schemas.microsoft.com/windowsazure")); if (activityIdElement != null) { string activityIdInstance = activityIdElement.Value; jobInstance.ActivityId = activityIdInstance; } XElement startTimeElement = jobElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure")); if (startTimeElement != null && !string.IsNullOrEmpty(startTimeElement.Value)) { DateTime startTimeInstance = DateTime.Parse(startTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); jobInstance.StartTime = startTimeInstance; } XElement endTimeElement = jobElement.Element(XName.Get("EndTime", "http://schemas.microsoft.com/windowsazure")); if (endTimeElement != null && !string.IsNullOrEmpty(endTimeElement.Value)) { DateTime endTimeInstance = DateTime.Parse(endTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); jobInstance.EndTime = endTimeInstance; } XElement displayNameElement = jobElement.Element(XName.Get("DisplayName", "http://schemas.microsoft.com/windowsazure")); if (displayNameElement != null) { string displayNameInstance = displayNameElement.Value; jobInstance.DisplayName = displayNameInstance; } XElement targetObjectIdElement = jobElement.Element(XName.Get("TargetObjectId", "http://schemas.microsoft.com/windowsazure")); if (targetObjectIdElement != null) { string targetObjectIdInstance = targetObjectIdElement.Value; jobInstance.TargetObjectId = targetObjectIdInstance; } XElement targetObjectTypeElement = jobElement.Element(XName.Get("TargetObjectType", "http://schemas.microsoft.com/windowsazure")); if (targetObjectTypeElement != null) { string targetObjectTypeInstance = targetObjectTypeElement.Value; jobInstance.TargetObjectType = targetObjectTypeInstance; } XElement targetObjectNameElement = jobElement.Element(XName.Get("TargetObjectName", "http://schemas.microsoft.com/windowsazure")); if (targetObjectNameElement != null) { string targetObjectNameInstance = targetObjectNameElement.Value; jobInstance.TargetObjectName = targetObjectNameInstance; } XElement allowedActionsSequenceElement = jobElement.Element(XName.Get("AllowedActions", "http://schemas.microsoft.com/windowsazure")); if (allowedActionsSequenceElement != null) { foreach (XElement allowedActionsElement in allowedActionsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { jobInstance.AllowedActions.Add(allowedActionsElement.Value); } } XElement stateElement = jobElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; jobInstance.State = stateInstance; } XElement stateDescriptionElement = jobElement.Element(XName.Get("StateDescription", "http://schemas.microsoft.com/windowsazure")); if (stateDescriptionElement != null) { string stateDescriptionInstance = stateDescriptionElement.Value; jobInstance.StateDescription = stateDescriptionInstance; } XElement tasksSequenceElement = jobElement.Element(XName.Get("Tasks", "http://schemas.microsoft.com/windowsazure")); if (tasksSequenceElement != null) { foreach (XElement tasksElement in tasksSequenceElement.Elements(XName.Get("Task", "http://schemas.microsoft.com/windowsazure"))) { AsrTask taskInstance = new AsrTask(); jobInstance.Tasks.Add(taskInstance); XElement startTimeElement2 = tasksElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure")); if (startTimeElement2 != null) { DateTime startTimeInstance2 = DateTime.Parse(startTimeElement2.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); taskInstance.StartTime = startTimeInstance2; } XElement endTimeElement2 = tasksElement.Element(XName.Get("EndTime", "http://schemas.microsoft.com/windowsazure")); if (endTimeElement2 != null) { DateTime endTimeInstance2 = DateTime.Parse(endTimeElement2.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); taskInstance.EndTime = endTimeInstance2; } XElement actionsSequenceElement = tasksElement.Element(XName.Get("Actions", "http://schemas.microsoft.com/windowsazure")); if (actionsSequenceElement != null) { foreach (XElement actionsElement in actionsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { taskInstance.Actions.Add(actionsElement.Value); } } XElement taskTypeElement = tasksElement.Element(XName.Get("TaskType", "http://schemas.microsoft.com/windowsazure")); if (taskTypeElement != null) { string taskTypeInstance = taskTypeElement.Value; taskInstance.TaskType = taskTypeInstance; } XElement taskNameElement = tasksElement.Element(XName.Get("TaskName", "http://schemas.microsoft.com/windowsazure")); if (taskNameElement != null) { string taskNameInstance = taskNameElement.Value; taskInstance.TaskName = taskNameInstance; } XElement stateElement2 = tasksElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement2 != null) { string stateInstance2 = stateElement2.Value; taskInstance.State = stateInstance2; } XElement stateDescriptionElement2 = tasksElement.Element(XName.Get("StateDescription", "http://schemas.microsoft.com/windowsazure")); if (stateDescriptionElement2 != null) { string stateDescriptionInstance2 = stateDescriptionElement2.Value; taskInstance.StateDescription = stateDescriptionInstance2; } XElement extendedDetailsElement = tasksElement.Element(XName.Get("ExtendedDetails", "http://schemas.microsoft.com/windowsazure")); if (extendedDetailsElement != null) { string extendedDetailsInstance = extendedDetailsElement.Value; taskInstance.ExtendedDetails = extendedDetailsInstance; } XElement nameElement = tasksElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; taskInstance.Name = nameInstance; } XElement idElement = tasksElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; taskInstance.ID = idInstance; } } } XElement errorsSequenceElement = jobElement.Element(XName.Get("Errors", "http://schemas.microsoft.com/windowsazure")); if (errorsSequenceElement != null) { foreach (XElement errorsElement in errorsSequenceElement.Elements(XName.Get("ErrorDetails", "http://schemas.microsoft.com/windowsazure"))) { ErrorDetails errorDetailsInstance = new ErrorDetails(); jobInstance.Errors.Add(errorDetailsInstance); XElement serviceErrorDetailsElement = errorsElement.Element(XName.Get("ServiceErrorDetails", "http://schemas.microsoft.com/windowsazure")); if (serviceErrorDetailsElement != null) { ServiceError serviceErrorDetailsInstance = new ServiceError(); errorDetailsInstance.ServiceErrorDetails = serviceErrorDetailsInstance; XElement codeElement = serviceErrorDetailsElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; serviceErrorDetailsInstance.Code = codeInstance; } XElement messageElement = serviceErrorDetailsElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; serviceErrorDetailsInstance.Message = messageInstance; } XElement possibleCausesElement = serviceErrorDetailsElement.Element(XName.Get("PossibleCauses", "http://schemas.microsoft.com/windowsazure")); if (possibleCausesElement != null) { string possibleCausesInstance = possibleCausesElement.Value; serviceErrorDetailsInstance.PossibleCauses = possibleCausesInstance; } XElement recommendedActionElement = serviceErrorDetailsElement.Element(XName.Get("RecommendedAction", "http://schemas.microsoft.com/windowsazure")); if (recommendedActionElement != null) { string recommendedActionInstance = recommendedActionElement.Value; serviceErrorDetailsInstance.RecommendedAction = recommendedActionInstance; } XElement activityIdElement2 = serviceErrorDetailsElement.Element(XName.Get("ActivityId", "http://schemas.microsoft.com/windowsazure")); if (activityIdElement2 != null) { string activityIdInstance2 = activityIdElement2.Value; serviceErrorDetailsInstance.ActivityId = activityIdInstance2; } } XElement providerErrorDetailsElement = errorsElement.Element(XName.Get("ProviderErrorDetails", "http://schemas.microsoft.com/windowsazure")); if (providerErrorDetailsElement != null) { ProviderError providerErrorDetailsInstance = new ProviderError(); errorDetailsInstance.ProviderErrorDetails = providerErrorDetailsInstance; XElement errorCodeElement = providerErrorDetailsElement.Element(XName.Get("ErrorCode", "http://schemas.microsoft.com/windowsazure")); if (errorCodeElement != null) { int errorCodeInstance = int.Parse(errorCodeElement.Value, CultureInfo.InvariantCulture); providerErrorDetailsInstance.ErrorCode = errorCodeInstance; } XElement errorMessageElement = providerErrorDetailsElement.Element(XName.Get("ErrorMessage", "http://schemas.microsoft.com/windowsazure")); if (errorMessageElement != null) { string errorMessageInstance = errorMessageElement.Value; providerErrorDetailsInstance.ErrorMessage = errorMessageInstance; } XElement errorIdElement = providerErrorDetailsElement.Element(XName.Get("ErrorId", "http://schemas.microsoft.com/windowsazure")); if (errorIdElement != null) { string errorIdInstance = errorIdElement.Value; providerErrorDetailsInstance.ErrorId = errorIdInstance; } XElement workflowIdElement = providerErrorDetailsElement.Element(XName.Get("WorkflowId", "http://schemas.microsoft.com/windowsazure")); if (workflowIdElement != null) { string workflowIdInstance = workflowIdElement.Value; providerErrorDetailsInstance.WorkflowId = workflowIdInstance; } XElement creationTimeUtcElement = providerErrorDetailsElement.Element(XName.Get("CreationTimeUtc", "http://schemas.microsoft.com/windowsazure")); if (creationTimeUtcElement != null) { DateTime creationTimeUtcInstance = DateTime.Parse(creationTimeUtcElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); providerErrorDetailsInstance.CreationTimeUtc = creationTimeUtcInstance; } XElement errorLevelElement = providerErrorDetailsElement.Element(XName.Get("ErrorLevel", "http://schemas.microsoft.com/windowsazure")); if (errorLevelElement != null) { string errorLevelInstance = errorLevelElement.Value; providerErrorDetailsInstance.ErrorLevel = errorLevelInstance; } XElement affectedObjectsSequenceElement = providerErrorDetailsElement.Element(XName.Get("AffectedObjects", "http://schemas.microsoft.com/windowsazure")); if (affectedObjectsSequenceElement != null) { foreach (XElement affectedObjectsElement in affectedObjectsSequenceElement.Elements(XName.Get("KeyValueOfstringstring", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { string affectedObjectsKey = affectedObjectsElement.Element(XName.Get("Key", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value; string affectedObjectsValue = affectedObjectsElement.Element(XName.Get("Value", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value; providerErrorDetailsInstance.AffectedObjects.Add(affectedObjectsKey, affectedObjectsValue); } } } XElement taskIdElement = errorsElement.Element(XName.Get("TaskId", "http://schemas.microsoft.com/windowsazure")); if (taskIdElement != null) { string taskIdInstance = taskIdElement.Value; errorDetailsInstance.TaskId = taskIdInstance; } } } XElement nameElement2 = jobElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement2 != null) { string nameInstance2 = nameElement2.Value; jobInstance.Name = nameInstance2; } XElement idElement2 = jobElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement2 != null) { string idInstance2 = idElement2.Value; jobInstance.ID = idInstance2; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get the list of all storage mappings under the vault. /// </summary> /// <param name='primaryServerId'> /// Required. Primary server Id. /// </param> /// <param name='recoveryServerId'> /// Required. Recovery server Id. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list of storage mappings operation. /// </returns> public async Task<StorageMappingListResponse> ListAsync(string primaryServerId, string recoveryServerId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (primaryServerId == null) { throw new ArgumentNullException("primaryServerId"); } if (recoveryServerId == null) { throw new ArgumentNullException("recoveryServerId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("primaryServerId", primaryServerId); tracingParameters.Add("recoveryServerId", recoveryServerId); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + "WAHyperVRecoveryManager"; url = url + "/~/"; url = url + "HyperVRecoveryManagerVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/StorageMappings"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-04-10"); queryParameters.Add("PrimaryServerId=" + Uri.EscapeDataString(primaryServerId)); queryParameters.Add("RecoveryServerId=" + Uri.EscapeDataString(recoveryServerId)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result StorageMappingListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new StorageMappingListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement arrayOfStorageMappingSequenceElement = responseDoc.Element(XName.Get("ArrayOfStorageMapping", "http://schemas.microsoft.com/windowsazure")); if (arrayOfStorageMappingSequenceElement != null) { foreach (XElement arrayOfStorageMappingElement in arrayOfStorageMappingSequenceElement.Elements(XName.Get("StorageMapping", "http://schemas.microsoft.com/windowsazure"))) { StorageMapping storageMappingInstance = new StorageMapping(); result.StorageMappings.Add(storageMappingInstance); XElement primaryServerIdElement = arrayOfStorageMappingElement.Element(XName.Get("PrimaryServerId", "http://schemas.microsoft.com/windowsazure")); if (primaryServerIdElement != null) { string primaryServerIdInstance = primaryServerIdElement.Value; storageMappingInstance.PrimaryServerId = primaryServerIdInstance; } XElement primaryStorageIdElement = arrayOfStorageMappingElement.Element(XName.Get("PrimaryStorageId", "http://schemas.microsoft.com/windowsazure")); if (primaryStorageIdElement != null) { string primaryStorageIdInstance = primaryStorageIdElement.Value; storageMappingInstance.PrimaryStorageId = primaryStorageIdInstance; } XElement primaryStorageNameElement = arrayOfStorageMappingElement.Element(XName.Get("PrimaryStorageName", "http://schemas.microsoft.com/windowsazure")); if (primaryStorageNameElement != null) { string primaryStorageNameInstance = primaryStorageNameElement.Value; storageMappingInstance.PrimaryStorageName = primaryStorageNameInstance; } XElement recoveryServerIdElement = arrayOfStorageMappingElement.Element(XName.Get("RecoveryServerId", "http://schemas.microsoft.com/windowsazure")); if (recoveryServerIdElement != null) { string recoveryServerIdInstance = recoveryServerIdElement.Value; storageMappingInstance.RecoveryServerId = recoveryServerIdInstance; } XElement recoveryStorageIdElement = arrayOfStorageMappingElement.Element(XName.Get("RecoveryStorageId", "http://schemas.microsoft.com/windowsazure")); if (recoveryStorageIdElement != null) { string recoveryStorageIdInstance = recoveryStorageIdElement.Value; storageMappingInstance.RecoveryStorageId = recoveryStorageIdInstance; } XElement recoveryStorageNameElement = arrayOfStorageMappingElement.Element(XName.Get("RecoveryStorageName", "http://schemas.microsoft.com/windowsazure")); if (recoveryStorageNameElement != null) { string recoveryStorageNameInstance = recoveryStorageNameElement.Value; storageMappingInstance.RecoveryStorageName = recoveryStorageNameInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Region.CoreModules.Framework.InterfaceCommander; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; namespace OpenSim.Region.CoreModules.World.Serialiser { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SerialiserModule")] public class SerialiserModule : ISharedRegionModule, IRegionSerialiserModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private Commander m_commander = new Commander("export"); private List<Scene> m_regions = new List<Scene>(); private string m_savedir = "exports"; private List<IFileSerialiser> m_serialisers = new List<IFileSerialiser>(); #region ISharedRegionModule Members public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { IConfig config = source.Configs["Serialiser"]; if (config != null) { m_savedir = config.GetString("save_dir", m_savedir); } m_log.InfoFormat("[Serialiser] Enabled, using save dir \"{0}\"", m_savedir); } public void PostInitialise() { lock (m_serialisers) { m_serialisers.Add(new SerialiseTerrain()); m_serialisers.Add(new SerialiseObjects()); } // LoadCommanderCommands(); } public void AddRegion(Scene scene) { // scene.RegisterModuleCommander(m_commander); // scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole; scene.RegisterModuleInterface<IRegionSerialiserModule>(this); lock (m_regions) { m_regions.Add(scene); } } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { lock (m_regions) { m_regions.Remove(scene); } } public void Close() { m_regions.Clear(); } public string Name { get { return "ExportSerialisationModule"; } } #endregion #region IRegionSerialiser Members public void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset) { SceneXmlLoader.LoadPrimsFromXml(scene, fileName, newIDS, loadOffset); } public void SavePrimsToXml(Scene scene, string fileName) { SceneXmlLoader.SavePrimsToXml(scene, fileName); } public void LoadPrimsFromXml2(Scene scene, string fileName) { SceneXmlLoader.LoadPrimsFromXml2(scene, fileName); } public void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts) { SceneXmlLoader.LoadPrimsFromXml2(scene, reader, startScripts); } public void SavePrimsToXml2(Scene scene, string fileName) { SceneXmlLoader.SavePrimsToXml2(scene, fileName); } public void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max) { SceneXmlLoader.SavePrimsToXml2(scene, stream, min, max); } public void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName) { SceneXmlLoader.SaveNamedPrimsToXml2(scene, primName, fileName); } public SceneObjectGroup DeserializeGroupFromXml2(string xmlString) { return SceneXmlLoader.DeserializeGroupFromXml2(xmlString); } public string SerializeGroupToXml2(SceneObjectGroup grp, Dictionary<string, object> options) { return SceneXmlLoader.SaveGroupToXml2(grp, options); } public void SavePrimListToXml2(EntityBase[] entityList, string fileName) { SceneXmlLoader.SavePrimListToXml2(entityList, fileName); } public void SavePrimListToXml2(EntityBase[] entityList, TextWriter stream, Vector3 min, Vector3 max) { SceneXmlLoader.SavePrimListToXml2(entityList, stream, min, max); } public List<string> SerialiseRegion(Scene scene, string saveDir) { List<string> results = new List<string>(); if (!Directory.Exists(saveDir)) { Directory.CreateDirectory(saveDir); } lock (m_serialisers) { foreach (IFileSerialiser serialiser in m_serialisers) { results.Add(serialiser.WriteToFile(scene, saveDir)); } } TextWriter regionInfoWriter = new StreamWriter(Path.Combine(saveDir, "README.TXT")); regionInfoWriter.WriteLine("Region Name: " + scene.RegionInfo.RegionName); regionInfoWriter.WriteLine("Region ID: " + scene.RegionInfo.RegionID.ToString()); regionInfoWriter.WriteLine("Backup Time: UTC " + DateTime.UtcNow.ToString()); regionInfoWriter.WriteLine("Serialise Version: 0.1"); regionInfoWriter.Close(); TextWriter manifestWriter = new StreamWriter(Path.Combine(saveDir, "region.manifest")); foreach (string line in results) { manifestWriter.WriteLine(line); } manifestWriter.Close(); return results; } #endregion // private void EventManager_OnPluginConsole(string[] args) // { // if (args[0] == "export") // { // string[] tmpArgs = new string[args.Length - 2]; // int i = 0; // for (i = 2; i < args.Length; i++) // tmpArgs[i - 2] = args[i]; // // m_commander.ProcessConsoleCommand(args[1], tmpArgs); // } // } private void InterfaceSaveRegion(Object[] args) { foreach (Scene region in m_regions) { if (region.RegionInfo.RegionName == (string) args[0]) { // List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/"); SerialiseRegion(region, Path.Combine(m_savedir, region.RegionInfo.RegionID.ToString())); } } } private void InterfaceSaveAllRegions(Object[] args) { foreach (Scene region in m_regions) { // List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/"); SerialiseRegion(region, Path.Combine(m_savedir, region.RegionInfo.RegionID.ToString())); } } // private void LoadCommanderCommands() // { // Command serialiseSceneCommand = new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveRegion, "Saves the named region into the exports directory."); // serialiseSceneCommand.AddArgument("region-name", "The name of the region you wish to export", "String"); // // Command serialiseAllScenesCommand = new Command("save-all",CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveAllRegions, "Saves all regions into the exports directory."); // // m_commander.RegisterCommand("save", serialiseSceneCommand); // m_commander.RegisterCommand("save-all", serialiseAllScenesCommand); // } } }
// <copyright file="IEnumerableExtensions.SequenceCompare.StandardTypes.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace IX.StandardExtensions.Extensions; /// <summary> /// Extensions for IEnumerable. /// </summary> [SuppressMessage( "ReSharper", "InconsistentNaming", Justification = "These are extensions for IEnumerable, so we must allow this.")] public static partial class IEnumerableExtensions { /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<byte>? left, IEnumerable<byte>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<byte> e1 = left.GetEnumerator(); using IEnumerator<byte> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<sbyte>? left, IEnumerable<sbyte>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<sbyte> e1 = left.GetEnumerator(); using IEnumerator<sbyte> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<short>? left, IEnumerable<short>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<short> e1 = left.GetEnumerator(); using IEnumerator<short> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<ushort>? left, IEnumerable<ushort>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<ushort> e1 = left.GetEnumerator(); using IEnumerator<ushort> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<char>? left, IEnumerable<char>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<char> e1 = left.GetEnumerator(); using IEnumerator<char> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<int>? left, IEnumerable<int>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<int> e1 = left.GetEnumerator(); using IEnumerator<int> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<uint>? left, IEnumerable<uint>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<uint> e1 = left.GetEnumerator(); using IEnumerator<uint> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<long>? left, IEnumerable<long>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<long> e1 = left.GetEnumerator(); using IEnumerator<long> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<ulong>? left, IEnumerable<ulong>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<ulong> e1 = left.GetEnumerator(); using IEnumerator<ulong> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<float>? left, IEnumerable<float>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<float> e1 = left.GetEnumerator(); using IEnumerator<float> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<double>? left, IEnumerable<double>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<double> e1 = left.GetEnumerator(); using IEnumerator<double> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<decimal>? left, IEnumerable<decimal>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<decimal> e1 = left.GetEnumerator(); using IEnumerator<decimal> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<DateTime>? left, IEnumerable<DateTime>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<DateTime> e1 = left.GetEnumerator(); using IEnumerator<DateTime> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<bool>? left, IEnumerable<bool>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<bool> e1 = left.GetEnumerator(); using IEnumerator<bool> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<TimeSpan>? left, IEnumerable<TimeSpan>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<TimeSpan> e1 = left.GetEnumerator(); using IEnumerator<TimeSpan> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = c1.CompareTo(c2); if (cr != 0) { return cr; } } } /// <summary> /// Compares two enumerable sequences to one another. /// </summary> /// <param name="left">The left operand enumerable.</param> /// <param name="right">The right operand enumerable.</param> /// <returns>The result of the comparison.</returns> public static int SequenceCompare(this IEnumerable<string>? left, IEnumerable<string>? right) { if (left == null) { if (right == null) { return 0; } else { return -1; } } if (right == null) { return 1; } using IEnumerator<string> e1 = left.GetEnumerator(); using IEnumerator<string> e2 = right.GetEnumerator(); while (true) { var b1 = e1.MoveNext(); var b2 = e2.MoveNext(); if (!b1 && !b2) { return 0; } var c1 = b1 ? e1.Current : default; var c2 = b2 ? e2.Current : default; var cr = string.Compare(c1, c2, CultureInfo.CurrentCulture, CompareOptions.None); if (cr != 0) { return cr; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; using System.Runtime.Versioning; using System.Threading; namespace System.Xml { // Specifies formatting options for XmlTextWriter. public enum Formatting { // No special formatting is done (this is the default). None, //This option causes child elements to be indented using the Indentation and IndentChar properties. // It only indents Element Content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-element-content) // and not Mixed Content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-mixed-content) // according to the XML 1.0 definitions of these terms. Indented, }; // Represents a writer that provides fast non-cached forward-only way of generating XML streams // containing XML documents that conform to the W3CExtensible Markup Language (XML) 1.0 specification // and the Namespaces in XML specification. [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class XmlTextWriter : XmlWriter { // // Private types // private enum NamespaceState { Uninitialized, NotDeclaredButInScope, DeclaredButNotWrittenOut, DeclaredAndWrittenOut } private struct TagInfo { internal string name; internal string prefix; internal string defaultNs; internal NamespaceState defaultNsState; internal XmlSpace xmlSpace; internal string xmlLang; internal int prevNsTop; internal int prefixCount; internal bool mixed; // whether to pretty print the contents of this element. internal void Init(int nsTop) { name = null; defaultNs = string.Empty; defaultNsState = NamespaceState.Uninitialized; xmlSpace = XmlSpace.None; xmlLang = null; prevNsTop = nsTop; prefixCount = 0; mixed = false; } } private struct Namespace { internal string prefix; internal string ns; internal bool declared; internal int prevNsIndex; internal void Set(string prefix, string ns, bool declared) { this.prefix = prefix; this.ns = ns; this.declared = declared; this.prevNsIndex = -1; } } private enum SpecialAttr { None, XmlSpace, XmlLang, XmlNs }; // State machine is working through autocomplete private enum State { Start, Prolog, PostDTD, Element, Attribute, Content, AttrOnly, Epilog, Error, Closed, } private enum Token { PI, Doctype, Comment, CData, StartElement, EndElement, LongEndElement, StartAttribute, EndAttribute, Content, Base64, RawData, Whitespace, Empty } // // Fields // // output private TextWriter _textWriter; private XmlTextEncoder _xmlEncoder; private Encoding _encoding; // formatting private Formatting _formatting; private bool _indented; // perf - faster to check a boolean. private int _indentation; private char[] _indentChars; private static char[] s_defaultIndentChars = CreateDefaultIndentChars(); // This method is needed as the native code compiler fails when this initialization is inline private static char[] CreateDefaultIndentChars() { return new string(DefaultIndentChar, IndentArrayLength).ToCharArray(); } // element stack private TagInfo[] _stack; private int _top; // state machine for AutoComplete private State[] _stateTable; private State _currentState; private Token _lastToken; // Base64 content private XmlTextWriterBase64Encoder _base64Encoder; // misc private char _quoteChar; private char _curQuoteChar; private bool _namespaces; private SpecialAttr _specialAttr; private string _prefixForXmlNs; private bool _flush; // namespaces private Namespace[] _nsStack; private int _nsTop; private Dictionary<string, int> _nsHashtable; private bool _useNsHashtable; // char types private XmlCharType _xmlCharType = XmlCharType.Instance; // // Constants and constant tables // private const int IndentArrayLength = 64; private const char DefaultIndentChar = ' '; private const int NamespaceStackInitialSize = 8; #if DEBUG private const int MaxNamespacesWalkCount = 3; #else private const int MaxNamespacesWalkCount = 16; #endif private static string[] s_stateName = { "Start", "Prolog", "PostDTD", "Element", "Attribute", "Content", "AttrOnly", "Epilog", "Error", "Closed", }; private static string[] s_tokenName = { "PI", "Doctype", "Comment", "CData", "StartElement", "EndElement", "LongEndElement", "StartAttribute", "EndAttribute", "Content", "Base64", "RawData", "Whitespace", "Empty" }; private static readonly State[] s_stateTableDefault = { // State.Start State.Prolog State.PostDTD State.Element State.Attribute State.Content State.AttrOnly State.Epilog // /* Token.PI */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog, /* Token.Doctype */ State.PostDTD, State.PostDTD, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, /* Token.Comment */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog, /* Token.CData */ State.Content, State.Content, State.Error, State.Content, State.Content, State.Content, State.Error, State.Epilog, /* Token.StartElement */ State.Element, State.Element, State.Element, State.Element, State.Element, State.Element, State.Error, State.Element, /* Token.EndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error, /* Token.LongEndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error, /* Token.StartAttribute */ State.AttrOnly, State.Error, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error, /* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Error, State.Element, State.Error, State.Epilog, State.Error, /* Token.Content */ State.Content, State.Content, State.Error, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog, /* Token.Base64 */ State.Content, State.Content, State.Error, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog, /* Token.RawData */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog, /* Token.Whitespace */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog, }; private static readonly State[] s_stateTableDocument = { // State.Start State.Prolog State.PostDTD State.Element State.Attribute State.Content State.AttrOnly State.Epilog // /* Token.PI */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog, /* Token.Doctype */ State.Error, State.PostDTD, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, /* Token.Comment */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog, /* Token.CData */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error, /* Token.StartElement */ State.Error, State.Element, State.Element, State.Element, State.Element, State.Element, State.Error, State.Error, /* Token.EndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error, /* Token.LongEndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error, /* Token.StartAttribute */ State.Error, State.Error, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error, /* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Error, State.Element, State.Error, State.Error, State.Error, /* Token.Content */ State.Error, State.Error, State.Error, State.Content, State.Attribute, State.Content, State.Error, State.Error, /* Token.Base64 */ State.Error, State.Error, State.Error, State.Content, State.Attribute, State.Content, State.Error, State.Error, /* Token.RawData */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Error, State.Epilog, /* Token.Whitespace */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Error, State.Epilog, }; // // Constructors // internal XmlTextWriter() { _namespaces = true; _formatting = Formatting.None; _indentation = 2; _indentChars = s_defaultIndentChars; // namespaces _nsStack = new Namespace[NamespaceStackInitialSize]; _nsTop = -1; // element stack _stack = new TagInfo[10]; _top = 0;// 0 is an empty sentanial element _stack[_top].Init(-1); _quoteChar = '"'; _stateTable = s_stateTableDefault; _currentState = State.Start; _lastToken = Token.Empty; } // Creates an instance of the XmlTextWriter class using the specified stream. public XmlTextWriter(Stream w, Encoding encoding) : this() { _encoding = encoding; if (encoding != null) _textWriter = new StreamWriter(w, encoding); else _textWriter = new StreamWriter(w); _xmlEncoder = new XmlTextEncoder(_textWriter); _xmlEncoder.QuoteChar = _quoteChar; } // Creates an instance of the XmlTextWriter class using the specified file. public XmlTextWriter(string filename, Encoding encoding) : this(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read), encoding) { } // Creates an instance of the XmlTextWriter class using the specified TextWriter. public XmlTextWriter(TextWriter w) : this() { _textWriter = w; _encoding = w.Encoding; _xmlEncoder = new XmlTextEncoder(w); _xmlEncoder.QuoteChar = _quoteChar; } // // XmlTextWriter properties // // Gets the XmlTextWriter base stream. public Stream BaseStream { get { StreamWriter streamWriter = _textWriter as StreamWriter; return (streamWriter == null ? null : streamWriter.BaseStream); } } // Gets or sets a value indicating whether to do namespace support. public bool Namespaces { get { return _namespaces; } set { if (_currentState != State.Start) throw new InvalidOperationException(SR.Xml_NotInWriteState); _namespaces = value; } } // Indicates how the output is formatted. public Formatting Formatting { get { return _formatting; } set { _formatting = value; _indented = value == Formatting.Indented; } } // Gets or sets how many IndentChars to write for each level in the hierarchy when Formatting is set to "Indented". public int Indentation { get { return _indentation; } set { if (value < 0) throw new ArgumentException(SR.Xml_InvalidIndentation); _indentation = value; } } // Gets or sets which character to use for indenting when Formatting is set to "Indented". public char IndentChar { get { return _indentChars[0]; } set { if (value == DefaultIndentChar) { _indentChars = s_defaultIndentChars; return; } if (ReferenceEquals(_indentChars, s_defaultIndentChars)) { _indentChars = new char[IndentArrayLength]; } for (int i = 0; i < IndentArrayLength; i++) { _indentChars[i] = value; } } } // Gets or sets which character to use to quote attribute values. public char QuoteChar { get { return _quoteChar; } set { if (value != '"' && value != '\'') { throw new ArgumentException(SR.Xml_InvalidQuote); } _quoteChar = value; _xmlEncoder.QuoteChar = value; } } // // XmlWriter implementation // // Writes out the XML declaration with the version "1.0". public override void WriteStartDocument() { StartDocument(-1); } // Writes out the XML declaration with the version "1.0" and the standalone attribute. public override void WriteStartDocument(bool standalone) { StartDocument(standalone ? 1 : 0); } // Closes any open elements or attributes and puts the writer back in the Start state. public override void WriteEndDocument() { try { AutoCompleteAll(); if (_currentState != State.Epilog) { if (_currentState == State.Closed) { throw new ArgumentException(SR.Xml_ClosedOrError); } else { throw new ArgumentException(SR.Xml_NoRoot); } } _stateTable = s_stateTableDefault; _currentState = State.Start; _lastToken = Token.Empty; } catch { _currentState = State.Error; throw; } } // Writes out the DOCTYPE declaration with the specified name and optional attributes. public override void WriteDocType(string name, string pubid, string sysid, string subset) { try { ValidateName(name, false); AutoComplete(Token.Doctype); _textWriter.Write("<!DOCTYPE "); _textWriter.Write(name); if (pubid != null) { _textWriter.Write(" PUBLIC " + _quoteChar); _textWriter.Write(pubid); _textWriter.Write(_quoteChar + " " + _quoteChar); _textWriter.Write(sysid); _textWriter.Write(_quoteChar); } else if (sysid != null) { _textWriter.Write(" SYSTEM " + _quoteChar); _textWriter.Write(sysid); _textWriter.Write(_quoteChar); } if (subset != null) { _textWriter.Write("["); _textWriter.Write(subset); _textWriter.Write("]"); } _textWriter.Write('>'); } catch { _currentState = State.Error; throw; } } // Writes out the specified start tag and associates it with the given namespace and prefix. public override void WriteStartElement(string prefix, string localName, string ns) { try { AutoComplete(Token.StartElement); PushStack(); _textWriter.Write('<'); if (_namespaces) { // Propagate default namespace and mix model down the stack. _stack[_top].defaultNs = _stack[_top - 1].defaultNs; if (_stack[_top - 1].defaultNsState != NamespaceState.Uninitialized) _stack[_top].defaultNsState = NamespaceState.NotDeclaredButInScope; _stack[_top].mixed = _stack[_top - 1].mixed; if (ns == null) { // use defined prefix if (prefix != null && prefix.Length != 0 && (LookupNamespace(prefix) == -1)) { throw new ArgumentException(SR.Xml_UndefPrefix); } } else { if (prefix == null) { string definedPrefix = FindPrefix(ns); if (definedPrefix != null) { prefix = definedPrefix; } else { PushNamespace(null, ns, false); // new default } } else if (prefix.Length == 0) { PushNamespace(null, ns, false); // new default } else { if (ns.Length == 0) { prefix = null; } VerifyPrefixXml(prefix, ns); PushNamespace(prefix, ns, false); // define } } _stack[_top].prefix = null; if (prefix != null && prefix.Length != 0) { _stack[_top].prefix = prefix; _textWriter.Write(prefix); _textWriter.Write(':'); } } else { if ((ns != null && ns.Length != 0) || (prefix != null && prefix.Length != 0)) { throw new ArgumentException(SR.Xml_NoNamespaces); } } _stack[_top].name = localName; _textWriter.Write(localName); } catch { _currentState = State.Error; throw; } } // Closes one element and pops the corresponding namespace scope. public override void WriteEndElement() { InternalWriteEndElement(false); } // Closes one element and pops the corresponding namespace scope. public override void WriteFullEndElement() { InternalWriteEndElement(true); } // Writes the start of an attribute. public override void WriteStartAttribute(string prefix, string localName, string ns) { try { AutoComplete(Token.StartAttribute); _specialAttr = SpecialAttr.None; if (_namespaces) { if (prefix != null && prefix.Length == 0) { prefix = null; } if (ns == XmlReservedNs.NsXmlNs && prefix == null && localName != "xmlns") { prefix = "xmlns"; } if (prefix == "xml") { if (localName == "lang") { _specialAttr = SpecialAttr.XmlLang; } else if (localName == "space") { _specialAttr = SpecialAttr.XmlSpace; } /* bug54408. to be fwd compatible we need to treat xml prefix as reserved and not really insist on a specific value. Who knows in the future it might be OK to say xml:blabla else { throw new ArgumentException(SR.Xml_InvalidPrefix); }*/ } else if (prefix == "xmlns") { if (XmlReservedNs.NsXmlNs != ns && ns != null) { throw new ArgumentException(SR.Xml_XmlnsBelongsToReservedNs); } if (localName == null || localName.Length == 0) { localName = prefix; prefix = null; _prefixForXmlNs = null; } else { _prefixForXmlNs = localName; } _specialAttr = SpecialAttr.XmlNs; } else if (prefix == null && localName == "xmlns") { if (XmlReservedNs.NsXmlNs != ns && ns != null) { // add the below line back in when DOM is fixed throw new ArgumentException(SR.Xml_XmlnsBelongsToReservedNs); } _specialAttr = SpecialAttr.XmlNs; _prefixForXmlNs = null; } else { if (ns == null) { // use defined prefix if (prefix != null && (LookupNamespace(prefix) == -1)) { throw new ArgumentException(SR.Xml_UndefPrefix); } } else if (ns.Length == 0) { // empty namespace require null prefix prefix = string.Empty; } else { // ns.Length != 0 VerifyPrefixXml(prefix, ns); if (prefix != null && LookupNamespaceInCurrentScope(prefix) != -1) { prefix = null; } // Now verify prefix validity string definedPrefix = FindPrefix(ns); if (definedPrefix != null && (prefix == null || prefix == definedPrefix)) { prefix = definedPrefix; } else { if (prefix == null) { prefix = GeneratePrefix(); // need a prefix if } PushNamespace(prefix, ns, false); } } } if (prefix != null && prefix.Length != 0) { _textWriter.Write(prefix); _textWriter.Write(':'); } } else { if ((ns != null && ns.Length != 0) || (prefix != null && prefix.Length != 0)) { throw new ArgumentException(SR.Xml_NoNamespaces); } if (localName == "xml:lang") { _specialAttr = SpecialAttr.XmlLang; } else if (localName == "xml:space") { _specialAttr = SpecialAttr.XmlSpace; } } _xmlEncoder.StartAttribute(_specialAttr != SpecialAttr.None); _textWriter.Write(localName); _textWriter.Write('='); if (_curQuoteChar != _quoteChar) { _curQuoteChar = _quoteChar; _xmlEncoder.QuoteChar = _quoteChar; } _textWriter.Write(_curQuoteChar); } catch { _currentState = State.Error; throw; } } // Closes the attribute opened by WriteStartAttribute. public override void WriteEndAttribute() { try { AutoComplete(Token.EndAttribute); } catch { _currentState = State.Error; throw; } } // Writes out a &lt;![CDATA[...]]&gt; block containing the specified text. public override void WriteCData(string text) { try { AutoComplete(Token.CData); if (null != text && text.IndexOf("]]>", StringComparison.Ordinal) >= 0) { throw new ArgumentException(SR.Xml_InvalidCDataChars); } _textWriter.Write("<![CDATA["); if (null != text) { _xmlEncoder.WriteRawWithSurrogateChecking(text); } _textWriter.Write("]]>"); } catch { _currentState = State.Error; throw; } } // Writes out a comment <!--...--> containing the specified text. public override void WriteComment(string text) { try { if (null != text && (text.IndexOf("--", StringComparison.Ordinal) >= 0 || (text.Length != 0 && text[text.Length - 1] == '-'))) { throw new ArgumentException(SR.Xml_InvalidCommentChars); } AutoComplete(Token.Comment); _textWriter.Write("<!--"); if (null != text) { _xmlEncoder.WriteRawWithSurrogateChecking(text); } _textWriter.Write("-->"); } catch { _currentState = State.Error; throw; } } // Writes out a processing instruction with a space between the name and text as follows: <?name text?> public override void WriteProcessingInstruction(string name, string text) { try { if (null != text && text.IndexOf("?>", StringComparison.Ordinal) >= 0) { throw new ArgumentException(SR.Xml_InvalidPiChars); } if (0 == string.Compare(name, "xml", StringComparison.OrdinalIgnoreCase) && _stateTable == s_stateTableDocument) { throw new ArgumentException(SR.Xml_DupXmlDecl); } AutoComplete(Token.PI); InternalWriteProcessingInstruction(name, text); } catch { _currentState = State.Error; throw; } } // Writes out an entity reference as follows: "&"+name+";". public override void WriteEntityRef(string name) { try { ValidateName(name, false); AutoComplete(Token.Content); _xmlEncoder.WriteEntityRef(name); } catch { _currentState = State.Error; throw; } } // Forces the generation of a character entity for the specified Unicode character value. public override void WriteCharEntity(char ch) { try { AutoComplete(Token.Content); _xmlEncoder.WriteCharEntity(ch); } catch { _currentState = State.Error; throw; } } // Writes out the given whitespace. public override void WriteWhitespace(string ws) { try { if (null == ws) { ws = string.Empty; } if (!_xmlCharType.IsOnlyWhitespace(ws)) { throw new ArgumentException(SR.Xml_NonWhitespace); } AutoComplete(Token.Whitespace); _xmlEncoder.Write(ws); } catch { _currentState = State.Error; throw; } } // Writes out the specified text content. public override void WriteString(string text) { try { if (null != text && text.Length != 0) { AutoComplete(Token.Content); _xmlEncoder.Write(text); } } catch { _currentState = State.Error; throw; } } // Writes out the specified surrogate pair as a character entity. public override void WriteSurrogateCharEntity(char lowChar, char highChar) { try { AutoComplete(Token.Content); _xmlEncoder.WriteSurrogateCharEntity(lowChar, highChar); } catch { _currentState = State.Error; throw; } } // Writes out the specified text content. public override void WriteChars(char[] buffer, int index, int count) { try { AutoComplete(Token.Content); _xmlEncoder.Write(buffer, index, count); } catch { _currentState = State.Error; throw; } } // Writes raw markup from the specified character buffer. public override void WriteRaw(char[] buffer, int index, int count) { try { AutoComplete(Token.RawData); _xmlEncoder.WriteRaw(buffer, index, count); } catch { _currentState = State.Error; throw; } } // Writes raw markup from the specified character string. public override void WriteRaw(string data) { try { AutoComplete(Token.RawData); _xmlEncoder.WriteRawWithSurrogateChecking(data); } catch { _currentState = State.Error; throw; } } // Encodes the specified binary bytes as base64 and writes out the resulting text. public override void WriteBase64(byte[] buffer, int index, int count) { try { if (!_flush) { AutoComplete(Token.Base64); } _flush = true; // No need for us to explicitly validate the args. The StreamWriter will do // it for us. if (null == _base64Encoder) { _base64Encoder = new XmlTextWriterBase64Encoder(_xmlEncoder); } // Encode will call WriteRaw to write out the encoded characters _base64Encoder.Encode(buffer, index, count); } catch { _currentState = State.Error; throw; } } // Encodes the specified binary bytes as binhex and writes out the resulting text. public override void WriteBinHex(byte[] buffer, int index, int count) { try { AutoComplete(Token.Content); BinHexEncoder.Encode(buffer, index, count, this); } catch { _currentState = State.Error; throw; } } // Returns the state of the XmlWriter. public override WriteState WriteState { get { switch (_currentState) { case State.Start: return WriteState.Start; case State.Prolog: case State.PostDTD: return WriteState.Prolog; case State.Element: return WriteState.Element; case State.Attribute: case State.AttrOnly: return WriteState.Attribute; case State.Content: case State.Epilog: return WriteState.Content; case State.Error: return WriteState.Error; case State.Closed: return WriteState.Closed; default: Debug.Fail($"Unexpected state {_currentState}"); return WriteState.Error; } } } // Closes the XmlWriter and the underlying stream/TextWriter. public override void Close() { try { AutoCompleteAll(); } catch { // never fail } finally { _currentState = State.Closed; _textWriter.Dispose(); } } // Flushes whatever is in the buffer to the underlying stream/TextWriter and flushes the underlying stream/TextWriter. public override void Flush() { _textWriter.Flush(); } // Writes out the specified name, ensuring it is a valid Name according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name public override void WriteName(string name) { try { AutoComplete(Token.Content); InternalWriteName(name, false); } catch { _currentState = State.Error; throw; } } // Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace. public override void WriteQualifiedName(string localName, string ns) { try { AutoComplete(Token.Content); if (_namespaces) { if (ns != null && ns.Length != 0 && ns != _stack[_top].defaultNs) { string prefix = FindPrefix(ns); if (prefix == null) { if (_currentState != State.Attribute) { throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns)); } prefix = GeneratePrefix(); // need a prefix if PushNamespace(prefix, ns, false); } if (prefix.Length != 0) { InternalWriteName(prefix, true); _textWriter.Write(':'); } } } else if (ns != null && ns.Length != 0) { throw new ArgumentException(SR.Xml_NoNamespaces); } InternalWriteName(localName, true); } catch { _currentState = State.Error; throw; } } // Returns the closest prefix defined in the current namespace scope for the specified namespace URI. public override string LookupPrefix(string ns) { if (ns == null || ns.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } string s = FindPrefix(ns); if (s == null && ns == _stack[_top].defaultNs) { s = string.Empty; } return s; } // Gets an XmlSpace representing the current xml:space scope. public override XmlSpace XmlSpace { get { for (int i = _top; i > 0; i--) { XmlSpace xs = _stack[i].xmlSpace; if (xs != XmlSpace.None) return xs; } return XmlSpace.None; } } // Gets the current xml:lang scope. public override string XmlLang { get { for (int i = _top; i > 0; i--) { string xlang = _stack[i].xmlLang; if (xlang != null) return xlang; } return null; } } // Writes out the specified name, ensuring it is a valid NmToken // according to the XML specification (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public override void WriteNmToken(string name) { try { AutoComplete(Token.Content); if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } if (!ValidateNames.IsNmtokenNoNamespaces(name)) { throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name)); } _textWriter.Write(name); } catch { _currentState = State.Error; throw; } } // // Private implementation methods // private void StartDocument(int standalone) { try { if (_currentState != State.Start) { throw new InvalidOperationException(SR.Xml_NotTheFirst); } _stateTable = s_stateTableDocument; _currentState = State.Prolog; StringBuilder bufBld = new StringBuilder(128); bufBld.Append("version=" + _quoteChar + "1.0" + _quoteChar); if (_encoding != null) { bufBld.Append(" encoding="); bufBld.Append(_quoteChar); bufBld.Append(_encoding.WebName); bufBld.Append(_quoteChar); } if (standalone >= 0) { bufBld.Append(" standalone="); bufBld.Append(_quoteChar); bufBld.Append(standalone == 0 ? "no" : "yes"); bufBld.Append(_quoteChar); } InternalWriteProcessingInstruction("xml", bufBld.ToString()); } catch { _currentState = State.Error; throw; } } private void AutoComplete(Token token) { if (_currentState == State.Closed) { throw new InvalidOperationException(SR.Xml_Closed); } else if (_currentState == State.Error) { throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, s_tokenName[(int)token], s_stateName[(int)State.Error])); } State newState = _stateTable[(int)token * 8 + (int)_currentState]; if (newState == State.Error) { throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, s_tokenName[(int)token], s_stateName[(int)_currentState])); } switch (token) { case Token.Doctype: if (_indented && _currentState != State.Start) { Indent(false); } break; case Token.StartElement: case Token.Comment: case Token.PI: case Token.CData: if (_currentState == State.Attribute) { WriteEndAttributeQuote(); WriteEndStartTag(false); } else if (_currentState == State.Element) { WriteEndStartTag(false); } if (token == Token.CData) { _stack[_top].mixed = true; } else if (_indented && _currentState != State.Start) { Indent(false); } break; case Token.EndElement: case Token.LongEndElement: if (_flush) { FlushEncoders(); } if (_currentState == State.Attribute) { WriteEndAttributeQuote(); } if (_currentState == State.Content) { token = Token.LongEndElement; } else { WriteEndStartTag(token == Token.EndElement); } if (s_stateTableDocument == _stateTable && _top == 1) { newState = State.Epilog; } break; case Token.StartAttribute: if (_flush) { FlushEncoders(); } if (_currentState == State.Attribute) { WriteEndAttributeQuote(); _textWriter.Write(' '); } else if (_currentState == State.Element) { _textWriter.Write(' '); } break; case Token.EndAttribute: if (_flush) { FlushEncoders(); } WriteEndAttributeQuote(); break; case Token.Whitespace: case Token.Content: case Token.RawData: case Token.Base64: if (token != Token.Base64 && _flush) { FlushEncoders(); } if (_currentState == State.Element && _lastToken != Token.Content) { WriteEndStartTag(false); } if (newState == State.Content) { _stack[_top].mixed = true; } break; default: throw new InvalidOperationException(SR.Xml_InvalidOperation); } _currentState = newState; _lastToken = token; } private void AutoCompleteAll() { if (_flush) { FlushEncoders(); } while (_top > 0) { WriteEndElement(); } } private static readonly char[] s_selfClosingTagOpen = new char[] { '<', '/' }; private void InternalWriteEndElement(bool longFormat) { try { if (_top <= 0) { throw new InvalidOperationException(SR.Xml_NoStartTag); } // if we are in the element, we need to close it. AutoComplete(longFormat ? Token.LongEndElement : Token.EndElement); if (_lastToken == Token.LongEndElement) { if (_indented) { Indent(true); } _textWriter.Write(s_selfClosingTagOpen); if (_namespaces && _stack[_top].prefix != null) { _textWriter.Write(_stack[_top].prefix); _textWriter.Write(':'); } _textWriter.Write(_stack[_top].name); _textWriter.Write('>'); } // pop namespaces int prevNsTop = _stack[_top].prevNsTop; if (_useNsHashtable && prevNsTop < _nsTop) { PopNamespaces(prevNsTop + 1, _nsTop); } _nsTop = prevNsTop; _top--; } catch { _currentState = State.Error; throw; } } private static readonly char[] s_closeTagEnd = new char[] { ' ', '/', '>' }; private void WriteEndStartTag(bool empty) { _xmlEncoder.StartAttribute(false); for (int i = _nsTop; i > _stack[_top].prevNsTop; i--) { if (!_nsStack[i].declared) { _textWriter.Write(" xmlns:"); _textWriter.Write(_nsStack[i].prefix); _textWriter.Write('='); _textWriter.Write(_quoteChar); _xmlEncoder.Write(_nsStack[i].ns); _textWriter.Write(_quoteChar); } } // Default if ((_stack[_top].defaultNs != _stack[_top - 1].defaultNs) && (_stack[_top].defaultNsState == NamespaceState.DeclaredButNotWrittenOut)) { _textWriter.Write(" xmlns="); _textWriter.Write(_quoteChar); _xmlEncoder.Write(_stack[_top].defaultNs); _textWriter.Write(_quoteChar); _stack[_top].defaultNsState = NamespaceState.DeclaredAndWrittenOut; } _xmlEncoder.EndAttribute(); if (empty) { _textWriter.Write(s_closeTagEnd); } else { _textWriter.Write('>'); } } private void WriteEndAttributeQuote() { if (_specialAttr != SpecialAttr.None) { // Ok, now to handle xmlspace, etc. HandleSpecialAttribute(); } _xmlEncoder.EndAttribute(); _textWriter.Write(_curQuoteChar); } private void Indent(bool beforeEndElement) { // pretty printing. if (_top == 0) { _textWriter.WriteLine(); } else if (!_stack[_top].mixed) { _textWriter.WriteLine(); int i = (beforeEndElement ? _top - 1 : _top) * _indentation; if(i <= _indentChars.Length) { _textWriter.Write(_indentChars, 0, i); } else { while(i > 0) { _textWriter.Write(_indentChars, 0, Math.Min(i, _indentChars.Length)); i -= _indentChars.Length; } } } } // pushes new namespace scope, and returns generated prefix, if one // was needed to resolve conflicts. private void PushNamespace(string prefix, string ns, bool declared) { if (XmlReservedNs.NsXmlNs == ns) { throw new ArgumentException(SR.Xml_CanNotBindToReservedNamespace); } if (prefix == null) { switch (_stack[_top].defaultNsState) { case NamespaceState.DeclaredButNotWrittenOut: Debug.Assert(declared == true, "Unexpected situation!!"); // the first namespace that the user gave us is what we // like to keep. break; case NamespaceState.Uninitialized: case NamespaceState.NotDeclaredButInScope: // we now got a brand new namespace that we need to remember _stack[_top].defaultNs = ns; break; default: Debug.Fail("Should have never come here"); return; } _stack[_top].defaultNsState = (declared ? NamespaceState.DeclaredAndWrittenOut : NamespaceState.DeclaredButNotWrittenOut); } else { if (prefix.Length != 0 && ns.Length == 0) { throw new ArgumentException(SR.Xml_PrefixForEmptyNs); } int existingNsIndex = LookupNamespace(prefix); if (existingNsIndex != -1 && _nsStack[existingNsIndex].ns == ns) { // it is already in scope. if (declared) { _nsStack[existingNsIndex].declared = true; } } else { // see if prefix conflicts for the current element if (declared) { if (existingNsIndex != -1 && existingNsIndex > _stack[_top].prevNsTop) { _nsStack[existingNsIndex].declared = true; // old one is silenced now } } AddNamespace(prefix, ns, declared); } } } private void AddNamespace(string prefix, string ns, bool declared) { int nsIndex = ++_nsTop; if (nsIndex == _nsStack.Length) { Namespace[] newStack = new Namespace[nsIndex * 2]; Array.Copy(_nsStack, newStack, nsIndex); _nsStack = newStack; } _nsStack[nsIndex].Set(prefix, ns, declared); if (_useNsHashtable) { AddToNamespaceHashtable(nsIndex); } else if (nsIndex == MaxNamespacesWalkCount) { // add all _nsHashtable = new Dictionary<string, int>(new SecureStringHasher()); for (int i = 0; i <= nsIndex; i++) { AddToNamespaceHashtable(i); } _useNsHashtable = true; } } private void AddToNamespaceHashtable(int namespaceIndex) { string prefix = _nsStack[namespaceIndex].prefix; int existingNsIndex; if (_nsHashtable.TryGetValue(prefix, out existingNsIndex)) { _nsStack[namespaceIndex].prevNsIndex = existingNsIndex; } _nsHashtable[prefix] = namespaceIndex; } private void PopNamespaces(int indexFrom, int indexTo) { Debug.Assert(_useNsHashtable); for (int i = indexTo; i >= indexFrom; i--) { Debug.Assert(_nsHashtable.ContainsKey(_nsStack[i].prefix)); if (_nsStack[i].prevNsIndex == -1) { _nsHashtable.Remove(_nsStack[i].prefix); } else { _nsHashtable[_nsStack[i].prefix] = _nsStack[i].prevNsIndex; } } } private string GeneratePrefix() { int temp = _stack[_top].prefixCount++ + 1; return "d" + _top.ToString("d", CultureInfo.InvariantCulture) + "p" + temp.ToString("d", CultureInfo.InvariantCulture); } private void InternalWriteProcessingInstruction(string name, string text) { _textWriter.Write("<?"); ValidateName(name, false); _textWriter.Write(name); _textWriter.Write(' '); if (null != text) { _xmlEncoder.WriteRawWithSurrogateChecking(text); } _textWriter.Write("?>"); } private int LookupNamespace(string prefix) { if (_useNsHashtable) { int nsIndex; if (_nsHashtable.TryGetValue(prefix, out nsIndex)) { return nsIndex; } } else { for (int i = _nsTop; i >= 0; i--) { if (_nsStack[i].prefix == prefix) { return i; } } } return -1; } private int LookupNamespaceInCurrentScope(string prefix) { if (_useNsHashtable) { int nsIndex; if (_nsHashtable.TryGetValue(prefix, out nsIndex)) { if (nsIndex > _stack[_top].prevNsTop) { return nsIndex; } } } else { for (int i = _nsTop; i > _stack[_top].prevNsTop; i--) { if (_nsStack[i].prefix == prefix) { return i; } } } return -1; } private string FindPrefix(string ns) { for (int i = _nsTop; i >= 0; i--) { if (_nsStack[i].ns == ns) { if (LookupNamespace(_nsStack[i].prefix) == i) { return _nsStack[i].prefix; } } } return null; } // There are three kind of strings we write out - Name, LocalName and Prefix. // Both LocalName and Prefix can be represented with NCName == false and Name // can be represented as NCName == true private void InternalWriteName(string name, bool isNCName) { ValidateName(name, isNCName); _textWriter.Write(name); } // This method is used for validation of the DOCTYPE, processing instruction and entity names plus names // written out by the user via WriteName and WriteQualifiedName. // Unfortunatelly the names of elements and attributes are not validated by the XmlTextWriter. // Also this method does not check wheather the character after ':' is a valid start name character. It accepts // all valid name characters at that position. This can't be changed because of backwards compatibility. private unsafe void ValidateName(string name, bool isNCName) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } int nameLength = name.Length; // Namespaces supported if (_namespaces) { // We can't use ValidateNames.ParseQName here because of backwards compatibility bug we need to preserve. // The bug is that the character after ':' is validated only as a NCName characters instead of NCStartName. int colonPosition = -1; // Parse NCName (may be prefix, may be local name) int position = ValidateNames.ParseNCName(name); Continue: if (position == nameLength) { return; } // we have prefix:localName if (name[position] == ':') { if (!isNCName) { // first colon in qname if (colonPosition == -1) { // make sure it is not the first or last characters if (position > 0 && position + 1 < nameLength) { colonPosition = position; // Because of the back-compat bug (described above) parse the rest as Nmtoken position++; position += ValidateNames.ParseNmtoken(name, position); goto Continue; } } } } } // Namespaces not supported else { if (ValidateNames.IsNameNoNamespaces(name)) { return; } } throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name)); } private void HandleSpecialAttribute() { string value = _xmlEncoder.AttributeValue; switch (_specialAttr) { case SpecialAttr.XmlLang: _stack[_top].xmlLang = value; break; case SpecialAttr.XmlSpace: // validate XmlSpace attribute value = XmlConvert.TrimString(value); if (value == "default") { _stack[_top].xmlSpace = XmlSpace.Default; } else if (value == "preserve") { _stack[_top].xmlSpace = XmlSpace.Preserve; } else { throw new ArgumentException(SR.Format(SR.Xml_InvalidXmlSpace, value)); } break; case SpecialAttr.XmlNs: VerifyPrefixXml(_prefixForXmlNs, value); PushNamespace(_prefixForXmlNs, value, true); break; } } private void VerifyPrefixXml(string prefix, string ns) { if (prefix != null && prefix.Length == 3) { if ( (prefix[0] == 'x' || prefix[0] == 'X') && (prefix[1] == 'm' || prefix[1] == 'M') && (prefix[2] == 'l' || prefix[2] == 'L') ) { if (XmlReservedNs.NsXml != ns) { throw new ArgumentException(SR.Xml_InvalidPrefix); } } } } private void PushStack() { if (_top == _stack.Length - 1) { TagInfo[] na = new TagInfo[_stack.Length + 10]; if (_top > 0) Array.Copy(_stack, na, _top + 1); _stack = na; } _top++; // Move up stack _stack[_top].Init(_nsTop); } private void FlushEncoders() { if (null != _base64Encoder) { // The Flush will call WriteRaw to write out the rest of the encoded characters _base64Encoder.Flush(); } _flush = false; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class JoinClusterDecoder { public const ushort BLOCK_LENGTH = 12; public const ushort TEMPLATE_ID = 74; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private JoinClusterDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public JoinClusterDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public JoinClusterDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int LeadershipTermIdId() { return 1; } public static int LeadershipTermIdSinceVersion() { return 0; } public static int LeadershipTermIdEncodingOffset() { return 0; } public static int LeadershipTermIdEncodingLength() { return 8; } public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LeadershipTermIdMaxValue() { return 9223372036854775807L; } public long LeadershipTermId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int MemberIdId() { return 2; } public static int MemberIdSinceVersion() { return 0; } public static int MemberIdEncodingOffset() { return 8; } public static int MemberIdEncodingLength() { return 4; } public static string MemberIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int MemberIdNullValue() { return -2147483648; } public static int MemberIdMinValue() { return -2147483647; } public static int MemberIdMaxValue() { return 2147483647; } public int MemberId() { return _buffer.GetInt(_offset + 8, ByteOrder.LittleEndian); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[JoinCluster](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LeadershipTermId="); builder.Append(LeadershipTermId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='memberId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("MemberId="); builder.Append(MemberId()); Limit(originalLimit); return builder; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.DoNotHideBaseClassMethodsAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpDoNotHideBaseClassMethodsFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.DoNotHideBaseClassMethodsAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicDoNotHideBaseClassMethodsFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class DoNotHideBaseClassMethodsTests { [Fact] public async Task CA1061_DerivedMethodMatchesBaseMethod_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" class Base { public void Method(string input) { } } class Derived : Base { public void Method(string input) { } }"); await VerifyVB.VerifyAnalyzerAsync(@" Class Base Public Sub Method(input As String) End Sub End Class Class Derived Inherits Base Public Sub Method(input As String) End Sub End Class"); } [Fact] public async Task CA1061_DerivedMethodHasMoreDerivedParameter_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" class Base { public void Method(object input) { } } class Derived : Base { public void Method(string input) { } }"); await VerifyVB.VerifyAnalyzerAsync(@" Class Base Public Sub Method(input As Object) End Sub End Class Class Derived Inherits Base Public Sub Method(input As String) End Sub End Class"); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" class Base { public void Method(string input) { } } class Derived : Base { public void Method(object input) { } }", GetCA1061CSharpResultAt(11, 17, "Derived.Method(object)", "Base.Method(string)")); await VerifyVB.VerifyAnalyzerAsync(@" Class Base Public Sub Method(input As String) End Sub End Class Class Derived Inherits Base Public Sub Method(input As Object) End Sub End Class", GetCA1061BasicResultAt(10, 16, "Public Sub Method(input As Object)", "Public Sub Method(input As String)")); } [Fact] public async Task CA1061_ConstructorCallsBaseConstructorWithDifferentParameterType_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" class Base { public Base(string input) { } } class Derived : Base { public Derived(object input) :base(null) { } } "); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_MultipleMethodsHidden_Diagnostics() { await VerifyCS.VerifyAnalyzerAsync(@" class Parent { public void Method(string input) { } } class Child : Parent { public void Method(string input) { } } class Grandchild : Child { public void Method(object input) { } }", GetCA1061CSharpResultAt(18, 17, "Grandchild.Method(object)", "Child.Method(string)"), GetCA1061CSharpResultAt(18, 17, "Grandchild.Method(object)", "Parent.Method(string)")); await VerifyVB.VerifyAnalyzerAsync(@" Class Parent Public Sub Method(input As String) End Sub End Class Class Child Inherits Parent Public Sub Method(input as String) End Sub End Class Class Grandchild Inherits Child Public Sub Method(input As Object) End Sub End Class", GetCA1061BasicResultAt(17, 16, "Public Sub Method(input As Object)", "Public Sub Method(input As String)"), GetCA1061BasicResultAt(17, 16, "Public Sub Method(input As Object)", "Public Sub Method(input As String)")); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_ImplementsInterface_CompileError() { await VerifyCS.VerifyAnalyzerAsync(@" interface IFace { void Method(string input); } class Derived : {|CS0535:IFace|} { public void Method(object input) { } }"); await VerifyVB.VerifyAnalyzerAsync(@" Interface IFace Sub Method(input As String) End Interface Class Derived Implements {|BC30149:IFace|} Public Sub Method(input As Object) Implements {|BC30401:IFace.Method|} End Sub End Class"); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_OverridesVirtualBaseMethod_CompileError() { await VerifyCS.VerifyAnalyzerAsync(@" class Base { public virtual void {|CS0501:Method|}(string input); } class Derived : Base { public override void {|CS0115:Method|}(object input) { } }"); await VerifyVB.VerifyAnalyzerAsync(@" Class Base Public Overridable Sub Method(input As String) End Sub End Class Class Derived Inherits Base Public Overrides Sub {|BC30284:Method|}(input As Object) End Sub End Class"); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_OverridesAbstractBaseMethod_CompileError() { await VerifyCS.VerifyAnalyzerAsync(@" abstract class Base { public abstract void Method(string input); } class {|CS0534:Derived|} : Base { public override void {|CS0115:Method|}(object input) { } }"); await VerifyVB.VerifyAnalyzerAsync(@" MustInherit Class Base Public MustOverride Sub Method(input As String) {|BC30429:End Sub|} End Class Class {|BC30610:Derived|} Inherits Base Public Overrides Sub {|BC30284:Method|}(input As Object) End Sub End Class"); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_DerivedMethodPrivate_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" class Base { public void Method(string input) { } } class Derived : Base { private void Method(object input) { } }", GetCA1061CSharpResultAt(11, 18, "Derived.Method(object)", "Base.Method(string)")); await VerifyVB.VerifyAnalyzerAsync(@" Class Base Public Sub Method(input As String) End Sub End Class Class Derived Inherits Base Public Sub Method(input As Object) End Sub End Class ", GetCA1061BasicResultAt(10, 16, "Public Sub Method(input As Object)", "Public Sub Method(input As String)")); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_BaseMethodPrivate_NoDiagnostic() { // Note: This behavior differs from FxCop's CA1061 await VerifyCS.VerifyAnalyzerAsync(@" class Base { private void Method(string input) { } } class Derived : Base { public void Method(object input) { } }"); await VerifyVB.VerifyAnalyzerAsync(@" Class Base Private Sub Method(input As String) End Sub End Class Class Derived Inherits Base Public Sub Method(input As Object) End Sub End Class "); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_ArityMismatch_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" class Base { public void Method(string input, string input2) { } } class Derived : Base { public void Method(object input) { } }"); await VerifyVB.VerifyAnalyzerAsync(@" Class Base Private Sub Method(input As String, input2 As String) End Sub End Class Class Derived Inherits Base Public Sub Method(input As Object) End Sub End Class "); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_ReturnTypeMismatch_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" class Base { public void Method(string input) { } } class Derived : Base { public int Method(object input) { return 0; } }"); await VerifyVB.VerifyAnalyzerAsync(@" Class Base Private Sub Method(input As String) End Sub End Class Class Derived Inherits Base Public Function Method(input As Object) As Integer Method = 0 End Function End Class "); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_ParameterTypeMismatchAtStart_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" class Base { public void Method(int input, string input2) { } } class Derived : Base { public void Method(char input, object input2) { } }"); await VerifyVB.VerifyAnalyzerAsync(@" Class Base Private Sub Method(input As Integer, input2 As String) End Sub End Class Class Derived Inherits Base Public Sub Method(input As Char, input2 As Object) End Sub End Class "); } [Fact] public async Task CA1061_DerivedMethodHasLessDerivedParameter_ParameterTypeMismatchAtEnd_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" class Base { public void Method(string input, int input2) { } } class Derived : Base { public void Method(object input, char input2) { } }"); await VerifyVB.VerifyAnalyzerAsync(@" Class Base Private Sub Method(input As String, input2 As Integer) End Sub End Class Class Derived Inherits Base Public Sub Method(input As Object, input2 As Char) End Sub End Class "); } private static DiagnosticResult GetCA1061CSharpResultAt(int line, int column, string derivedMethod, string baseMethod) => VerifyCS.Diagnostic() .WithLocation(line, column) .WithArguments(derivedMethod, baseMethod); private static DiagnosticResult GetCA1061BasicResultAt(int line, int column, string derivedMethod, string baseMethod) => VerifyVB.Diagnostic() .WithLocation(line, column) .WithArguments(derivedMethod, baseMethod); } }
/* * Meshinator * Copyright Mike Mahoney 2013 */ using UnityEngine; using System.Collections; using System.Collections.Generic; [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(Rigidbody))] public class Meshinator : MonoBehaviour { #region Fields & Properties public enum CacheOptions { None = 0, CacheAfterCollision = 1, CacheOnLoad = 2, }; public enum ImpactShapes { FlatImpact = 0, SphericalImpact = 1, }; public enum ImpactTypes { Compression = 0, Fracture = 1, }; // This is how many FixedUpdates we require before we will do anything in the OnCollisionEnter function. // If this many FixedUpdate calls have occurred and we have not collided with anything, then the // OnCollisionEnter function will the work normally. This is meant to prevent SubHulls creating new // GameObjects with colliders that overlap from the start and cause bad behavior. private const int c_FixedUpdateCountToIgnoreCollisions = 3; // This determines when we load up the Hull object. // - "None" means that nothing is loaded until a collision occurs; this has no extra memory or CPU // cost except when a collision is occuring, but the collision will take longer to compute. // - "CacheAfterCollision" loads a copy of the mesh during the first collision and maintains that // information from that point forward. This will mean a heavier memory footprint for each object // that has already had at least one collsion, but each collsion after the first will compute faster. // - "CacheOnLoad" loads a copy of the mesh on Start, which means a heavier footprint from the // beginning, but every deformation computation will be faster than they would without caching. public CacheOptions m_CacheOption = CacheOptions.CacheAfterCollision; // This determines what kind of deformation calculations will occur on a collision. // - "FlatImpact" treats the deformation as if the collision ocurred against a flat plane. This is // generally fine for collisions between objects of roughly the same size. // - "Spherical Impact" treats the deformation is if the collision occured against a sphere. This is // good when objects colliding against this one are expected to be much smaller than this object. public ImpactShapes m_ImpactShape = ImpactShapes.FlatImpact; // This determines what the result of the deformation calculations will be after a collision. // - "Compression" compresses the mesh on impact, but does not create any extra debris // - "Fracture" shatters a mesh into seperate meshes on seperate game objects public ImpactTypes m_ImpactType = ImpactTypes.Compression; // Subtracted from the force of an impact before any deformation is done. If the force becomes negative // due to this, no deformation will occur (the material resisted the impact). public float m_ForceResistance = 10f; // This is the maximum force that can affect a mesh on any given impact. Any force beyond this amount is // negated. If m_MaxForcePerImpact is less than or equal to m_ForceResistance, then no impact will ever // deform this GameObject's mesh. public float m_MaxForcePerImpact = 12f; // Multiplied by the force of an impact to determine the depth of an impact/explosion/etc. Higher // values indicate less dense materials (and thus more deformation), while smaller values indicate // more dense materials (and thus less deformation). public float m_ForceMultiplier = 0.25f; // Is an impact currently being calculated? If so, we'll end up ignoring other Impact calls to prevent // concurrent modifications to the mesh. private bool m_Calculating = false; // This is the cached Hull object that we may or may not use based on the set CacheOptions above. private Hull m_Hull = null; // These are the bounding boxes used to guide the mesh deformation so that it doesn't contract or expand // an unreasonable size. These are established either on Start (if CacheOptions.None), or on the first // collsion (if CacheOptions.CacheOnLoad or CacheOptions.CacheAfterCollision). private bool m_BoundsSet = false; private Bounds m_InitialBounds; // Collision-enabling info private bool m_ClearedForCollisions = true; private int m_CollisionCount = 0; private int m_FixedUpdatesSinceLastCollision = 0; #endregion Fields & Properties #region Unity Functions public void Start() { if (m_CacheOption == CacheOptions.CacheOnLoad) { // Make sure we have a MeshFilter MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>(); if (meshFilter == null || meshFilter.sharedMesh == null) return; // Get the initial bounding box for this mesh m_InitialBounds = meshFilter.sharedMesh.bounds; m_BoundsSet = true; // Generate a hull to work with m_Hull = new Hull(meshFilter.sharedMesh); } } public void FixedUpdate() { // Keep track of how many FixedUpdates occur while m_ClearedForCollisions is false. // If enough FixedUpdate calls have occurred and we have not collided with anything, then the // OnCollisionEnter function will the work normally. This is meant to prevent SubHulls creating new // GameObjects with colliders that overlap from the start and cause bad behavior. if (m_ClearedForCollisions == false) { if (m_CollisionCount != 0) m_FixedUpdatesSinceLastCollision = 0; else m_FixedUpdatesSinceLastCollision++; if (m_FixedUpdatesSinceLastCollision > c_FixedUpdateCountToIgnoreCollisions) m_ClearedForCollisions = true; } } #endregion Unity Functions #region Collision Callback Functions public void OnCollisionEnter(Collision collision) { m_CollisionCount++; if (m_ClearedForCollisions && collision.impactForceSum.magnitude >= m_ForceResistance) { // Find the impact point foreach (ContactPoint contact in collision.contacts) { if (contact.otherCollider == collision.collider) { Impact(contact.point, collision.impactForceSum, m_ImpactShape, m_ImpactType); break; } } } } public void OnCollisionExit() { m_CollisionCount--; } #endregion Collision Callback Functions #region Impact Functions public void DelayCollisions() { m_ClearedForCollisions = false; } public void Impact(Vector3 point, Vector3 force, ImpactShapes impactShape, ImpactTypes impactType) { // See if we can do this right now if (!CanDoImpact(point, force)) return; // We're now set on course to calculate the impact deformation m_Calculating = true; // Set up m_Hull InitializeHull(); // Figure out the true impact force if (force.magnitude > m_MaxForcePerImpact) force = force.normalized * m_MaxForcePerImpact; float impactFactor = (force.magnitude - m_ForceResistance) * m_ForceMultiplier; if (impactFactor <= 0) return; // Localize the point and the force to account for transform scaling (and maybe rotation or translation) Vector3 impactPoint = transform.InverseTransformPoint(point); Vector3 impactForce = transform.InverseTransformDirection(force.normalized) * impactFactor; // Limit the force by the extents of the initial bounds to keep things reasonable float impactForceX = Mathf.Max(Mathf.Min(impactForce.x, m_InitialBounds.extents.x), -m_InitialBounds.extents.x); float impactForceY = Mathf.Max(Mathf.Min(impactForce.y, m_InitialBounds.extents.y), -m_InitialBounds.extents.y); float impactForceZ = Mathf.Max(Mathf.Min(impactForce.z, m_InitialBounds.extents.z), -m_InitialBounds.extents.z); impactForce = new Vector3(impactForceX, impactForceY, impactForceZ); // Run the mesh deformation on another thread ThreadManager.RunAsync(()=> { // Do all the math to deform this mesh m_Hull.Impact(impactPoint, impactForce, impactShape, impactType); // Queue the final mesh setting on the main thread once the deformations are done ThreadManager.QueueOnMainThread(()=> { // Clear out the current Mesh and MeshCollider (if we have one) for now MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>(); if (meshFilter != null) meshFilter.sharedMesh = null; MeshCollider meshCollider = gameObject.GetComponent<MeshCollider>(); if (meshCollider != null) meshCollider.sharedMesh = null; // Get the newly-adjusted Mesh so we can work with it Mesh newMesh = m_Hull.GetMesh(); // If this is a fracture, then create a new GameObject for the chunk that broke off if (impactType == ImpactTypes.Fracture) { Mesh subHullMesh = m_Hull.GetSubHullMesh(); if (subHullMesh != null) { // Create the new GameObject GameObject newGO = (GameObject)GameObject.Instantiate(gameObject); // Set the new Mesh onto the MeshFilter and MeshCollider MeshFilter newMeshFilter = newGO.GetComponent<MeshFilter>(); MeshCollider newMeshCollider = newGO.GetComponent<MeshCollider>(); if (newMeshFilter != null) newMeshFilter.sharedMesh = subHullMesh; if (newMeshCollider != null) newMeshCollider.sharedMesh = subHullMesh; // If using convex MeshColliders, it's possible for colliders to overlap right after a // fracture, which causes exponentially more fractures... So, right after a fracture, // temporarily disable impacts to both the old GameObject, and the new one we just created DelayCollisions(); Meshinator subHullMeshinator = newGO.GetComponent<Meshinator>(); if (subHullMeshinator != null) subHullMeshinator.DelayCollisions(); // Figure out the approximate volume of our Hull and SubHull meshes. This // will be used to calculate the rigidbody masses (if a rigidbodies are present) // for the old and new GameObjects. if (gameObject.rigidbody != null && newGO.rigidbody != null) { Vector3 hullSize = newMesh.bounds.size; float hullVolume = hullSize.x * hullSize.y * hullSize.z; Vector3 subHullSize = subHullMesh.bounds.size; float subHullVolume = subHullSize.x * subHullSize.y * subHullSize.z; float totalVolume = hullVolume + subHullVolume; float totalMass = gameObject.rigidbody.mass; gameObject.rigidbody.mass = totalMass * (hullVolume / totalVolume); newGO.rigidbody.mass = totalMass * (subHullVolume / totalVolume); // Set the old velocity onto the new GameObject's rigidbody newGO.rigidbody.velocity = gameObject.rigidbody.velocity; // Set the centers of mass to be within the new meshes gameObject.rigidbody.centerOfMass = newMesh.bounds.center; newGO.rigidbody.centerOfMass = subHullMesh.bounds.center; } } } // Set the hull's new mesh back onto this game object if (meshFilter != null) meshFilter.sharedMesh = newMesh; // If this GameObject has a MeshCollider, put the new mesh there too if (meshCollider != null) meshCollider.sharedMesh = newMesh; // Drop our cached Hull if we're not supposed to keep it around if (m_CacheOption == CacheOptions.None) m_Hull = null; // Our calculations are done m_Calculating = false; }); }); } private void InitializeHull() { // See if we already have a hull if (m_Hull == null) { // Make sure we have a MeshFilter MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>(); if (meshFilter == null || meshFilter.sharedMesh == null) { m_Calculating = false; return; } // Get the initial bounding box for this mesh if needed if (m_BoundsSet == false) { m_InitialBounds = meshFilter.sharedMesh.bounds; m_BoundsSet = true; } // Generate a hull to work with m_Hull = new Hull(meshFilter.sharedMesh); } } private bool CanDoImpact(Vector3 point, Vector3 force) { //If we are already handling a call to FlatImpact, we'll end up ignoring other Impact calls to // prevent concurrent modifications to the mesh. if (m_Calculating) return false; // Make sure this force can affect this object float forceMagnitude = force.magnitude; if (forceMagnitude - m_ForceResistance <= 0) return false; // Figure out the true impact force, and make sure it's greater than zero float impactFactor = (forceMagnitude - m_ForceResistance) * m_ForceMultiplier; if (impactFactor <= 0) return false; return true; } #endregion Impact Functions }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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. #define USE_IPC using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; using Gallio.Common; using Gallio.Common.IO; using Gallio.Common.Platform; using Gallio.Common.Reflection; using Gallio.Runtime.Debugging; using Gallio.Runtime.Logging; using Gallio.Common.Concurrency; using Gallio.Common.Remoting; using Timer=System.Threading.Timer; namespace Gallio.Runtime.Hosting { /// <summary> /// An isolated process host is a <see cref="IHost" /> that runs code within a /// new external process. /// </summary> /// <remarks> /// <para> /// Communication with the external process occurs over /// an inter-process communication channel. /// </para> /// <para> /// The host application is copied to a unique temporary folder and configured /// in place according to the <see cref="HostSetup" />. Then it is launched /// and connected to with inter-process communication. The process is pinged /// periodically by the <see cref="BinaryIpcClientChannel" />. Therefore it /// can be configured to self-terminate when it looks like the connection /// has been severed. /// </para> /// </remarks> public class IsolatedProcessHost : RemoteHost { private static readonly TimeSpan ReadyTimeout = TimeSpan.FromSeconds(60); private static readonly TimeSpan ReadyPollInterval = TimeSpan.FromSeconds(0.5); private static readonly TimeSpan PingInterval = TimeSpan.FromSeconds(5); private static readonly TimeSpan JoinBeforeAbortTimeout = TimeSpan.FromMinutes(10); // This timeout is purposely long to allow code coverage tools to finish up. private static readonly TimeSpan JoinBeforeAbortWarningTimeout = TimeSpan.FromSeconds(10); private static readonly TimeSpan JoinAfterAbortTimeout = TimeSpan.FromSeconds(15); // FIXME: Large timeout to workaround the remoting starvation issue. See Google Code issue #147. Reduce value when fixed. private static readonly TimeSpan WatchdogTimeout = TimeSpan.FromSeconds(120); private readonly string runtimePath; private readonly string uniqueId; private string temporaryConfigurationFilePath; private ProcessTask processTask; private IClientChannel clientChannel; private IServerChannel callbackChannel; private SeverityPrefixParser severityPrefixParser; private const int logConsoleOutputBufferTimeoutMilliseconds = 100; private readonly Timer logConsoleOutputBufferTimer; private LogSeverity logConsoleOutputBufferedMessageSeverity; private string logConsoleOutputBufferedMessage; /// <summary> /// Creates an uninitialized host. /// </summary> /// <param name="hostSetup">The host setup.</param> /// <param name="logger">The logger for host message output.</param> /// <param name="runtimePath">The runtime path where the hosting executable will be found.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="hostSetup"/> /// <paramref name="logger"/>, or <paramref name="runtimePath"/> is null.</exception> public IsolatedProcessHost(HostSetup hostSetup, ILogger logger, string runtimePath) : base(hostSetup, logger, PingInterval) { if (runtimePath == null) throw new ArgumentNullException("runtimePath"); this.runtimePath = runtimePath; uniqueId = Hash64.CreateUniqueHash().ToString(); logConsoleOutputBufferTimer = new Timer(LogConsoleOutputBufferTimeoutExpired); } /// <inheritdoc /> protected override IRemoteHostService AcquireRemoteHostService() { try { string hostConnectionArguments; Func<IClientChannel> clientChannelFactory; Func<IServerChannel> callbackChannelFactory; PrepareConnection(uniqueId, out hostConnectionArguments, out clientChannelFactory, out callbackChannelFactory); StartProcess(hostConnectionArguments); EnsureProcessIsRunning(); clientChannel = clientChannelFactory(); callbackChannel = callbackChannelFactory(); IRemoteHostService hostService = HostServiceChannelInterop.GetRemoteHostService(clientChannel); WaitUntilReady(hostService); return hostService; } catch (Exception ex) { FreeResources(true); throw new HostException("Error attaching to the host process.", ex); } } /// <inheritdoc /> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) FreeResources(false); } /// <summary> /// Creates the process task to start the process. /// </summary> /// <remarks> /// <para> /// This method can be overridden to change how the process is started. /// </para> /// </remarks> /// <param name="executablePath">The executable path.</param> /// <param name="arguments">The command-line arguments.</param> /// <param name="workingDirectory">The working directory.</param> /// <returns>The process task.</returns> protected virtual ProcessTask CreateProcessTask(string executablePath, string arguments, string workingDirectory) { return new HostProcessTask(executablePath, arguments, workingDirectory, HostSetup.DebuggerSetup, Logger); } /// <summary> /// Prepares the parameters for the remote connection. /// </summary> /// <param name="uniqueId">The unique id of the host.</param> /// <param name="hostConnectionArguments">Set to the host application arguments used to configure its server channel.</param> /// <param name="clientChannelFactory">Set to a factory used to create the local client channel.</param> /// <param name="callbackChannelFactory">Set to a factory used to create the local server channel to allow the remote host to call back to this one.</param> protected virtual void PrepareConnection(string uniqueId, out string hostConnectionArguments, out Func<IClientChannel> clientChannelFactory, out Func<IServerChannel> callbackChannelFactory) { #if USE_IPC string portName = @"IsolatedProcessHost." + uniqueId; hostConnectionArguments = "/ipc-port:" + portName; clientChannelFactory = delegate { return new BinaryIpcClientChannel(portName); }; callbackChannelFactory = delegate { return new BinaryIpcServerChannel(portName + ".Callback"); }; #else // The TCP channel implementation needs some work to become useful. // I implemented it partially as part of an effort to isolate the source of some // remoting timeouts that were occurring. In due time the whole channel-based // remoting infrastructure will probably need to be overhauled to use truly // bidirectional channels. -- Jeff. hostConnectionArguments = "/tcp-port:63217"; clientChannelFactory = delegate { return new BinaryTcpClientChannel("localhost", 63217); }; callbackChannelFactory = delegate { return new BinaryTcpServerChannel("localhost", 63218); }; #endif } private void StartProcess(string hostConnectionArguments) { bool useElevation = HostSetup.Elevated && !DotNetRuntimeSupport.IsUsingMono; CreateTemporaryConfigurationFile(); StringBuilder hostArguments = new StringBuilder(); hostArguments.Append(hostConnectionArguments); if (HostSetup.DebuggerSetup == null) hostArguments.Append(@" /timeout:").Append((int)WatchdogTimeout.TotalSeconds); hostArguments.Append(@" /owner-process:").Append(Process.GetCurrentProcess().Id); if (HostSetup.ApplicationBaseDirectory != null) hostArguments.Append(@" /application-base-directory:""").Append( FileUtils.StripTrailingBackslash(HostSetup.ApplicationBaseDirectory)).Append('"'); foreach (string hintDirectory in HostSetup.HintDirectories) hostArguments.Append(@" /hint-directory:""").Append( FileUtils.StripTrailingBackslash(hintDirectory)).Append('"'); hostArguments.Append(@" /configuration-file:""").Append(temporaryConfigurationFilePath).Append('"'); if (HostSetup.ShadowCopy) hostArguments.Append(@" /shadow-copy"); if (HostSetup.DebuggerSetup != null) hostArguments.Append(@" /debug"); hostArguments.Append(" /severity-prefix"); if (useElevation) hostArguments.Append(" /quiet"); severityPrefixParser = new SeverityPrefixParser(); processTask = CreateProcessTask(GetInstalledHostProcessPath(), hostArguments.ToString(), HostSetup.WorkingDirectory ?? Environment.CurrentDirectory); processTask.Terminated += HandleProcessExit; if (useElevation) { if (HostSetup.RuntimeVersion != null) throw new HostException("The host does not support a non-default RuntimeVersion with Elevation."); processTask.UseShellExecute = true; processTask.ConfigureProcessStartInfo += (sender, e) => { e.ProcessStartInfo.Verb = "runas"; e.ProcessStartInfo.ErrorDialog = true; e.ProcessStartInfo.ErrorDialogParentHandle = GetOwnerWindowHandle(); }; } else { processTask.CaptureConsoleOutput = true; processTask.CaptureConsoleError = true; processTask.ConsoleOutputDataReceived += LogConsoleOutput; processTask.ConsoleErrorDataReceived += LogConsoleError; // Force CLR runtime version. string runtimeVersion = HostSetup.RuntimeVersion; if (runtimeVersion == null) runtimeVersion = DotNetRuntimeSupport.MostRecentInstalledDotNetRuntimeVersion; if (!runtimeVersion.StartsWith("v")) runtimeVersion = "v" + runtimeVersion; // just in case, this is a common user error // http://msdn.microsoft.com/en-us/library/w4atty68.aspx if (runtimeVersion == "v4.0") runtimeVersion = "v4.0.30319"; processTask.SetEnvironmentVariable("COMPLUS_Version", runtimeVersion); } processTask.Start(); } private static IntPtr GetOwnerWindowHandle() { if (Application.MessageLoop) { foreach (Form form in Application.OpenForms) { if (form.TopLevel) return form.Handle; } } return IntPtr.Zero; } private void CreateTemporaryConfigurationFile() { try { HostSetup patchedSetup = HostSetup.Copy(); patchedSetup.Configuration.AddAssemblyBinding(new AssemblyBinding(typeof(IsolatedProcessHost).Assembly)); temporaryConfigurationFilePath = patchedSetup.WriteTemporaryConfigurationFile(); } catch (Exception ex) { throw new HostException("Could not write the temporary configuration file.", ex); } } private void LogConsoleOutput(object sender, DataReceivedEventArgs e) { lock (logConsoleOutputBufferTimer) { if (e.Data != null) { LogSeverity severity; string message; if (severityPrefixParser.ParseLine(e.Data, out severity, out message)) LogConsoleOutputWriteBufferedMessageSync(); message = message.TrimEnd(); logConsoleOutputBufferedMessageSeverity = severity; if (logConsoleOutputBufferedMessage == null) logConsoleOutputBufferedMessage = message; else logConsoleOutputBufferedMessage = string.Concat(logConsoleOutputBufferedMessage, "\n", message); logConsoleOutputBufferTimer.Change(logConsoleOutputBufferTimeoutMilliseconds, Timeout.Infinite); } else { LogConsoleOutputWriteBufferedMessageSync(); } } } private void LogConsoleOutputBufferTimeoutExpired(object dummy) { lock (logConsoleOutputBufferTimer) { LogConsoleOutputWriteBufferedMessageSync(); } } private void LogConsoleOutputWriteBufferedMessageSync() { if (logConsoleOutputBufferedMessage != null) { Logger.Log(logConsoleOutputBufferedMessageSeverity, logConsoleOutputBufferedMessage); logConsoleOutputBufferedMessage = null; } } private void LogConsoleError(object sender, DataReceivedEventArgs e) { if (e.Data != null) { Logger.Log(LogSeverity.Error, e.Data.TrimEnd()); } } private void HandleProcessExit(object sender, TaskEventArgs e) { var processTask = (ProcessTask)e.Task; if (! processTask.Result.HasValue) { Logger.Log(LogSeverity.Error, "Host process encountered an exception.", processTask.Result.Exception); } else { var diagnostics = new StringBuilder(); int exitCode = processTask.ExitCode; diagnostics.AppendFormat("Host process exited with code: {0}", exitCode); string exitCodeDescription = processTask.ExitCodeDescription; if (exitCodeDescription != null) diagnostics.Append(" (").Append(exitCodeDescription).Append(")"); Logger.Log(exitCode != 0 ? LogSeverity.Error : LogSeverity.Info, diagnostics.ToString()); } NotifyDisconnected(); } [DebuggerNonUserCode] private void WaitUntilReady(IHostService hostService) { Stopwatch stopwatch = Stopwatch.StartNew(); for (; ; ) { EnsureProcessIsRunning(); try { hostService.Ping(); return; } catch (Exception) { if (stopwatch.Elapsed >= ReadyTimeout) throw; } EnsureProcessIsRunning(); Thread.Sleep(ReadyPollInterval); } } private void EnsureProcessIsRunning() { if (! processTask.IsRunning) throw new HostException("The host process terminated abruptly."); } private void FreeResources(bool abortImmediately) { if (processTask != null) { if (! abortImmediately) { if (!processTask.Join(JoinBeforeAbortWarningTimeout)) { Logger.Log(LogSeverity.Info, "Waiting for the host process to terminate."); if (!processTask.Join(JoinBeforeAbortTimeout - JoinBeforeAbortWarningTimeout)) Logger.Log(LogSeverity.Info, string.Format("Timed out after {0} minutes.", JoinBeforeAbortTimeout.TotalMinutes)); } } if (! processTask.Join(TimeSpan.Zero)) { Logger.Log(LogSeverity.Warning, "Forcibly killing the host process!"); processTask.Abort(); processTask.Join(JoinAfterAbortTimeout); } processTask = null; } if (clientChannel != null) { clientChannel.Dispose(); clientChannel = null; } if (callbackChannel != null) { callbackChannel.Dispose(); callbackChannel = null; } if (temporaryConfigurationFilePath != null) { File.Delete(temporaryConfigurationFilePath); temporaryConfigurationFilePath = null; } lock (logConsoleOutputBufferTimer) { logConsoleOutputBufferTimer.Dispose(); } } private string GetInstalledHostProcessPath() { string hostProcessPath = Path.Combine(runtimePath, GetHostFileName(HostSetup.ProcessorArchitecture, HostSetup.Elevated)); if (!File.Exists(hostProcessPath)) throw new HostException(String.Format("Could not find the installed host application in '{0}'.", hostProcessPath)); return hostProcessPath; } private static string GetHostFileName(ProcessorArchitecture processorArchitecture, bool elevated) { // TODO: Should find a way to verify that Amd64 / IA64 are supported. switch (processorArchitecture) { case ProcessorArchitecture.None: case ProcessorArchitecture.MSIL: case ProcessorArchitecture.Amd64: case ProcessorArchitecture.IA64: return elevated ? "Gallio.Host.Elevated.exe" : "Gallio.Host.exe"; case ProcessorArchitecture.X86: return elevated ? "Gallio.Host.Elevated.x86.exe" : "Gallio.Host.x86.exe"; default: throw new ArgumentOutOfRangeException("processorArchitecture"); } } private sealed class HostProcessTask : ProcessTask { private readonly DebuggerSetup debuggerSetup; private readonly ILogger logger; public HostProcessTask(string executablePath, string arguments, string workingDirectory, DebuggerSetup debuggerSetup, ILogger logger) : base(executablePath, arguments, workingDirectory) { this.debuggerSetup = debuggerSetup; this.logger = logger; } protected override Process StartProcess(ProcessStartInfo startInfo) { if (debuggerSetup != null) { IDebugger debugger = new DefaultDebuggerManager().GetDebugger(debuggerSetup, logger); Process process = debugger.LaunchProcess(startInfo); if (process != null) return process; } return base.StartProcess(startInfo); } } } }
#region Copyright (C) 2012 // Project HWClassLibrary // Copyright (C) 2011 - 2012 Harald Hoyer // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // Comments, bugs and suggestions to hahoyer at yahoo.de #endregion using System; using System.Collections; using System.ComponentModel; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.Windows.Forms; using HWClassLibrary.Debug; using HWClassLibrary.Helper; using JetBrains.Annotations; namespace HWClassLibrary.TreeStructure { public static class Extender { /// <summary> /// Creates a treenode.with a given title from an object /// </summary> /// <param name="nodeData"> </param> /// <param name="title"> </param> /// <param name="iconKey"> </param> /// <param name="isDefaultIcon"> </param> /// <returns> </returns> public static TreeNode CreateNode(this object nodeData, string title = "", string iconKey = null, bool isDefaultIcon = false) { var result = new TreeNode(title + nodeData.GetAdditionalInfo()) {Tag = nodeData}; if(iconKey == null) iconKey = nodeData.GetIconKey(); if(isDefaultIcon) { var defaultIcon = nodeData.GetIconKey(); if(defaultIcon != null) iconKey = defaultIcon; } if(iconKey != null) { result.ImageKey = iconKey; result.SelectedImageKey = iconKey; } return result; } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt;: &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="iconKey"> The icon key. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> public static TreeNode CreateTaggedNode(this object nodeData, string title, string iconKey) { return nodeData.CreateTaggedNode(title, iconKey, false); } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt; = &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="iconKey"> The icon key. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> public static TreeNode CreateNamedNode(this object nodeData, string title, string iconKey) { return nodeData.CreateNamedNode(title, iconKey, false); } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt; = &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="iconKey"> The icon key. </param> /// <param name="isDefaultIcon"> if set to <c>true</c> [is default icon]. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> /// created 06.02.2007 23:26 public static TreeNode CreateNamedNode(this object nodeData, string title, string iconKey, bool isDefaultIcon) { return nodeData.CreateNode(title + " = ", iconKey, isDefaultIcon); } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt;: &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="iconKey"> The icon key. </param> /// <param name="isDefaultIcon"> if set to <c>true</c> [is default icon]. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> /// created 06.02.2007 23:26 public static TreeNode CreateTaggedNode(this object nodeData, string title, string iconKey, bool isDefaultIcon) { return nodeData.CreateNode(title + ": ", iconKey, isDefaultIcon); } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt;: &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> public static TreeNode CreateTaggedNode(this object nodeData, string title) { return nodeData.CreateTaggedNode(title, null, false); } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt; = &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> public static TreeNode CreateNamedNode(this object nodeData, string title) { return nodeData.CreateNamedNode(title, null, false); } static TreeNode[] InternalCreateNodes(IDictionary dictionary) { var result = new List<TreeNode>(); foreach(var element in dictionary) result.Add(CreateNumberedNode(element, result.Count, "ListItem")); return result.ToArray(); } static TreeNode CreateNumberedNode(object nodeData, int i, string iconKey, bool isDefaultIcon = false) { return nodeData.CreateNode("[" + i + "] ", iconKey, isDefaultIcon); } static TreeNode[] InternalCreateNodes(IList list) { var result = new List<TreeNode>(); foreach(var o in list) result.Add(CreateNumberedNode(o, result.Count, "ListItem", true)); return result.ToArray(); } static TreeNode[] InternalCreateNodes(DictionaryEntry dictionaryEntry) { return new[] { dictionaryEntry.Key.CreateTaggedNode("key", "Key", true), dictionaryEntry.Value.CreateTaggedNode("value") }; } /// <summary> /// Gets the name of the icon. /// </summary> /// <param name="nodeData"> The node data. </param> /// <returns> </returns> static string GetIconKey(this object nodeData) { if(nodeData == null) return null; var ip = nodeData as IIconKeyProvider; if(ip != null) return ip.IconKey; if(nodeData is string) return "String"; if(nodeData is bool) return "Bool"; if(nodeData.GetType().IsPrimitive) return "Number"; if(nodeData is IDictionary) return "Dictionary"; if(nodeData is IList) return "List"; return null; } [NotNull] internal static string GetAdditionalInfo([CanBeNull] this object nodeData) { if(nodeData == null) return "<null>"; var additionalNodeInfoProvider = nodeData as IAdditionalNodeInfoProvider; if(additionalNodeInfoProvider != null) return additionalNodeInfoProvider.AdditionalNodeInfo; var attrs = nodeData.GetType().GetCustomAttributes(typeof(AdditionalNodeInfoAttribute), true); if(attrs.Length > 0) { var attr = (AdditionalNodeInfoAttribute) attrs[0]; return nodeData.GetType().GetProperty(attr.Property).GetValue(nodeData, null).ToString(); } var il = nodeData as IList; if(il != null) return il.GetType().PrettyName() + "[" + ((IList) nodeData).Count + "]"; var nameSpace = nodeData.GetType().Namespace; if(nameSpace != null && nameSpace.StartsWith("System")) return nodeData.ToString(); return ""; } static TreeNode[] InternalCreateNodes(object target) { var result = new List<TreeNode>(); result.AddRange(CreateFieldNodes(target)); result.AddRange(CreatePropertyNodes(target)); return result.ToArray(); } public static TreeNode[] CreateNodes(this object target) { if(target == null) return new TreeNode[0]; var xn = target as ITreeNodeSupport; if(xn != null) return xn.CreateNodes().ToArray(); return CreateAutomaticNodes(target); } public static TreeNode[] CreateAutomaticNodes(this object target) { var xl = target as IList; if(xl != null) return InternalCreateNodes(xl); var xd = target as IDictionary; if(xd != null) return InternalCreateNodes(xd); if(target is DictionaryEntry) return InternalCreateNodes((DictionaryEntry) target); return InternalCreateNodes(target); } static TreeNode[] CreatePropertyNodes(object nodeData) { return nodeData .GetType() .GetProperties(DefaultBindingFlags) .Select(propertyInfo => CreateTreeNode(nodeData, propertyInfo)) .Where(treeNode => treeNode != null) .ToArray(); } static TreeNode[] CreateFieldNodes(object nodeData) { return nodeData .GetType() .GetFieldInfos() .Select(fieldInfo => CreateTreeNode(nodeData, fieldInfo)) .Where(treeNode => treeNode != null) .ToArray(); } static BindingFlags DefaultBindingFlags { get { return BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy; } } static TreeNode CreateTreeNode(object nodeData, FieldInfo fieldInfo) { return CreateTreeNode(fieldInfo, () => Value(fieldInfo, nodeData)); } static TreeNode CreateTreeNode(object nodeData, PropertyInfo propertyInfo) { return CreateTreeNode(propertyInfo, () => Value(propertyInfo, nodeData)); } static object Value(FieldInfo fieldInfo, object nodeData) { return fieldInfo.GetValue(nodeData); } static object Value(PropertyInfo propertyInfo, object nodeData) { return propertyInfo.GetValue(nodeData, null); } static TreeNode CreateTreeNode(MemberInfo memberInfo, Func<object> getValue) { var attribute = memberInfo.GetAttribute<NodeAttribute>(true); if(attribute == null) return null; var value = CatchedEval(getValue); if(value == null) return null; var result = CreateNamedNode(value, memberInfo.Name, attribute.IconKey); if(memberInfo.GetAttribute<SmartNodeAttribute>(true) == null) return result; return SmartNodeAttribute.Process(result); } static object CatchedEval(Func<object> value) { try { return value(); } catch(Exception e) { return e; } } static void CreateNodeList(TreeNodeCollection nodes, object target) { var treeNodes = CreateNodes(target); //Tracer.FlaggedLine(treeNodes.Dump()); //Tracer.ConditionalBreak(treeNodes.Length == 20,""); nodes.Clear(); nodes.AddRange(treeNodes); } public static void Connect(this TreeView treeView, object target) { Connect(target, treeView); } public static void Connect(this object target, TreeView treeView) { CreateNodeList(treeView.Nodes, target); AddSubNodes(treeView.Nodes); treeView.BeforeExpand += BeforeExpand; } static void AddSubNodesAsync(TreeNodeCollection nodes) { lock(nodes) { var backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += ((sender, e) => AddSubNodes(nodes)); backgroundWorker.RunWorkerAsync(); } } static void AddSubNodes(TreeNodeCollection nodes) { foreach(TreeNode node in nodes) CreateNodeList(node); } internal static void CreateNodeList(this TreeNode node) { CreateNodeList(node.Nodes, node.Tag); } static void BeforeExpand(object sender, TreeViewCancelEventArgs e) { AddSubNodes(e.Node.Nodes); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using Tamir.SharpSsh.jsch; using Tamir.Streams; /* * SshShell.cs * * Copyright (c) 2006 Tamir Gal, http://www.tamirgal.com, All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * 3. The names of the authors may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHOR * *OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **/ namespace Tamir.SharpSsh { /// <summary> /// Summary description for SshShell. /// </summary> public class SshShell : SshBase { private Stream m_sshIO = null; private Regex m_expectPattern; private bool m_removeTerminalChars; private bool m_redirectToConsole; private Dictionary<int, string> m_localMappedPorts; private static string escapeCharsPattern; public static SshExec Clone(SshBase baseConnection) { var exec = new SshExec(baseConnection.Host, baseConnection.Username, baseConnection.Password); exec.Session = baseConnection.Session; return exec; } public SshShell(string host, string user, string password) : base(host, user, password) { Init(); } public SshShell(string host, string user) : base(host, user) { Init(); } protected void Init() { m_removeTerminalChars = false; m_redirectToConsole = false; m_localMappedPorts = new Dictionary<int, string>(); escapeCharsPattern = "\\[[0-9;?]*[^0-9;]"; ExpectPattern = ""; m_removeTerminalChars = false; } protected override void OnChannelReceived() { base.OnChannelReceived(); if (m_redirectToConsole) { SetStream(Console.OpenStandardInput(), Console.OpenStandardOutput()); } else { m_sshIO = GetStream(); } } protected override string ChannelType { get { return "shell"; } } public Stream IO { get { // if(m_sshIO == null) // { // m_sshIO = GetStream(); // } return m_sshIO; } } public IEnumerator<string> StreamASCII() { Channel chan = base.Channel; if (chan == null || chan.isConnected()) yield break; var numerator = StreamASCII(chan); while (numerator.MoveNext()) yield return numerator.Current; } public void WriteLine(string data) { Write(data + "\r"); } public void Write(string data) { Write(Encoding.Default.GetBytes(data)); } /// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream. </param> public virtual void Write(byte[] buffer) { Write(buffer, 0, buffer.Length); } /// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream. </param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream. </param> public virtual void Write(byte[] buffer, int offset, int count) { IO.Write(buffer, offset, count); IO.Flush(); } /// <summary> /// Creates a new I/O stream of communication with this SSH shell connection /// </summary> public Stream GetStream() { return new CombinedStream(m_channel.getInputStream(), m_channel.getOutputStream()); ; } public void SetStream(Stream inputStream, Stream outputStream) { m_channel.setInputStream(inputStream); m_channel.setOutputStream(outputStream); } public void SetStream(Stream s) { SetStream(s, s); } public void RedirectToConsole() { m_redirectToConsole = true; } public virtual bool ShellOpened { get { if (m_channel != null) { return !m_channel.isClosed(); } return false; } } public virtual bool ShellConnected { get { if (m_channel != null) { return m_channel.isConnected(); } return false; } } /// <summary> /// Gets or sets a value indicating wether this Steam sould remove the terminal emulation's escape sequence characters from the response String. /// </summary> public bool RemoveTerminalEmulationCharacters { get { return m_removeTerminalChars; } set { m_removeTerminalChars = value; } } /// <summary> /// A regular expression pattern string to match when reading the resonse using the ReadResponse() method. The default prompt value is "\n" which makes the ReadRespons() method return one line of response. /// </summary> public string ExpectPattern { get { return m_expectPattern.ToString(); } set { m_expectPattern = new Regex(value, RegexOptions.Singleline); } } /// <summary> /// Reads a response string from the SSH channel. This method will block until the pattern in the 'Prompt' property is matched in the response. /// </summary> /// <returns>A response string from the SSH server.</returns> public string Expect() { return Expect(m_expectPattern); } /// <summary> /// Reads a response string from the SSH channel. This method will block until the pattern in the 'Prompt' property is matched in the response. /// </summary> /// <returns>A response string from the SSH server.</returns> public string Expect(string pattern) { return Expect(new Regex(pattern, RegexOptions.Singleline)); } /// <summary> /// Reads a response string from the SSH channel. This method will block until the pattern in the 'Prompt' property is matched in the response. /// </summary> /// <returns>A response string from the SSH server.</returns> public string Expect(Regex pattern) { int readCount; StringBuilder resp = new StringBuilder(); byte[] buff = new byte[1024]; Match match; do { readCount = IO.Read(buff, 0, buff.Length); if (readCount == -1) break; string tmp = Encoding.Default.GetString(buff, 0, readCount); resp.Append(tmp, 0, readCount); string s = resp.ToString(); match = pattern.Match(s); } while (!match.Success); string result = resp.ToString(); if (RemoveTerminalEmulationCharacters) result = HandleTerminalChars(result); return result; } /// <summary> /// Reads a response string from the SSH channel. /// This method will continue producing results /// until the pattern in the 'Prompt' property is matched in the response. /// </summary> /// <returns>A response string from the SSH server.</returns> public IEnumerator<string> ExpectEx() { return ExpectEx(m_expectPattern); } /// <summary> /// Reads a response string from the SSH channel. /// This method will continue producing results until the regex (specified as a string) /// in the argument is matched in the response. /// </summary> /// <returns>A response string from the SSH server.</returns> public IEnumerator<string> ExpectEx(string pattern) { return ExpectEx(new Regex(pattern, RegexOptions.Singleline)); } /// <summary> /// Reads a response string from the SSH channel. /// This method will continue producing results until the pattern in the argument /// is matched in the response. /// </summary> /// <returns>A response string from the SSH server.</returns> public IEnumerator<string> ExpectEx(Regex pattern) { // int readCount; string result = String.Empty; var fn = StreamResults(IO); byte[] buff; // Match match; while((buff = fn()) != null) { string tmp = Encoding.ASCII.GetString(buff, 0, buff.Length); yield return RemoveTerminalEmulationCharacters ? HandleTerminalChars(tmp) : tmp; result = String.Concat(result, tmp); if(pattern.IsMatch(result)) break; } } /// <summary> /// Closes the SSH subsystem /// </summary> public override void Close() { foreach (int localPort in m_localMappedPorts.Keys) { m_session.delPortForwardingL(localPort); } base.Close(); } /// <summary> /// Sets up a Local Port Forward on the current session, using specific local port number. /// </summary> public void ForwardLocalPortToRemote(int localPort, string remoteHostName, int remotePort) { if (m_localMappedPorts.ContainsKey(remotePort)) throw new InvalidOperationException("Remote port number {0} already mapped!"); if (!this.Connected) throw new InvalidOperationException("Shell must be connected before port forwarding can be configured!"); m_session.setPortForwardingL(localPort, remoteHostName, remotePort); m_localMappedPorts.Add(localPort, remoteHostName); } /// <summary> /// Sets up a Local Port Forward on the current session, auto-selecting an appropriate local port number to listen on. /// </summary> /// <returns>The auto-assigned local port number.</returns> public int ForwardLocalPortToRemote(string remoteHostName, int remotePort) { System.Net.Sockets.TcpListener autoListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0); autoListener.Start(0); int autoAssignedPort = ((System.Net.IPEndPoint)autoListener.LocalEndpoint).Port; autoListener.Stop(); ForwardLocalPortToRemote(autoAssignedPort, remoteHostName, remotePort); return autoAssignedPort; } /// <summary> /// Removes escape sequence characters from the input string. /// </summary> public static string HandleTerminalChars(string str) { str = str.Replace("(B)0", ""); str = Regex.Replace(str, escapeCharsPattern, ""); str = str.Replace(((char) 15).ToString(), ""); str = Regex.Replace(str, ((char) 27) + "=*", ""); //str = Regex.Replace(str, "\\s*\r\n", "\r\n"); return str; } } }
/////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; /// /// ExcelMachineEditor.cs /// /// (c)2014 Kim, Hyoun Woo /// /////////////////////////////////////////////////////////////////////////////// using UnityEngine; /// <summary>Custom editor script class for excel file setting.</summary> [CustomEditor(typeof(ExcelMachine))] public class ExcelMachineEditor : BaseMachineEditor { private void OnEnable() { machine = target as ExcelMachine; if (machine != null) { if (string.IsNullOrEmpty(ExcelSettings.Instance.RuntimePath) == false) machine.RuntimeClassPath = ExcelSettings.Instance.RuntimePath; if (string.IsNullOrEmpty(ExcelSettings.Instance.EditorPath) == false) machine.EditorClassPath = ExcelSettings.Instance.EditorPath; } } public override void OnInspectorGUI() { ExcelMachine machine = target as ExcelMachine; GUIStyle headerStyle = GUIHelper.MakeHeader(); GUILayout.Label("Excel Settings:", headerStyle); GUILayout.BeginHorizontal(); GUILayout.Label("File:", GUILayout.Width(50)); string path = ""; if (string.IsNullOrEmpty(machine.excelFilePath)) path = Application.dataPath; else path = machine.excelFilePath; machine.excelFilePath = GUILayout.TextField(path, GUILayout.Width(250)); if (GUILayout.Button("...", GUILayout.Width(20))) { string folder = Path.GetDirectoryName(path); #if UNITY_EDITOR_WIN path = EditorUtility.OpenFilePanel("Open Excel file", folder, "excel files;*.xls;*.xlsx"); #else path = EditorUtility.OpenFilePanel("Open Excel file", folder, "xls"); #endif if (path.Length != 0) { machine.SpreadSheetName = Path.GetFileName(path); // the path should be relative not absolute one. int index = path.IndexOf("Assets"); machine.excelFilePath = path.Substring(index); machine.SheetNames = new ExcelQuery(path).GetSheetNames(); } } GUILayout.EndHorizontal(); // Failed to get sheet name so we just return not to make editor on going. if (machine.SheetNames.Length == 0) { EditorGUILayout.Separator(); EditorGUILayout.LabelField("Error: Failed to retrieve the specified excel file."); EditorGUILayout.LabelField("If the excel file is opened, close it then reopen it again."); return; } machine.SpreadSheetName = EditorGUILayout.TextField("Spreadsheet File: ", machine.SpreadSheetName); machine.CurrentSheetIndex = EditorGUILayout.Popup(machine.CurrentSheetIndex, machine.SheetNames); if (machine.SheetNames != null) machine.WorkSheetName = machine.SheetNames[machine.CurrentSheetIndex]; EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); if (machine.HasHeadColumn()) { if (GUILayout.Button("Update")) Import(); if (GUILayout.Button("Reimport")) Import(true); } else { if (GUILayout.Button("Import")) Import(); } GUILayout.EndHorizontal(); EditorGUILayout.Separator(); DrawHeaderSetting(machine); EditorGUILayout.Separator(); GUILayout.Label("Path Settings:", headerStyle); machine.TemplatePath = EditorGUILayout.TextField("Template: ", machine.TemplatePath); machine.RuntimeClassPath = EditorGUILayout.TextField("Runtime: ", machine.RuntimeClassPath); machine.EditorClassPath = EditorGUILayout.TextField("Editor:", machine.EditorClassPath); //machine.DataFilePath = EditorGUILayout.TextField("Data:", machine.DataFilePath); machine.onlyCreateDataClass = EditorGUILayout.Toggle("Only DataClass", machine.onlyCreateDataClass); EditorGUILayout.Separator(); if (GUILayout.Button("Generate")) { ScriptPrescription sp = Generate(machine); if (sp != null) { Debug.Log("Successfully generated!"); } else Debug.LogError("Failed to create a script from excel."); } if (GUI.changed) { EditorUtility.SetDirty(machine); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } } /// <summary>Import the specified excel file and prepare to set type of each cell.</summary> protected override void Import(bool reimport = false) { base.Import(reimport); ExcelMachine machine = target as ExcelMachine; string path = machine.excelFilePath; string sheet = machine.WorkSheetName; if (string.IsNullOrEmpty(path)) { EditorUtility.DisplayDialog( "Error", "You should specify spreadsheet file first!", "OK" ); return; } if (!File.Exists(path)) { EditorUtility.DisplayDialog( "Error", "File at " + path + " does not exist.", "OK" ); return; } var titles = new ExcelQuery(path, sheet).GetTitle(); List<string> titleList = titles.ToList(); if (machine.HasHeadColumn() && reimport == false) { var headerDic = machine.HeaderColumnList.ToDictionary(header => header.name); // collect non changed header columns var exist = from t in titleList where headerDic.ContainsKey(t) == true select new HeaderColumn { name = t, type = headerDic[t].type, OrderNO = headerDic[t].OrderNO }; // collect newly added or changed header columns var changed = from t in titleList where headerDic.ContainsKey(t) == false select new HeaderColumn { name = t, type = CellType.Undefined, OrderNO = titleList.IndexOf(t) }; // merge two var merged = exist.Union(changed).OrderBy(x => x.OrderNO); machine.HeaderColumnList.Clear(); machine.HeaderColumnList = merged.ToList(); } else { machine.HeaderColumnList.Clear(); if (titles != null) { int i = 0; foreach (string s in titles) { machine.HeaderColumnList.Add(new HeaderColumn { name = s, type = CellType.Undefined, OrderNO = i }); i++; } } else { Debug.LogWarning("The WorkSheet [" + sheet + "] may be empty."); } } EditorUtility.SetDirty(machine); AssetDatabase.SaveAssets(); } /// <summary>Generate AssetPostprocessor editor script file.</summary> protected override void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp) { ExcelMachine machine = target as ExcelMachine; sp.className = machine.WorkSheetName; sp.dataClassName = machine.WorkSheetName + "Data"; sp.worksheetClassName = machine.WorkSheetName; // where the imported excel file is. sp.importedFilePath = machine.excelFilePath; // path where the .asset file will be created. string path = Path.GetDirectoryName(machine.excelFilePath); path += "/" + machine.WorkSheetName + ".asset"; sp.assetFilepath = path; sp.assetPostprocessorClass = machine.WorkSheetName + "AssetPostprocessor"; sp.template = GetTemplate("PostProcessor"); // write a script to the given folder. using (var writer = new StreamWriter(TargetPathForAssetPostProcessorFile(machine.WorkSheetName))) { writer.Write(new NewScriptGenerator(sp).ToString()); writer.Close(); } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. 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.Runtime.InteropServices; namespace OpenTK { /// <summary>Represents a 2D vector using two double-precision floating-point numbers.</summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector2d : IEquatable<Vector2d> { #region Fields /// <summary>The X coordinate of this instance.</summary> public double X; /// <summary>The Y coordinate of this instance.</summary> public double Y; /// <summary> /// Defines a unit-length Vector2d that points towards the X-axis. /// </summary> public static Vector2d UnitX = new Vector2d(1, 0); /// <summary> /// Defines a unit-length Vector2d that points towards the Y-axis. /// </summary> public static Vector2d UnitY = new Vector2d(0, 1); /// <summary> /// Defines a zero-length Vector2d. /// </summary> public static Vector2d Zero = new Vector2d(0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector2d One = new Vector2d(1, 1); /// <summary> /// Defines the size of the Vector2d struct in bytes. /// </summary> public static readonly int SizeInBytes = Marshal.SizeOf(new Vector2d()); #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector2d(double value) { X = value; Y = value; } /// <summary>Constructs left vector with the given coordinates.</summary> /// <param name="x">The X coordinate.</param> /// <param name="y">The Y coordinate.</param> public Vector2d(double x, double y) { this.X = x; this.Y = y; } #endregion #region Public Members #region Instance #region public void Add() /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Add() method instead.")] public void Add(Vector2d right) { this.X += right.X; this.Y += right.Y; } /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Add() method instead.")] public void Add(ref Vector2d right) { this.X += right.X; this.Y += right.Y; } #endregion public void Add() #region public void Sub() /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Subtract() method instead.")] public void Sub(Vector2d right) { this.X -= right.X; this.Y -= right.Y; } /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Subtract() method instead.")] public void Sub(ref Vector2d right) { this.X -= right.X; this.Y -= right.Y; } #endregion public void Sub() #region public void Mult() /// <summary>Multiply this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Multiply() method instead.")] public void Mult(double f) { this.X *= f; this.Y *= f; } #endregion public void Mult() #region public void Div() /// <summary>Divide this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Divide() method instead.")] public void Div(double f) { double mult = 1.0 / f; this.X *= mult; this.Y *= mult; } #endregion public void Div() #region public double Length /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <seealso cref="LengthSquared"/> public double Length { get { return System.Math.Sqrt(X * X + Y * Y); } } #endregion #region public double LengthSquared /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> public double LengthSquared { get { return X * X + Y * Y; } } #endregion #region public Vector2d PerpendicularRight /// <summary> /// Gets the perpendicular vector on the right side of this vector. /// </summary> public Vector2d PerpendicularRight { get { return new Vector2d(Y, -X); } } #endregion #region public Vector2d PerpendicularLeft /// <summary> /// Gets the perpendicular vector on the left side of this vector. /// </summary> public Vector2d PerpendicularLeft { get { return new Vector2d(-Y, X); } } #endregion #region public void Normalize() /// <summary> /// Scales the Vector2 to unit length. /// </summary> public void Normalize() { double scale = 1.0 / Length; X *= scale; Y *= scale; } #endregion #region public void Scale() /// <summary> /// Scales the current Vector2 by the given amounts. /// </summary> /// <param name="sx">The scale of the X component.</param> /// <param name="sy">The scale of the Y component.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(double sx, double sy) { X *= sx; Y *= sy; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(Vector2d scale) { this.X *= scale.X; this.Y *= scale.Y; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [CLSCompliant(false)] [Obsolete("Use static Multiply() method instead.")] public void Scale(ref Vector2d scale) { this.X *= scale.X; this.Y *= scale.Y; } #endregion public void Scale() #endregion #region Static #region Obsolete #region Sub /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> [Obsolete("Use static Subtract() method instead.")] public static Vector2d Sub(Vector2d a, Vector2d b) { a.X -= b.X; a.Y -= b.Y; return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> [Obsolete("Use static Subtract() method instead.")] public static void Sub(ref Vector2d a, ref Vector2d b, out Vector2d result) { result.X = a.X - b.X; result.Y = a.Y - b.Y; } #endregion #region Mult /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <returns>Result of the multiplication</returns> [Obsolete("Use static Multiply() method instead.")] public static Vector2d Mult(Vector2d a, double d) { a.X *= d; a.Y *= d; return a; } /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <param name="result">Result of the multiplication</param> [Obsolete("Use static Multiply() method instead.")] public static void Mult(ref Vector2d a, double d, out Vector2d result) { result.X = a.X * d; result.Y = a.Y * d; } #endregion #region Div /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <returns>Result of the division</returns> [Obsolete("Use static Divide() method instead.")] public static Vector2d Div(Vector2d a, double d) { double mult = 1.0 / d; a.X *= mult; a.Y *= mult; return a; } /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <param name="result">Result of the division</param> [Obsolete("Use static Divide() method instead.")] public static void Div(ref Vector2d a, double d, out Vector2d result) { double mult = 1.0 / d; result.X = a.X * mult; result.Y = a.Y * mult; } #endregion #endregion #region Add /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <returns>Result of operation.</returns> public static Vector2d Add(Vector2d a, Vector2d b) { Add(ref a, ref b, out a); return a; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector2d a, ref Vector2d b, out Vector2d result) { result = new Vector2d(a.X + b.X, a.Y + b.Y); } #endregion #region Subtract /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector2d Subtract(Vector2d a, Vector2d b) { Subtract(ref a, ref b, out a); return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector2d a, ref Vector2d b, out Vector2d result) { result = new Vector2d(a.X - b.X, a.Y - b.Y); } #endregion #region Multiply /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Multiply(Vector2d vector, double scale) { Multiply(ref vector, scale, out vector); return vector; } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2d vector, double scale, out Vector2d result) { result = new Vector2d(vector.X * scale, vector.Y * scale); } /// <summary> /// Multiplies a vector by the components a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Multiply(Vector2d vector, Vector2d scale) { Multiply(ref vector, ref scale, out vector); return vector; } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2d vector, ref Vector2d scale, out Vector2d result) { result = new Vector2d(vector.X * scale.X, vector.Y * scale.Y); } #endregion #region Divide /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Divide(Vector2d vector, double scale) { Divide(ref vector, scale, out vector); return vector; } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2d vector, double scale, out Vector2d result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divides a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Divide(Vector2d vector, Vector2d scale) { Divide(ref vector, ref scale, out vector); return vector; } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2d vector, ref Vector2d scale, out Vector2d result) { result = new Vector2d(vector.X / scale.X, vector.Y / scale.Y); } #endregion #region Min /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector2d Min(Vector2d a, Vector2d b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void Min(ref Vector2d a, ref Vector2d b, out Vector2d result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; } #endregion #region Max /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector2d Max(Vector2d a, Vector2d b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void Max(ref Vector2d a, ref Vector2d b, out Vector2d result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; } #endregion #region Clamp /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <returns>The clamped vector</returns> public static Vector2d Clamp(Vector2d vec, Vector2d min, Vector2d max) { vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; return vec; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <param name="result">The clamped vector</param> public static void Clamp(ref Vector2d vec, ref Vector2d min, ref Vector2d max, out Vector2d result) { result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; } #endregion #region Normalize /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector2d Normalize(Vector2d vec) { double scale = 1.0 / vec.Length; vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void Normalize(ref Vector2d vec, out Vector2d result) { double scale = 1.0 / vec.Length; result.X = vec.X * scale; result.Y = vec.Y * scale; } #endregion #region NormalizeFast /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector2d NormalizeFast(Vector2d vec) { double scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y); vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void NormalizeFast(ref Vector2d vec, out Vector2d result) { double scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y); result.X = vec.X * scale; result.Y = vec.Y * scale; } #endregion #region Dot /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static double Dot(Vector2d left, Vector2d right) { return left.X * right.X + left.Y * right.Y; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector2d left, ref Vector2d right, out double result) { result = left.X * right.X + left.Y * right.Y; } #endregion #region Lerp /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector2d Lerp(Vector2d a, Vector2d b, double blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector2d a, ref Vector2d b, double blend, out Vector2d result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; } #endregion #region Barycentric /// <summary> /// Interpolate 3 Vectors using Barycentric coordinates /// </summary> /// <param name="a">First input Vector</param> /// <param name="b">Second input Vector</param> /// <param name="c">Third input Vector</param> /// <param name="u">First Barycentric Coordinate</param> /// <param name="v">Second Barycentric Coordinate</param> /// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns> public static Vector2d BaryCentric(Vector2d a, Vector2d b, Vector2d c, double u, double v) { return a + u * (b - a) + v * (c - a); } /// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary> /// <param name="a">First input Vector.</param> /// <param name="b">Second input Vector.</param> /// <param name="c">Third input Vector.</param> /// <param name="u">First Barycentric Coordinate.</param> /// <param name="v">Second Barycentric Coordinate.</param> /// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param> public static void BaryCentric(ref Vector2d a, ref Vector2d b, ref Vector2d c, double u, double v, out Vector2d result) { result = a; // copy Vector2d temp = b; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, u, out temp); Add(ref result, ref temp, out result); temp = c; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, v, out temp); Add(ref result, ref temp, out result); } #endregion #region Transform /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector2d Transform(Vector2d vec, Quaterniond quat) { Vector2d result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector2d vec, ref Quaterniond quat, out Vector2d result) { Quaterniond v = new Quaterniond(vec.X, vec.Y, 0, 0), i, t; Quaterniond.Invert(ref quat, out i); Quaterniond.Multiply(ref quat, ref v, out t); Quaterniond.Multiply(ref t, ref i, out v); result = new Vector2d(v.X, v.Y); } #endregion #endregion #region Operators /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator +(Vector2d left, Vector2d right) { left.X += right.X; left.Y += right.Y; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator -(Vector2d left, Vector2d right) { left.X -= right.X; left.Y -= right.Y; return left; } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator -(Vector2d vec) { vec.X = -vec.X; vec.Y = -vec.Y; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="f">The scalar.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator *(Vector2d vec, double f) { vec.X *= f; vec.Y *= f; return vec; } /// <summary> /// Multiply an instance by a scalar. /// </summary> /// <param name="f">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator *(double f, Vector2d vec) { vec.X *= f; vec.Y *= f; return vec; } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="f">The scalar.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator /(Vector2d vec, double f) { double mult = 1.0 / f; vec.X *= mult; vec.Y *= mult; return vec; } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>True, if both instances are equal; false otherwise.</returns> public static bool operator ==(Vector2d left, Vector2d right) { return left.Equals(right); } /// <summary> /// Compares two instances for ienquality. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>True, if the instances are not equal; false otherwise.</returns> public static bool operator !=(Vector2d left, Vector2d right) { return !left.Equals(right); } /// <summary>Converts OpenTK.Vector2 to OpenTK.Vector2d.</summary> /// <param name="v2">The Vector2 to convert.</param> /// <returns>The resulting Vector2d.</returns> public static explicit operator Vector2d(Vector2 v2) { return new Vector2d(v2.X, v2.Y); } /// <summary>Converts OpenTK.Vector2d to OpenTK.Vector2.</summary> /// <param name="v2d">The Vector2d to convert.</param> /// <returns>The resulting Vector2.</returns> public static explicit operator Vector2(Vector2d v2d) { return new Vector2((float)v2d.X, (float)v2d.Y); } #endregion #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current instance. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("({0}, {1})", X, Y); } #endregion #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } #endregion #region public override bool Equals(object obj) /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector2d)) return false; return this.Equals((Vector2d)obj); } #endregion #endregion #endregion #region IEquatable<Vector2d> Members /// <summary>Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector2d other) { return X == other.X && Y == other.Y; } #endregion } }
// // Mono.Data.Sqlite.SQLiteFunction.cs // // Author(s): // Robert Simpson ([email protected]) // // Adapted and modified for the Mono Project by // Marek Habersack ([email protected]) // // // Copyright (C) 2006 Novell, Inc (http://www.novell.com) // Copyright (C) 2007 Marek Habersack // // 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. // /******************************************************** * ADO.NET 2.0 Data Provider for Sqlite Version 3.X * Written by Robert Simpson ([email protected]) * * Released to the public domain, use at your own risk! ********************************************************/ #if NET_2_0 namespace Mono.Data.Sqlite { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Globalization; /// <summary> /// The type of user-defined function to declare /// </summary> public enum FunctionType { /// <summary> /// Scalar functions are designed to be called and return a result immediately. Examples include ABS(), Upper(), Lower(), etc. /// </summary> Scalar = 0, /// <summary> /// Aggregate functions are designed to accumulate data until the end of a call and then return a result gleaned from the accumulated data. /// Examples include SUM(), COUNT(), AVG(), etc. /// </summary> Aggregate = 1, /// <summary> /// Collation sequences are used to sort textual data in a custom manner, and appear in an ORDER BY clause. Typically text in an ORDER BY is /// sorted using a straight case-insensitive comparison function. Custom collating sequences can be used to alter the behavior of text sorting /// in a user-defined manner. /// </summary> Collation = 2, } /// <summary> /// An internal callback delegate declaration. /// </summary> /// <param name="context">Raw context pointer for the user function</param> /// <param name="nArgs">Count of arguments to the function</param> /// <param name="argsptr">A pointer to the array of argument pointers</param> internal delegate void SqliteCallback(IntPtr context, int nArgs, IntPtr argsptr); /// <summary> /// An internal callback delegate declaration. /// </summary> /// <param name="context">Raw context pointer for the user function</param> internal delegate void SqliteFinalCallback(IntPtr context); /// <summary> /// Internal callback delegate for implementing collation sequences /// </summary> /// <param name="len1">Length of the string pv1</param> /// <param name="pv1">Pointer to the first string to compare</param> /// <param name="len2">Length of the string pv2</param> /// <param name="pv2">Pointer to the second string to compare</param> /// <returns>Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater /// than the second.</returns> internal delegate int SqliteCollation(int len1, IntPtr pv1, int len2, IntPtr pv2); /// <summary> /// This abstract class is designed to handle user-defined functions easily. An instance of the derived class is made for each /// connection to the database. /// </summary> /// <remarks> /// Although there is one instance of a class derived from SqliteFunction per database connection, the derived class has no access /// to the underlying connection. This is necessary to deter implementers from thinking it would be a good idea to make database /// calls during processing. /// /// It is important to distinguish between a per-connection instance, and a per-SQL statement context. One instance of this class /// services all SQL statements being stepped through on that connection, and there can be many. One should never store per-statement /// information in member variables of user-defined function classes. /// /// For aggregate functions, always create and store your per-statement data in the contextData object on the 1st step. This data will /// be automatically freed for you (and Dispose() called if the item supports IDisposable) when the statement completes. /// </remarks> public abstract class SqliteFunction : IDisposable { /// <summary> /// The base connection this function is attached to /// </summary> private SqliteBase _base; /// <summary> /// Internal array used to keep track of aggregate function context data /// </summary> private Dictionary<long, object> _contextDataList; /// <summary> /// Holds a reference to the callback function for user functions /// </summary> private SqliteCallback _InvokeFunc; /// <summary> /// Holds a reference to the callbakc function for stepping in an aggregate function /// </summary> private SqliteCallback _StepFunc; /// <summary> /// Holds a reference to the callback function for finalizing an aggregate function /// </summary> private SqliteFinalCallback _FinalFunc; /// <summary> /// Holds a reference to the callback function for collation sequences /// </summary> private SqliteCollation _CompareFunc; /// <summary> /// This static list contains all the user-defined functions declared using the proper attributes. /// </summary> private static List<SqliteFunctionAttribute> _registeredFunctions = new List<SqliteFunctionAttribute>(); /// <summary> /// Internal constructor, initializes the function's internal variables. /// </summary> protected SqliteFunction() { _contextDataList = new Dictionary<long, object>(); } /// <summary> /// Returns a reference to the underlying connection's SqliteConvert class, which can be used to convert /// strings and DateTime's into the current connection's encoding schema. /// </summary> public SqliteConvert SqliteConvert { get { return _base; } } /// <summary> /// Scalar functions override this method to do their magic. /// </summary> /// <remarks> /// Parameters passed to functions have only an affinity for a certain data type, there is no underlying schema available /// to force them into a certain type. Therefore the only types you will ever see as parameters are /// DBNull.Value, Int64, Double, String or byte[] array. /// </remarks> /// <param name="args">The arguments for the command to process</param> /// <returns>You may return most simple types as a return value, null or DBNull.Value to return null, DateTime, or /// you may return an Exception-derived class if you wish to return an error to Sqlite. Do not actually throw the error, /// just return it!</returns> public virtual object Invoke(object[] args) { return null; } /// <summary> /// Aggregate functions override this method to do their magic. /// </summary> /// <remarks> /// Typically you'll be updating whatever you've placed in the contextData field and returning as quickly as possible. /// </remarks> /// <param name="args">The arguments for the command to process</param> /// <param name="stepNumber">The 1-based step number. This is incrememted each time the step method is called.</param> /// <param name="contextData">A placeholder for implementers to store contextual data pertaining to the current context.</param> public virtual void Step(object[] args, int stepNumber, ref object contextData) { } /// <summary> /// Aggregate functions override this method to finish their aggregate processing. /// </summary> /// <remarks> /// If you implemented your aggregate function properly, /// you've been recording and keeping track of your data in the contextData object provided, and now at this stage you should have /// all the information you need in there to figure out what to return. /// NOTE: It is possible to arrive here without receiving a previous call to Step(), in which case the contextData will /// be null. This can happen when no rows were returned. You can either return null, or 0 or some other custom return value /// if that is the case. /// </remarks> /// <param name="contextData">Your own assigned contextData, provided for you so you can return your final results.</param> /// <returns>You may return most simple types as a return value, null or DBNull.Value to return null, DateTime, or /// you may return an Exception-derived class if you wish to return an error to Sqlite. Do not actually throw the error, /// just return it! /// </returns> public virtual object Final(object contextData) { return null; } /// <summary> /// User-defined collation sequences override this method to provide a custom string sorting algorithm. /// </summary> /// <param name="param1">The first string to compare</param> /// <param name="param2">The second strnig to compare</param> /// <returns>1 if param1 is greater than param2, 0 if they are equal, or -1 if param1 is less than param2</returns> public virtual int Compare(string param1, string param2) { return 0; } /// <summary> /// Converts an IntPtr array of context arguments to an object array containing the resolved parameters the pointers point to. /// </summary> /// <remarks> /// Parameters passed to functions have only an affinity for a certain data type, there is no underlying schema available /// to force them into a certain type. Therefore the only types you will ever see as parameters are /// DBNull.Value, Int64, Double, String or byte[] array. /// </remarks> /// <param name="nArgs">The number of arguments</param> /// <param name="argsptr">A pointer to the array of arguments</param> /// <returns>An object array of the arguments once they've been converted to .NET values</returns> internal object[] ConvertParams(int nArgs, IntPtr argsptr) { object[] parms = new object[nArgs]; #if !PLATFORM_COMPACTFRAMEWORK IntPtr[] argint = new IntPtr[nArgs]; #else int[] argint = new int[nArgs]; #endif Marshal.Copy(argsptr, argint, 0, nArgs); for (int n = 0; n < nArgs; n++) { switch (_base.GetParamValueType((IntPtr)argint[n])) { case TypeAffinity.Null: parms[n] = DBNull.Value; break; case TypeAffinity.Int64: parms[n] = _base.GetParamValueInt64((IntPtr)argint[n]); break; case TypeAffinity.Double: parms[n] = _base.GetParamValueDouble((IntPtr)argint[n]); break; case TypeAffinity.Text: parms[n] = _base.GetParamValueText((IntPtr)argint[n]); break; case TypeAffinity.Blob: { int x; byte[] blob; x = (int)_base.GetParamValueBytes((IntPtr)argint[n], 0, null, 0, 0); blob = new byte[x]; _base.GetParamValueBytes((IntPtr)argint[n], 0, blob, 0, x); parms[n] = blob; } break; case TypeAffinity.DateTime: // Never happens here but what the heck, maybe it will one day. parms[n] = _base.ToDateTime(_base.GetParamValueText((IntPtr)argint[n])); break; } } return parms; } /// <summary> /// Takes the return value from Invoke() and Final() and figures out how to return it to Sqlite's context. /// </summary> /// <param name="context">The context the return value applies to</param> /// <param name="returnValue">The parameter to return to Sqlite</param> void SetReturnValue(IntPtr context, object returnValue) { if (returnValue == null || returnValue == DBNull.Value) { _base.ReturnNull(context); return; } Type t = returnValue.GetType(); if (t == typeof(DateTime)) { _base.ReturnText(context, _base.ToString((DateTime)returnValue)); return; } else { Exception r = returnValue as Exception; if (r != null) { _base.ReturnError(context, r.Message); return; } } switch (SqliteConvert.TypeToAffinity(t)) { case TypeAffinity.Null: _base.ReturnNull(context); return; case TypeAffinity.Int64: _base.ReturnInt64(context, Convert.ToInt64(returnValue, CultureInfo.CurrentCulture)); return; case TypeAffinity.Double: _base.ReturnDouble(context, Convert.ToDouble(returnValue, CultureInfo.CurrentCulture)); return; case TypeAffinity.Text: _base.ReturnText(context, returnValue.ToString()); return; case TypeAffinity.Blob: _base.ReturnBlob(context, (byte[])returnValue); return; } } /// <summary> /// Internal scalar callback function, which wraps the raw context pointer and calls the virtual Invoke() method. /// </summary> /// <param name="context">A raw context pointer</param> /// <param name="nArgs">Number of arguments passed in</param> /// <param name="argsptr">A pointer to the array of arguments</param> internal void ScalarCallback(IntPtr context, int nArgs, IntPtr argsptr) { SetReturnValue(context, Invoke(ConvertParams(nArgs, argsptr))); } /// <summary> /// Internal collation sequence function, which wraps up the raw string pointers and executes the Compare() virtual function. /// </summary> /// <param name="len1">Length of the string pv1</param> /// <param name="ptr1">Pointer to the first string to compare</param> /// <param name="len2">Length of the string pv2</param> /// <param name="ptr2">Pointer to the second string to compare</param> /// <returns>Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater /// than the second.</returns> internal int CompareCallback(int len1, IntPtr ptr1, int len2, IntPtr ptr2) { return Compare(_base.ToString(ptr1), _base.ToString(ptr2)); } /// <summary> /// The internal aggregate Step function callback, which wraps the raw context pointer and calls the virtual Step() method. /// </summary> /// <remarks> /// This function takes care of doing the lookups and getting the important information put together to call the Step() function. /// That includes pulling out the user's contextData and updating it after the call is made. We use a sorted list for this so /// binary searches can be done to find the data. /// </remarks> /// <param name="context">A raw context pointer</param> /// <param name="nArgs">Number of arguments passed in</param> /// <param name="argsptr">A pointer to the array of arguments</param> internal void StepCallback(IntPtr context, int nArgs, IntPtr argsptr) { int n = _base.AggregateCount(context); long nAux; object obj = null; nAux = (long)_base.AggregateContext(context); if (n > 1) obj = _contextDataList[nAux]; Step(ConvertParams(nArgs, argsptr), n, ref obj); _contextDataList[nAux] = obj; } /// <summary> /// An internal aggregate Final function callback, which wraps the context pointer and calls the virtual Final() method. /// </summary> /// <param name="context">A raw context pointer</param> internal void FinalCallback(IntPtr context) { long n = (long)_base.AggregateContext(context); object obj = null; if (_contextDataList.ContainsKey(n)) { obj = _contextDataList[n]; _contextDataList.Remove(n); } SetReturnValue(context, Final(obj)); IDisposable disp = obj as IDisposable; if (disp != null) disp.Dispose(); } /// <summary> /// Placeholder for a user-defined disposal routine /// </summary> /// <param name="disposing">True if the object is being disposed explicitly</param> protected virtual void Dispose(bool disposing) { } /// <summary> /// Disposes of any active contextData variables that were not automatically cleaned up. Sometimes this can happen if /// someone closes the connection while a DataReader is open. /// </summary> public void Dispose() { Dispose(true); IDisposable disp; foreach (KeyValuePair<long, object> kv in _contextDataList) { disp = kv.Value as IDisposable; if (disp != null) disp.Dispose(); } _contextDataList.Clear(); _InvokeFunc = null; _StepFunc = null; _FinalFunc = null; _CompareFunc = null; _base = null; _contextDataList = null; GC.SuppressFinalize(this); } #if !PLATFORM_COMPACTFRAMEWORK /// <summary> /// Using reflection, enumerate all assemblies in the current appdomain looking for classes that /// have a SqliteFunctionAttribute attribute, and registering them accordingly. /// </summary> static SqliteFunction() { SqliteFunctionAttribute at; System.Reflection.Assembly[] arAssemblies = System.AppDomain.CurrentDomain.GetAssemblies(); int w = arAssemblies.Length; System.Reflection.AssemblyName sqlite = System.Reflection.Assembly.GetCallingAssembly().GetName(); for (int n = 0; n < w; n++) { Type[] arTypes; bool found = false; System.Reflection.AssemblyName[] references; try { // Inspect only assemblies that reference SQLite references = arAssemblies[n].GetReferencedAssemblies(); int t = references.Length; for (int z = 0; z < t; z++) { if (references[z].Name == sqlite.Name) { found = true; break; } } if (found == false) continue; arTypes = arAssemblies[n].GetTypes(); } catch (System.Reflection.ReflectionTypeLoadException e) { arTypes = e.Types; } int v = arTypes.Length; for (int x = 0; x < v; x++) { if (arTypes[x] == null) continue; object[] arAtt = arTypes[x].GetCustomAttributes(typeof(SqliteFunctionAttribute), false); int u = arAtt.Length; for (int y = 0; y < u; y++) { at = arAtt[y] as SqliteFunctionAttribute; if (at != null) { at._instanceType = arTypes[x]; _registeredFunctions.Add(at); } } } } } #else /// <summary> /// Manual method of registering a function. The type must still have the SqliteFunctionAttributes in order to work /// properly, but this is a workaround for the Compact Framework where enumerating assemblies is not currently supported. /// </summary> /// <param name="typ">The type of the function to register</param> public static void RegisterFunction(Type typ) { object[] arAtt = typ.GetCustomAttributes(typeof(SqliteFunctionAttribute), false); int u = arAtt.Length; SqliteFunctionAttribute at; for (int y = 0; y < u; y++) { at = arAtt[y] as SqliteFunctionAttribute; if (at != null) { at._instanceType = typ; _registeredFunctions.Add(at); } } } #endif /// <summary> /// Called by SqliteBase derived classes, this function binds all user-defined functions to a connection. /// It is done this way so that all user-defined functions will access the database using the same encoding scheme /// as the connection (UTF-8 or UTF-16). /// </summary> /// <param name="sqlbase">The base object on which the functions are to bind</param> /// <returns>Returns an array of functions which the connection object should retain until the connection is closed.</returns> internal static SqliteFunction[] BindFunctions(SqliteBase sqlbase) { SqliteFunction f; List<SqliteFunction> lFunctions = new List<SqliteFunction>(); foreach (SqliteFunctionAttribute pr in _registeredFunctions) { f = (SqliteFunction)Activator.CreateInstance(pr._instanceType); f._base = sqlbase; f._InvokeFunc = (pr.FuncType == FunctionType.Scalar) ? new SqliteCallback(f.ScalarCallback) : null; f._StepFunc = (pr.FuncType == FunctionType.Aggregate) ? new SqliteCallback(f.StepCallback) : null; f._FinalFunc = (pr.FuncType == FunctionType.Aggregate) ? new SqliteFinalCallback(f.FinalCallback) : null; f._CompareFunc = (pr.FuncType == FunctionType.Collation) ? new SqliteCollation(f.CompareCallback) : null; if (pr.FuncType != FunctionType.Collation) sqlbase.CreateFunction(pr.Name, pr.Arguments, f._InvokeFunc, f._StepFunc, f._FinalFunc); else sqlbase.CreateCollation(pr.Name, f._CompareFunc); lFunctions.Add(f); } SqliteFunction[] arFunctions = new SqliteFunction[lFunctions.Count]; lFunctions.CopyTo(arFunctions, 0); return arFunctions; } } } #endif
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: [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 = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// GroupInformation /// </summary> [DataContract] public partial class GroupInformation : IEquatable<GroupInformation>, IValidatableObject { public GroupInformation() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="GroupInformation" /> class. /// </summary> /// <param name="EndPosition">The last position in the result set. .</param> /// <param name="Groups">A collection group objects containing information about the groups returned..</param> /// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param> /// <param name="PreviousUri">The postal code for the billing address..</param> /// <param name="ResultSetSize">The number of results returned in this response. .</param> /// <param name="StartPosition">Starting position of the current result set..</param> /// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param> public GroupInformation(string EndPosition = default(string), List<Group> Groups = default(List<Group>), string NextUri = default(string), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalSetSize = default(string)) { this.EndPosition = EndPosition; this.Groups = Groups; this.NextUri = NextUri; this.PreviousUri = PreviousUri; this.ResultSetSize = ResultSetSize; this.StartPosition = StartPosition; this.TotalSetSize = TotalSetSize; } /// <summary> /// The last position in the result set. /// </summary> /// <value>The last position in the result set. </value> [DataMember(Name="endPosition", EmitDefaultValue=false)] public string EndPosition { get; set; } /// <summary> /// A collection group objects containing information about the groups returned. /// </summary> /// <value>A collection group objects containing information about the groups returned.</value> [DataMember(Name="groups", EmitDefaultValue=false)] public List<Group> Groups { get; set; } /// <summary> /// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. /// </summary> /// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value> [DataMember(Name="nextUri", EmitDefaultValue=false)] public string NextUri { get; set; } /// <summary> /// The postal code for the billing address. /// </summary> /// <value>The postal code for the billing address.</value> [DataMember(Name="previousUri", EmitDefaultValue=false)] public string PreviousUri { get; set; } /// <summary> /// The number of results returned in this response. /// </summary> /// <value>The number of results returned in this response. </value> [DataMember(Name="resultSetSize", EmitDefaultValue=false)] public string ResultSetSize { get; set; } /// <summary> /// Starting position of the current result set. /// </summary> /// <value>Starting position of the current result set.</value> [DataMember(Name="startPosition", EmitDefaultValue=false)] public string StartPosition { get; set; } /// <summary> /// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response. /// </summary> /// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value> [DataMember(Name="totalSetSize", EmitDefaultValue=false)] public string TotalSetSize { 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 GroupInformation {\n"); sb.Append(" EndPosition: ").Append(EndPosition).Append("\n"); sb.Append(" Groups: ").Append(Groups).Append("\n"); sb.Append(" NextUri: ").Append(NextUri).Append("\n"); sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n"); sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n"); sb.Append(" StartPosition: ").Append(StartPosition).Append("\n"); sb.Append(" TotalSetSize: ").Append(TotalSetSize).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 GroupInformation); } /// <summary> /// Returns true if GroupInformation instances are equal /// </summary> /// <param name="other">Instance of GroupInformation to be compared</param> /// <returns>Boolean</returns> public bool Equals(GroupInformation other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.EndPosition == other.EndPosition || this.EndPosition != null && this.EndPosition.Equals(other.EndPosition) ) && ( this.Groups == other.Groups || this.Groups != null && this.Groups.SequenceEqual(other.Groups) ) && ( this.NextUri == other.NextUri || this.NextUri != null && this.NextUri.Equals(other.NextUri) ) && ( this.PreviousUri == other.PreviousUri || this.PreviousUri != null && this.PreviousUri.Equals(other.PreviousUri) ) && ( this.ResultSetSize == other.ResultSetSize || this.ResultSetSize != null && this.ResultSetSize.Equals(other.ResultSetSize) ) && ( this.StartPosition == other.StartPosition || this.StartPosition != null && this.StartPosition.Equals(other.StartPosition) ) && ( this.TotalSetSize == other.TotalSetSize || this.TotalSetSize != null && this.TotalSetSize.Equals(other.TotalSetSize) ); } /// <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.EndPosition != null) hash = hash * 59 + this.EndPosition.GetHashCode(); if (this.Groups != null) hash = hash * 59 + this.Groups.GetHashCode(); if (this.NextUri != null) hash = hash * 59 + this.NextUri.GetHashCode(); if (this.PreviousUri != null) hash = hash * 59 + this.PreviousUri.GetHashCode(); if (this.ResultSetSize != null) hash = hash * 59 + this.ResultSetSize.GetHashCode(); if (this.StartPosition != null) hash = hash * 59 + this.StartPosition.GetHashCode(); if (this.TotalSetSize != null) hash = hash * 59 + this.TotalSetSize.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.Rule { #region Namesapces using System; using System.ComponentModel.Composition; using ODataValidator.RuleEngine; using ODataValidator.RuleEngine.Common; #endregion /// <summary> /// Base Class of extension rule to check payload if of supported type. /// </summary> public abstract class CommonCore2000: ExtensionRule { /// <summary> /// Gets rule name /// </summary> public override string Name { get { return "Common.Core.2000"; } } /// <summary> /// Gets Category property /// </summary> public override string Category { get { return "core"; } } /// <summary> /// Gets rule description /// </summary> public override string Description { get { return "Uri for validation must point to a valid OData Service document, Metadata document, Feed, or Entry."; } } /// <summary> /// Gets rule specification in OData document /// </summary> public override string SpecificationSection { get { return null; } } /// <summary> /// Gets location of help information of the rule /// </summary> public override string HelpLink { get { return null; } } /// <summary> /// Gets the error message for validation failure /// </summary> public override string ErrorMessage { get { return "Uri for validation must point to a valid OData Service document, Metadata document, Feed, or Entry."; } } /// <summary> /// Gets the requirement level. /// </summary> public override RequirementLevel RequirementLevel { get { return RequirementLevel.Must; } } /// <summary> /// Gets the flag of rule applying to offline context /// </summary> public override bool? IsOfflineContext { get { return null; // it applies to both live context and offline context, not like most code rules. } } /// <summary> /// Verifies the semantic rule /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool passed = false; info = null; switch (context.PayloadType) { case RuleEngine.PayloadType.ServiceDoc: case RuleEngine.PayloadType.Metadata: case RuleEngine.PayloadType.Entry: case RuleEngine.PayloadType.Feed: passed = true; break; default: info = new ExtensionRuleViolationInfo(Resource.NotSupportedPayloadType, context.Destination, context.ResponsePayload); break; } return passed; } } /// <summary> /// Class of extension rule to check payload if of supported type. /// </summary> [Export(typeof(ExtensionRule))] public class CommonCore2000_Other : CommonCore2000 { /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Other; } } } /// <summary> /// Class of extension rule to check payload if of supported type. /// </summary> [Export(typeof(ExtensionRule))] public class CommonCore2000_None : CommonCore2000 { /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.None; } } } /// <summary> /// Class of extension rule to check payload if of supported type. /// </summary> [Export(typeof(ExtensionRule))] public class CommonCore2000_ServiceDoc : CommonCore2000 { /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.ServiceDoc; } } } /// <summary> /// Class of extension rule to check payload if of supported type. /// </summary> [Export(typeof(ExtensionRule))] public class CommonCore2000_Metadata : CommonCore2000 { /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Metadata; } } } /// <summary> /// Class of extension rule to check payload if of supported type. /// </summary> [Export(typeof(ExtensionRule))] public class CommonCore2000_Feed : CommonCore2000 { /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Feed; } } } /// <summary> /// Class of extension rule to check payload if of supported type. /// </summary> [Export(typeof(ExtensionRule))] public class CommonCore2000_Entry : CommonCore2000 { /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Entry; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Globalization; using System.Collections.Generic; using System.Configuration.Assemblies; using System.Runtime.Serialization; using System.Security; namespace System.Reflection { public abstract partial class Assembly : ICustomAttributeProvider, ISerializable { protected Assembly() { } public virtual IEnumerable<TypeInfo> DefinedTypes { get { Type[] types = GetTypes(); TypeInfo[] typeinfos = new TypeInfo[types.Length]; for (int i = 0; i < types.Length; i++) { TypeInfo typeinfo = types[i].GetTypeInfo(); if (typeinfo == null) throw new NotSupportedException(SR.Format(SR.NotSupported_NoTypeInfo, types[i].FullName)); typeinfos[i] = typeinfo; } return typeinfos; } } public virtual Type[] GetTypes() { Module[] m = GetModules(false); int finalLength = 0; Type[][] moduleTypes = new Type[m.Length][]; for (int i = 0; i < moduleTypes.Length; i++) { moduleTypes[i] = m[i].GetTypes(); finalLength += moduleTypes[i].Length; } int current = 0; Type[] ret = new Type[finalLength]; for (int i = 0; i < moduleTypes.Length; i++) { int length = moduleTypes[i].Length; Array.Copy(moduleTypes[i], 0, ret, current, length); current += length; } return ret; } public virtual IEnumerable<Type> ExportedTypes => GetExportedTypes(); public virtual Type[] GetExportedTypes() { throw NotImplemented.ByDesign; } public virtual Type[] GetForwardedTypes() { throw NotImplemented.ByDesign; } public virtual string CodeBase { get { throw NotImplemented.ByDesign; } } public virtual MethodInfo EntryPoint { get { throw NotImplemented.ByDesign; } } public virtual string FullName { get { throw NotImplemented.ByDesign; } } public virtual string ImageRuntimeVersion { get { throw NotImplemented.ByDesign; } } public virtual bool IsDynamic => false; public virtual string Location { get { throw NotImplemented.ByDesign; } } public virtual bool ReflectionOnly { get { throw NotImplemented.ByDesign; } } public virtual ManifestResourceInfo GetManifestResourceInfo(string resourceName) { throw NotImplemented.ByDesign; } public virtual string[] GetManifestResourceNames() { throw NotImplemented.ByDesign; } public virtual Stream GetManifestResourceStream(string name) { throw NotImplemented.ByDesign; } public virtual Stream GetManifestResourceStream(Type type, string name) { throw NotImplemented.ByDesign; } public bool IsFullyTrusted => true; public virtual AssemblyName GetName() => GetName(copiedName: false); public virtual AssemblyName GetName(bool copiedName) { throw NotImplemented.ByDesign; } public virtual Type GetType(string name) => GetType(name, throwOnError: false, ignoreCase: false); public virtual Type GetType(string name, bool throwOnError) => GetType(name, throwOnError: throwOnError, ignoreCase: false); public virtual Type GetType(string name, bool throwOnError, bool ignoreCase) { throw NotImplemented.ByDesign; } public virtual bool IsDefined(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; } public virtual IEnumerable<CustomAttributeData> CustomAttributes => GetCustomAttributesData(); public virtual IList<CustomAttributeData> GetCustomAttributesData() { throw NotImplemented.ByDesign; } public virtual object[] GetCustomAttributes(bool inherit) { throw NotImplemented.ByDesign; } public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; } public virtual string EscapedCodeBase => AssemblyName.EscapeCodeBase(CodeBase); public object CreateInstance(string typeName) => CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null); public object CreateInstance(string typeName, bool ignoreCase) => CreateInstance(typeName, ignoreCase, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null); public virtual object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) { Type t = GetType(typeName, throwOnError: false, ignoreCase: ignoreCase); if (t == null) return null; return Activator.CreateInstance(t, bindingAttr, binder, args, culture, activationAttributes); } public virtual event ModuleResolveEventHandler ModuleResolve { add { throw NotImplemented.ByDesign; } remove { throw NotImplemented.ByDesign; } } public virtual Module ManifestModule { get { throw NotImplemented.ByDesign; } } public virtual Module GetModule(string name) { throw NotImplemented.ByDesign; } public Module[] GetModules() => GetModules(getResourceModules: false); public virtual Module[] GetModules(bool getResourceModules) { throw NotImplemented.ByDesign; } public virtual IEnumerable<Module> Modules => GetLoadedModules(getResourceModules: true); public Module[] GetLoadedModules() => GetLoadedModules(getResourceModules: false); public virtual Module[] GetLoadedModules(bool getResourceModules) { throw NotImplemented.ByDesign; } public virtual AssemblyName[] GetReferencedAssemblies() { throw NotImplemented.ByDesign; } public virtual Assembly GetSatelliteAssembly(CultureInfo culture) { throw NotImplemented.ByDesign; } public virtual Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { throw NotImplemented.ByDesign; } public virtual FileStream GetFile(string name) { throw NotImplemented.ByDesign; } public virtual FileStream[] GetFiles() => GetFiles(getResourceModules: false); public virtual FileStream[] GetFiles(bool getResourceModules) { throw NotImplemented.ByDesign; } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw NotImplemented.ByDesign; } public override string ToString() { string displayName = FullName; if (displayName == null) return base.ToString(); else return displayName; } /* Returns true if the assembly was loaded from the global assembly cache. */ public virtual bool GlobalAssemblyCache { get { throw NotImplemented.ByDesign; } } public virtual long HostContext { get { throw NotImplemented.ByDesign; } } public override bool Equals(object o) => base.Equals(o); public override int GetHashCode() => base.GetHashCode(); public static bool operator ==(Assembly left, Assembly right) { if (object.ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null) return false; return left.Equals(right); } public static bool operator !=(Assembly left, Assembly right) { return !(left == right); } public static string CreateQualifiedName(string assemblyName, string typeName) => typeName + ", " + assemblyName; public static Assembly GetAssembly(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); Module m = type.Module; if (m == null) return null; else return m.Assembly; } public static Assembly Load(byte[] rawAssembly) => Load(rawAssembly, rawSymbolStore: null); [Obsolete("This method has been deprecated. Please use Assembly.Load() instead. https://go.microsoft.com/fwlink/?linkid=14202")] public static Assembly LoadWithPartialName(string partialName) { if (partialName == null) throw new ArgumentNullException(nameof(partialName)); return Load(partialName); } public static Assembly UnsafeLoadFrom(string assemblyFile) => LoadFrom(assemblyFile); public Module LoadModule(string moduleName, byte[] rawModule) => LoadModule(moduleName, rawModule, null); public virtual Module LoadModule(string moduleName, byte[] rawModule, byte[] rawSymbolStore) { throw NotImplemented.ByDesign; } public static Assembly ReflectionOnlyLoad(byte[] rawAssembly) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } public static Assembly ReflectionOnlyLoad(string assemblyString) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } public static Assembly ReflectionOnlyLoadFrom(string assemblyFile) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } public virtual SecurityRuleSet SecurityRuleSet => SecurityRuleSet.None; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// A certificate that can be installed on compute nodes and can be used to authenticate operations on a node. /// </summary> public partial class Certificate : ITransportObjectProvider<Models.CertificateAddParameter>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<Common.CertificateFormat?> CertificateFormatProperty; public readonly PropertyAccessor<string> DataProperty; public readonly PropertyAccessor<DeleteCertificateError> DeleteCertificateErrorProperty; public readonly PropertyAccessor<string> PasswordProperty; public readonly PropertyAccessor<Common.CertificateState?> PreviousStateProperty; public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty; public readonly PropertyAccessor<string> PublicDataProperty; public readonly PropertyAccessor<Common.CertificateState?> StateProperty; public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty; public readonly PropertyAccessor<string> ThumbprintProperty; public readonly PropertyAccessor<string> ThumbprintAlgorithmProperty; public readonly PropertyAccessor<string> UrlProperty; public PropertyContainer() : base(BindingState.Unbound) { this.CertificateFormatProperty = this.CreatePropertyAccessor<Common.CertificateFormat?>(nameof(CertificateFormat), BindingAccess.Read | BindingAccess.Write); this.DataProperty = this.CreatePropertyAccessor<string>(nameof(Data), BindingAccess.Read | BindingAccess.Write); this.DeleteCertificateErrorProperty = this.CreatePropertyAccessor<DeleteCertificateError>(nameof(DeleteCertificateError), BindingAccess.None); this.PasswordProperty = this.CreatePropertyAccessor<string>(nameof(Password), BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor<Common.CertificateState?>(nameof(PreviousState), BindingAccess.None); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(PreviousStateTransitionTime), BindingAccess.None); this.PublicDataProperty = this.CreatePropertyAccessor<string>(nameof(PublicData), BindingAccess.None); this.StateProperty = this.CreatePropertyAccessor<Common.CertificateState?>(nameof(State), BindingAccess.None); this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None); this.ThumbprintProperty = this.CreatePropertyAccessor<string>(nameof(Thumbprint), BindingAccess.Read | BindingAccess.Write); this.ThumbprintAlgorithmProperty = this.CreatePropertyAccessor<string>(nameof(ThumbprintAlgorithm), BindingAccess.Read | BindingAccess.Write); this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None); } public PropertyContainer(Models.Certificate protocolObject) : base(BindingState.Bound) { this.CertificateFormatProperty = this.CreatePropertyAccessor<Common.CertificateFormat?>( nameof(CertificateFormat), BindingAccess.None); this.DataProperty = this.CreatePropertyAccessor<string>( nameof(Data), BindingAccess.None); this.DeleteCertificateErrorProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.DeleteCertificateError, o => new DeleteCertificateError(o).Freeze()), nameof(DeleteCertificateError), BindingAccess.Read); this.PasswordProperty = this.CreatePropertyAccessor<string>( nameof(Password), BindingAccess.None); this.PreviousStateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.CertificateState, Common.CertificateState>(protocolObject.PreviousState), nameof(PreviousState), BindingAccess.Read); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.PreviousStateTransitionTime, nameof(PreviousStateTransitionTime), BindingAccess.Read); this.PublicDataProperty = this.CreatePropertyAccessor( protocolObject.PublicData, nameof(PublicData), BindingAccess.Read); this.StateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.CertificateState, Common.CertificateState>(protocolObject.State), nameof(State), BindingAccess.Read); this.StateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.StateTransitionTime, nameof(StateTransitionTime), BindingAccess.Read); this.ThumbprintProperty = this.CreatePropertyAccessor( protocolObject.Thumbprint, nameof(Thumbprint), BindingAccess.Read); this.ThumbprintAlgorithmProperty = this.CreatePropertyAccessor( protocolObject.ThumbprintAlgorithm, nameof(ThumbprintAlgorithm), BindingAccess.Read); this.UrlProperty = this.CreatePropertyAccessor( protocolObject.Url, nameof(Url), BindingAccess.Read); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Certificate"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> /// <param name='data'>The base64-encoded raw certificate data (contents of the .pfx or .cer file or data from which the <see cref="Certificate"/> /// was created).</param> /// <param name='thumbprint'>The thumbprint of the certificate. This is a sequence of up to 40 hex digits.</param> /// <param name='thumbprintAlgorithm'>The algorithm used to derive the thumbprint.</param> /// <param name='certificateFormat'>The format of the certificate data.</param> /// <param name='password'>The password to access the certificate private key.</param> internal Certificate( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors, string data, string thumbprint, string thumbprintAlgorithm, Common.CertificateFormat? certificateFormat = default(Common.CertificateFormat?), string password = default(string)) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; this.Data = data; this.Thumbprint = thumbprint; this.ThumbprintAlgorithm = thumbprintAlgorithm; this.CertificateFormat = certificateFormat; this.Password = password; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } internal Certificate( BatchClient parentBatchClient, Models.Certificate protocolObject, IEnumerable<BatchClientBehavior> baseBehaviors) { this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="Certificate"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region Certificate /// <summary> /// Gets the format of the certificate data. /// </summary> public Common.CertificateFormat? CertificateFormat { get { return this.propertyContainer.CertificateFormatProperty.Value; } private set { this.propertyContainer.CertificateFormatProperty.Value = value; } } /// <summary> /// Gets the base64-encoded raw certificate data (contents of the .pfx or .cer file or data from which the <see cref="Certificate"/> /// was created). /// </summary> /// <remarks> /// <para>This property is set when creating a new <see cref="Certificate"/>. It is not defined for certificates /// retrieved from the Batch service.</para> <para>The maximum size is 10 KB.</para> /// </remarks> public string Data { get { return this.propertyContainer.DataProperty.Value; } private set { this.propertyContainer.DataProperty.Value = value; } } /// <summary> /// Gets the error that occurred on the last attempt to delete this certificate. /// </summary> /// <remarks> /// This property is null unless the certificate is in the <see cref="Common.CertificateState.DeleteFailed"/> state. /// </remarks> public DeleteCertificateError DeleteCertificateError { get { return this.propertyContainer.DeleteCertificateErrorProperty.Value; } } /// <summary> /// Gets the password to access the certificate private key. /// </summary> /// <remarks> /// This property is set when creating a new <see cref="Certificate"/> from .pfx format data (see <see cref="CertificateOperations.CreateCertificateFromPfx(byte[], /// string)"/> and <see cref="CertificateOperations.CreateCertificateFromPfx(string, string)"/>). It is not defined /// for certificates retrieved from the Batch service. /// </remarks> public string Password { get { return this.propertyContainer.PasswordProperty.Value; } private set { this.propertyContainer.PasswordProperty.Value = value; } } /// <summary> /// Gets the previous state of the certificate. /// </summary> /// <remarks> /// If the certificate is in its initial <see cref="Common.CertificateState.Active"/> state, the PreviousState property /// is not defined. /// </remarks> public Common.CertificateState? PreviousState { get { return this.propertyContainer.PreviousStateProperty.Value; } } /// <summary> /// Gets the time at which the certificate entered its previous state. /// </summary> /// <remarks> /// If the certificate is in its initial <see cref="Common.CertificateState.Active"/> state, the PreviousStateTransitionTime /// property is not defined. /// </remarks> public DateTime? PreviousStateTransitionTime { get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; } } /// <summary> /// Gets the public part of the certificate as a string containing base-64 encoded .cer format data. /// </summary> public string PublicData { get { return this.propertyContainer.PublicDataProperty.Value; } } /// <summary> /// Gets the current state of the certificate. /// </summary> public Common.CertificateState? State { get { return this.propertyContainer.StateProperty.Value; } } /// <summary> /// Gets the time at which the certificate entered its current state. /// </summary> public DateTime? StateTransitionTime { get { return this.propertyContainer.StateTransitionTimeProperty.Value; } } /// <summary> /// Gets the thumbprint of the certificate. This is a sequence of up to 40 hex digits. /// </summary> public string Thumbprint { get { return this.propertyContainer.ThumbprintProperty.Value; } private set { this.propertyContainer.ThumbprintProperty.Value = value; } } /// <summary> /// Gets the algorithm used to derive the thumbprint. /// </summary> public string ThumbprintAlgorithm { get { return this.propertyContainer.ThumbprintAlgorithmProperty.Value; } private set { this.propertyContainer.ThumbprintAlgorithmProperty.Value = value; } } /// <summary> /// Gets the URL of the certificate. /// </summary> public string Url { get { return this.propertyContainer.UrlProperty.Value; } } #endregion // Certificate #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.CertificateAddParameter ITransportObjectProvider<Models.CertificateAddParameter>.GetTransportObject() { Models.CertificateAddParameter result = new Models.CertificateAddParameter() { CertificateFormat = UtilitiesInternal.MapNullableEnum<Common.CertificateFormat, Models.CertificateFormat>(this.CertificateFormat), Data = this.Data, Password = this.Password, Thumbprint = this.Thumbprint, ThumbprintAlgorithm = this.ThumbprintAlgorithm, }; return result; } #endregion // Internal/private methods } }
using System; using System.Diagnostics; namespace Lucene.Net.Store { using Lucene.Net.Support; using System.IO; using System.IO.MemoryMappedFiles; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Constants = Lucene.Net.Util.Constants; /// <summary> /// File-based <seealso cref="Directory"/> implementation that uses /// mmap for reading, and {@link /// FSDirectory.FSIndexOutput} for writing. /// /// <p><b>NOTE</b>: memory mapping uses up a portion of the /// virtual memory address space in your process equal to the /// size of the file being mapped. Before using this class, /// be sure your have plenty of virtual address space, e.g. by /// using a 64 bit JRE, or a 32 bit JRE with indexes that are /// guaranteed to fit within the address space. /// On 32 bit platforms also consult <seealso cref="#MMapDirectory(File, LockFactory, int)"/> /// if you have problems with mmap failing because of fragmented /// address space. If you get an OutOfMemoryException, it is recommended /// to reduce the chunk size, until it works. /// /// <p>Due to <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038"> /// this bug</a> in Sun's JRE, MMapDirectory's <seealso cref="IndexInput#close"/> /// is unable to close the underlying OS file handle. Only when GC /// finally collects the underlying objects, which could be quite /// some time later, will the file handle be closed. /// /// <p>this will consume additional transient disk usage: on Windows, /// attempts to delete or overwrite the files will result in an /// exception; on other platforms, which typically have a &quot;delete on /// last close&quot; semantics, while such operations will succeed, the bytes /// are still consuming space on disk. For many applications this /// limitation is not a problem (e.g. if you have plenty of disk space, /// and you don't rely on overwriting files on Windows) but it's still /// an important limitation to be aware of. /// /// <p>this class supplies the workaround mentioned in the bug report /// (see <seealso cref="#setUseUnmap"/>), which may fail on /// non-Sun JVMs. It forcefully unmaps the buffer on close by using /// an undocumented internal cleanup functionality. /// <seealso cref="#UNMAP_SUPPORTED"/> is <code>true</code>, if the workaround /// can be enabled (with no guarantees). /// <p> /// <b>NOTE:</b> Accessing this class either directly or /// indirectly from a thread while it's interrupted can close the /// underlying channel immediately if at the same time the thread is /// blocked on IO. The channel will remain closed and subsequent access /// to <seealso cref="MMapDirectory"/> will throw a <seealso cref="ClosedChannelException"/>. /// </p> /// </summary> public class MMapDirectory : FSDirectory { private bool UseUnmapHack = UNMAP_SUPPORTED; /// <summary> /// Default max chunk size. </summary> /// <seealso cref= #MMapDirectory(File, LockFactory, int) </seealso> public static readonly int DEFAULT_MAX_BUFF = Constants.JRE_IS_64BIT ? (1 << 30) : (1 << 28); internal readonly int ChunkSizePower; /// <summary> /// Create a new MMapDirectory for the named location. /// </summary> /// <param name="path"> the path of the directory </param> /// <param name="lockFactory"> the lock factory to use, or null for the default /// (<seealso cref="NativeFSLockFactory"/>); </param> /// <exception cref="System.IO.IOException"> if there is a low-level I/O error </exception> public MMapDirectory(DirectoryInfo path, LockFactory lockFactory) : this(path, lockFactory, DEFAULT_MAX_BUFF) { } /// <summary> /// Create a new MMapDirectory for the named location and <seealso cref="NativeFSLockFactory"/>. /// </summary> /// <param name="path"> the path of the directory </param> /// <exception cref="System.IO.IOException"> if there is a low-level I/O error </exception> public MMapDirectory(DirectoryInfo path) : this(path, null) { } /// <summary> /// Create a new MMapDirectory for the named location, specifying the /// maximum chunk size used for memory mapping. /// </summary> /// <param name="path"> the path of the directory </param> /// <param name="lockFactory"> the lock factory to use, or null for the default /// (<seealso cref="NativeFSLockFactory"/>); </param> /// <param name="maxChunkSize"> maximum chunk size (default is 1 GiBytes for /// 64 bit JVMs and 256 MiBytes for 32 bit JVMs) used for memory mapping. /// <p> /// Especially on 32 bit platform, the address space can be very fragmented, /// so large index files cannot be mapped. Using a lower chunk size makes /// the directory implementation a little bit slower (as the correct chunk /// may be resolved on lots of seeks) but the chance is higher that mmap /// does not fail. On 64 bit Java platforms, this parameter should always /// be {@code 1 << 30}, as the address space is big enough. /// <p> /// <b>Please note:</b> The chunk size is always rounded down to a power of 2. </param> /// <exception cref="System.IO.IOException"> if there is a low-level I/O error </exception> public MMapDirectory(DirectoryInfo path, LockFactory lockFactory, int maxChunkSize) : base(path, lockFactory) { if (maxChunkSize <= 0) { throw new System.ArgumentException("Maximum chunk size for mmap must be >0"); } this.ChunkSizePower = 31 - Number.NumberOfLeadingZeros(maxChunkSize); Debug.Assert(this.ChunkSizePower >= 0 && this.ChunkSizePower <= 30); } /// <summary> /// <code>true</code>, if this platform supports unmapping mmapped files. /// </summary> public static readonly bool UNMAP_SUPPORTED; /*static MMapDirectory() { bool v; try { Type.GetType("sun.misc.Cleaner"); Type.GetType("java.nio.DirectByteBuffer").GetMethod("cleaner"); v = true; } catch (Exception) { v = false; } UNMAP_SUPPORTED = v; }*/ /// <summary> /// this method enables the workaround for unmapping the buffers /// from address space after closing <seealso cref="IndexInput"/>, that is /// mentioned in the bug report. this hack may fail on non-Sun JVMs. /// It forcefully unmaps the buffer on close by using /// an undocumented internal cleanup functionality. /// <p><b>NOTE:</b> Enabling this is completely unsupported /// by Java and may lead to JVM crashes if <code>IndexInput</code> /// is closed while another thread is still accessing it (SIGSEGV). </summary> /// <exception cref="IllegalArgumentException"> if <seealso cref="#UNMAP_SUPPORTED"/> /// is <code>false</code> and the workaround cannot be enabled. </exception> public virtual bool UseUnmap { set { if (value && !UNMAP_SUPPORTED) { throw new System.ArgumentException("Unmap hack not supported on this platform!"); } this.UseUnmapHack = value; } get { return UseUnmapHack; } } /// <summary> /// Returns the current mmap chunk size. </summary> /// <seealso cref= #MMapDirectory(File, LockFactory, int) </seealso> public int MaxChunkSize { get { return 1 << ChunkSizePower; } } /// <summary> /// Creates an IndexInput for the file with the given name. </summary> public override IndexInput OpenInput(string name, IOContext context) { EnsureOpen(); var file = new FileInfo(Path.Combine(Directory.FullName, name)); var c = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); return new MMapIndexInput(this, "MMapIndexInput(path=\"" + file + "\")", c); } public override IndexInputSlicer CreateSlicer(string name, IOContext context) { var full = (MMapIndexInput)OpenInput(name, context); return new IndexInputSlicerAnonymousInnerClassHelper(this, full); } private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer { private readonly MMapDirectory OuterInstance; private MMapIndexInput Full; public IndexInputSlicerAnonymousInnerClassHelper(MMapDirectory outerInstance, MMapIndexInput full) : base(outerInstance) { this.OuterInstance = outerInstance; this.Full = full; } public override IndexInput OpenSlice(string sliceDescription, long offset, long length) { OuterInstance.EnsureOpen(); return Full.Slice(sliceDescription, offset, length); } public override IndexInput OpenFullSlice() { OuterInstance.EnsureOpen(); return (IndexInput)Full.Clone(); } public override void Dispose(bool disposing) { Full.Dispose(); } } public sealed class MMapIndexInput : ByteBufferIndexInput { internal readonly bool UseUnmapHack; internal MemoryMappedFile memoryMappedFile; // .NET port: this is equivalent to FileChannel.map internal MMapDirectory outerInstance; internal MMapIndexInput(MMapDirectory outerInstance, string resourceDescription, FileStream fc) : base(resourceDescription, null, fc.Length, outerInstance.ChunkSizePower, outerInstance.UseUnmap) { this.outerInstance = outerInstance; this.UseUnmapHack = outerInstance.UseUnmap; this.Buffers = outerInstance.Map(this, fc, 0, fc.Length); //Called here to let buffers get set up base.Seek(0L); } public override sealed void Dispose() { if (null != this.memoryMappedFile) { this.memoryMappedFile.Dispose(); this.memoryMappedFile = null; } base.Dispose(); } /// <summary> /// Try to unmap the buffer, this method silently fails if no support /// for that in the JVM. On Windows, this leads to the fact, /// that mmapped files cannot be modified or deleted. /// </summary> protected internal override void FreeBuffer(ByteBuffer buffer) { // .NET port: this should free the memory mapped view accessor var mmfbb = buffer as MemoryMappedFileByteBuffer; if (mmfbb != null) mmfbb.Dispose(); /* if (UseUnmapHack) { try { AccessController.doPrivileged(new PrivilegedExceptionActionAnonymousInnerClassHelper(this, buffer)); } catch (PrivilegedActionException e) { System.IO.IOException ioe = new System.IO.IOException("unable to unmap the mapped buffer"); ioe.initCause(e.InnerException); throw ioe; } }*/ } /* private class PrivilegedExceptionActionAnonymousInnerClassHelper : PrivilegedExceptionAction<Void> { private readonly MMapIndexInput OuterInstance; private ByteBuffer Buffer; public PrivilegedExceptionActionAnonymousInnerClassHelper(MMapIndexInput outerInstance, ByteBuffer buffer) { this.OuterInstance = outerInstance; this.Buffer = buffer; } public override void Run() { Method getCleanerMethod = Buffer.GetType().GetMethod("cleaner"); getCleanerMethod.Accessible = true; object cleaner = getCleanerMethod.invoke(Buffer); if (cleaner != null) { cleaner.GetType().GetMethod("clean").invoke(cleaner); } //return null; } }*/ } /// <summary> /// Maps a file into a set of buffers </summary> internal virtual ByteBuffer[] Map(MMapIndexInput input, FileStream fc, long offset, long length) { if (Number.URShift(length, ChunkSizePower) >= int.MaxValue) throw new ArgumentException("RandomAccessFile too big for chunk size: " + fc.ToString()); long chunkSize = 1L << ChunkSizePower; // we always allocate one more buffer, the last one may be a 0 byte one int nrBuffers = (int)((long)((ulong)length >> ChunkSizePower)) + 1; ByteBuffer[] buffers = new ByteBuffer[nrBuffers]; /* public static MemoryMappedFile CreateFromFile(FileStream fileStream, String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability, bool leaveOpen) */ if (input.memoryMappedFile == null) { input.memoryMappedFile = MemoryMappedFile.CreateFromFile(fc, null, length == 0 ? 100 : length, MemoryMappedFileAccess.Read, null, HandleInheritability.Inheritable, false); } long bufferStart = 0L; for (int bufNr = 0; bufNr < nrBuffers; bufNr++) { int bufSize = (int)((length > (bufferStart + chunkSize)) ? chunkSize : (length - bufferStart)); //LUCENE TO-DO buffers[bufNr] = new MemoryMappedFileByteBuffer(input.memoryMappedFile.CreateViewAccessor(offset + bufferStart, bufSize, MemoryMappedFileAccess.Read), -1, 0, bufSize, bufSize); //buffers[bufNr] = fc.Map(FileStream.MapMode.READ_ONLY, offset + bufferStart, bufSize); bufferStart += bufSize; } return buffers; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Django.Analysis; using Microsoft.PythonTools.Django.Project; using Microsoft.PythonTools.Django.TemplateParsing; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.Text; namespace DjangoTests { [TestClass] public class DjangoTemplateParserTests { #region Filter parser tests [TestMethod, Priority(1)] public void FilterRegexTests() { var testCases = new[] { new { Got = ("100"), Expected = DjangoVariable.Number("100", 0) }, new { Got = ("100.0"), Expected = DjangoVariable.Number("100.0", 0) }, new { Got = ("+100"), Expected = DjangoVariable.Number("+100", 0) }, new { Got = ("-100"), Expected = DjangoVariable.Number("-100", 0) }, new { Got = ("'fob'"), Expected = DjangoVariable.Constant("'fob'", 0) }, new { Got = ("\"fob\""), Expected = DjangoVariable.Constant("\"fob\"", 0) }, new { Got = ("fob"), Expected = DjangoVariable.Variable("fob", 0) }, new { Got = ("fob.oar"), Expected = DjangoVariable.Variable("fob.oar", 0) }, new { Got = ("fob|oar"), Expected = DjangoVariable.Variable("fob", 0, new DjangoFilter("oar", 4)) }, new { Got = ("fob|oar|baz"), Expected = DjangoVariable.Variable("fob", 0, new DjangoFilter("oar", 4), new DjangoFilter("baz", 8)) }, new { Got = ("fob|oar:'fob'"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Constant("oar", 4, "'fob'", 8)) }, new { Got = ("fob|oar:42"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "42", 8)) }, new { Got = ("fob|oar:\"fob\""), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Constant("oar", 4, "\"fob\"", 8)) }, new { Got = ("fob|oar:100"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "100", 8)) }, new { Got = ("fob|oar:100.0"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "100.0", 8)) }, new { Got = ("fob|oar:+100.0"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "+100.0", 8)) }, new { Got = ("fob|oar:-100.0"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "-100.0", 8)) }, new { Got = ("fob|oar:baz.quox"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Variable("oar", 4, "baz.quox", 8)) }, new { Got = ("fob|oar:baz"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Variable("oar", 4, "baz", 8)) }, new { Got = ("{{ 100 }}"), Expected = DjangoVariable.Number("100", 3) }, new { Got = ("{{ 100.0 }}"), Expected = DjangoVariable.Number("100.0", 3) }, new { Got = ("{{ +100 }}"), Expected = DjangoVariable.Number("+100", 3) }, new { Got = ("{{ -100 }}"), Expected = DjangoVariable.Number("-100", 3) }, new { Got = ("{{ 'fob' }}"), Expected = DjangoVariable.Constant("'fob'", 3) }, new { Got = ("{{ \"fob\" }}"), Expected = DjangoVariable.Constant("\"fob\"", 3) }, new { Got = ("{{ fob }}"), Expected = DjangoVariable.Variable("fob", 3) }, new { Got = ("{{ fob.oar }}"), Expected = DjangoVariable.Variable("fob.oar", 3) }, new { Got = ("{{ fob|oar }}"), Expected = DjangoVariable.Variable("fob", 3, new DjangoFilter("oar", 7)) }, new { Got = ("{{ fob|oar|baz }}"), Expected = DjangoVariable.Variable("fob", 3, new DjangoFilter("oar", 7), new DjangoFilter("baz", 11)) }, new { Got = ("{{ fob|oar:'fob' }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Constant("oar", 7, "'fob'", 11)) }, new { Got = ("{{ fob|oar:42 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "42", 11)) }, new { Got = ("{{ fob|oar:\"fob\" }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Constant("oar", 7, "\"fob\"", 11)) }, new { Got = ("{{ fob|oar:100 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "100", 11)) }, new { Got = ("{{ fob|oar:100.0 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "100.0", 11)) }, new { Got = ("{{ fob|oar:+100.0 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "+100.0", 11)) }, new { Got = ("{{ fob|oar:-100.0 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "-100.0", 11)) }, new { Got = ("{{ fob|oar:baz.quox }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Variable("oar", 7, "baz.quox", 11)) }, new { Got = ("{{ fob|oar:baz }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Variable("oar", 7, "baz", 11)) }, }; foreach (var testCase in testCases) { Console.WriteLine(testCase.Got); var got = DjangoVariable.Parse(testCase.Got); ValidateFilter(testCase.Expected, got); } } internal void ValidateFilter(DjangoVariable got, DjangoVariable expected) { Assert.AreEqual(expected.Expression.Value, got.Expression.Value); Assert.AreEqual(expected.Expression.Kind, got.Expression.Kind); Assert.AreEqual(expected.ExpressionStart, got.ExpressionStart); Assert.AreEqual(expected.Filters.Length, got.Filters.Length); for (int i = 0; i < expected.Filters.Length; i++) { if (expected.Filters[i].Arg == null) { Assert.AreEqual(null, got.Filters[i].Arg); } else { Assert.AreEqual(expected.Filters[i].Arg.Value, got.Filters[i].Arg.Value); Assert.AreEqual(expected.Filters[i].Arg.Kind, got.Filters[i].Arg.Kind); Assert.AreEqual(expected.Filters[i].ArgStart, got.Filters[i].ArgStart); } Assert.AreEqual(expected.Filters[i].Filter, got.Filters[i].Filter); } } #endregion #region Block parser tests [TestMethod, Priority(1)] public void BlockParserTests() { var testCases = new[] { new { Got = ("for x in "), Expected = (DjangoBlock)new DjangoForBlock(new BlockParseInfo("for", "x in ", 0), 6, null, 9, -1, new[] { new Tuple<string, int>("x", 4) }), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 9, Expected = new[] { "fob", "oar" } }, new { Position = 4, Expected = new string[0] } } }, new { Got = ("for x in oar"), Expected = (DjangoBlock)new DjangoForBlock(new BlockParseInfo("for", "x in oar", 0), 6, DjangoVariable.Variable("oar", 9), 12, -1, new[] { new Tuple<string, int>("x", 4) }), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 9, Expected = new[] { "fob", "oar" } }, new { Position = 4, Expected = new string[0] } } }, new { Got = ("for x in b"), Expected = (DjangoBlock)new DjangoForBlock(new BlockParseInfo("for", "x in b", 0), 6, DjangoVariable.Variable("b", 9), 10, -1, new[] { new Tuple<string, int>("x", 4) }), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new [] { "fob", "oar" } }, new { Position = 4, Expected = new string[0] } } }, new { Got = ("autoescape"), Expected = (DjangoBlock)new DjangoAutoEscapeBlock(new BlockParseInfo("autoescape", "", 0), -1, -1), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new[] { "on", "off" } } } }, new { Got = ("autoescape on"), Expected = (DjangoBlock)new DjangoAutoEscapeBlock(new BlockParseInfo("autoescape", " on", 0), 11, 2), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new string[0] } } }, new { Got = ("comment"), Expected = (DjangoBlock)new DjangoArgumentlessBlock(new BlockParseInfo("comment", "", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 0, Expected = new string[0] } } }, new { Got = ("spaceless"), Expected = (DjangoBlock)new DjangoSpacelessBlock(new BlockParseInfo("spaceless", "", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 0, Expected = new string[0] } } }, new { Got = ("filter "), Expected = (DjangoBlock)new DjangoFilterBlock(new BlockParseInfo("filter", " ", 0), DjangoVariable.Variable("", 7)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 7, Expected = new [] { "cut", "lower" } } } }, new { Got = ("ifequal "), Expected = (DjangoBlock)new DjangoIfOrIfNotEqualBlock(new BlockParseInfo("ifequal", " ", 0), DjangoVariable.Variable("", 8)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 8, Expected = new [] { "fob", "oar" } } } }, new { Got = ("ifequal fob "), Expected = (DjangoBlock)new DjangoIfOrIfNotEqualBlock(new BlockParseInfo("ifequal", " fob ", 0), DjangoVariable.Variable("fob", 8)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 12, Expected = new [] { "fob", "oar" } } } }, new { Got = ("if "), Expected = (DjangoBlock)new DjangoIfBlock(new BlockParseInfo("if", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 3, Expected = new [] { "fob", "oar", "not" } } } }, new { Got = ("if fob "), Expected = (DjangoBlock)new DjangoIfBlock(new BlockParseInfo("if", " fob ", 0), new BlockClassification(new Span(3, 3), Classification.Identifier)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 7, Expected = new [] { "and", "or" } } } }, new { Got = ("if fob and "), Expected = (DjangoBlock)new DjangoIfBlock(new BlockParseInfo("if", " fob and ", 0), new BlockClassification(new Span(3, 3), Classification.Identifier), new BlockClassification(new Span(7, 3), Classification.Keyword)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 11, Expected = new [] { "fob", "oar", "not" } } } }, new { Got = ("firstof "), Expected = (DjangoBlock)new DjangoMultiVariableArgumentBlock(new BlockParseInfo("firstof", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 8, Expected = new [] { "fob", "oar" } } } }, new { Got = ("firstof fob|"), Expected = (DjangoBlock)new DjangoMultiVariableArgumentBlock(new BlockParseInfo("firstof", " fob|", 0), DjangoVariable.Variable("fob", 8)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 12, Expected = new [] { "cut", "lower" } } } }, new { Got = ("spaceless "), Expected = (DjangoBlock)new DjangoSpacelessBlock(new BlockParseInfo("spaceless", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new string[0] } } }, new { Got = ("widthratio "), Expected = (DjangoBlock)new DjangoWidthRatioBlock(new BlockParseInfo("widthratio", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 11, Expected = new [] { "fob", "oar" } } } }, new { Got = ("templatetag "), Expected = (DjangoBlock)new DjangoTemplateTagBlock(new BlockParseInfo("templatetag", " ", 0), 11, null), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 11, Expected = new [] { "openblock", "closeblock", "openvariable", "closevariable", "openbrace", "closebrace", "opencomment", "closecomment" } } } }, new { Got = ("templatetag open"), Expected = (DjangoBlock)new DjangoTemplateTagBlock(new BlockParseInfo("templatetag", " open", 0), 11, null), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 15, Expected = new [] { "openblock", "openvariable", "openbrace", "opencomment" } } } }, new { Got = ("templatetag openblock "), Expected = (DjangoBlock)new DjangoTemplateTagBlock(new BlockParseInfo("templatetag", " openblock ", 0), 11, "openblock"), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 22, Expected = new string[0] } } }, }; foreach (var testCase in testCases) { Console.WriteLine(testCase.Got); var got = DjangoBlock.Parse(testCase.Got); ValidateBlock(testCase.Expected, got); foreach (var completionCase in testCase.Completions) { var completions = new HashSet<string>(got.GetCompletions(testCase.Context, completionCase.Position).Select(x => x.DisplayText)); Assert.AreEqual(completionCase.Expected.Length, completions.Count); var expected = new HashSet<string>(completionCase.Expected); foreach (var value in completions) { Assert.IsTrue(expected.Contains(value)); } } } } private static Dictionary<Type, Action<DjangoBlock, DjangoBlock>> _blockValidators = MakeBlockValidators(); private static Dictionary<Type, Action<DjangoBlock, DjangoBlock>> MakeBlockValidators() { return new Dictionary<Type, Action<DjangoBlock, DjangoBlock>>() { { typeof(DjangoForBlock), ValidateForBlock }, { typeof(DjangoAutoEscapeBlock), ValidateAutoEscape }, { typeof(DjangoArgumentlessBlock), ValidateArgumentless }, { typeof(DjangoFilterBlock), ValidateFilter }, { typeof(DjangoIfOrIfNotEqualBlock), ValidateIfOrIfNotEqualBlock}, { typeof(DjangoIfBlock), ValidateIfBlock}, { typeof(DjangoMultiVariableArgumentBlock), ValidateMultiArgumentBlock}, { typeof(DjangoSpacelessBlock), ValidateSpacelessBlock}, { typeof(DjangoTemplateTagBlock), ValidateTemplateTagBlock }, { typeof(DjangoWidthRatioBlock), ValidateWidthRatioBlock } }; } private static void ValidateWidthRatioBlock(DjangoBlock expected, DjangoBlock got) { var withExpected = (DjangoWidthRatioBlock)expected; var withGot = (DjangoWidthRatioBlock)got; Assert.AreEqual(withExpected.ParseInfo.Start, withGot.ParseInfo.Start); Assert.AreEqual(withExpected.ParseInfo.Command, withGot.ParseInfo.Command); Assert.AreEqual(withExpected.ParseInfo.Args, withGot.ParseInfo.Args); } private static void ValidateTemplateTagBlock(DjangoBlock expected, DjangoBlock got) { var tempTagExpected = (DjangoTemplateTagBlock)expected; var tempTagGot = (DjangoTemplateTagBlock)got; Assert.AreEqual(tempTagExpected.ParseInfo.Start, tempTagGot.ParseInfo.Start); Assert.AreEqual(tempTagExpected.ParseInfo.Command, tempTagGot.ParseInfo.Command); Assert.AreEqual(tempTagExpected.ParseInfo.Args, tempTagGot.ParseInfo.Args); } private static void ValidateSpacelessBlock(DjangoBlock expected, DjangoBlock got) { var spacelessExpected = (DjangoSpacelessBlock)expected; var spacelessGot = (DjangoSpacelessBlock)got; Assert.AreEqual(spacelessExpected.ParseInfo.Start, spacelessGot.ParseInfo.Start); Assert.AreEqual(spacelessExpected.ParseInfo.Command, spacelessGot.ParseInfo.Command); Assert.AreEqual(spacelessExpected.ParseInfo.Args, spacelessGot.ParseInfo.Args); } private static void ValidateMultiArgumentBlock(DjangoBlock expected, DjangoBlock got) { var maExpected = (DjangoMultiVariableArgumentBlock)expected; var maGot = (DjangoMultiVariableArgumentBlock)got; Assert.AreEqual(maExpected.ParseInfo.Start, maGot.ParseInfo.Start); Assert.AreEqual(maExpected.ParseInfo.Command, maGot.ParseInfo.Command); Assert.AreEqual(maExpected.ParseInfo.Args, maGot.ParseInfo.Args); } private static void ValidateIfBlock(DjangoBlock expected, DjangoBlock got) { var ifExpected = (DjangoIfBlock)expected; var ifGot = (DjangoIfBlock)got; Assert.AreEqual(ifExpected.ParseInfo.Start, ifGot.ParseInfo.Start); Assert.AreEqual(ifExpected.ParseInfo.Command, ifGot.ParseInfo.Command); Assert.AreEqual(ifExpected.ParseInfo.Args, ifGot.ParseInfo.Args); Assert.AreEqual(ifExpected.Args.Length, ifGot.Args.Length); for (int i = 0; i < ifExpected.Args.Length; i++) { Assert.AreEqual(ifExpected.Args[i], ifGot.Args[i]); } } private static void ValidateIfOrIfNotEqualBlock(DjangoBlock expected, DjangoBlock got) { var ifExpected = (DjangoIfOrIfNotEqualBlock)expected; var ifGot = (DjangoIfOrIfNotEqualBlock)got; Assert.AreEqual(ifExpected.ParseInfo.Start, ifGot.ParseInfo.Start); Assert.AreEqual(ifExpected.ParseInfo.Command, ifGot.ParseInfo.Command); Assert.AreEqual(ifExpected.ParseInfo.Args, ifGot.ParseInfo.Args); } private static void ValidateFilter(DjangoBlock expected, DjangoBlock got) { var filterExpected = (DjangoFilterBlock)expected; var filterGot = (DjangoFilterBlock)got; Assert.AreEqual(filterExpected.ParseInfo.Start, filterGot.ParseInfo.Start); Assert.AreEqual(filterExpected.ParseInfo.Command, filterGot.ParseInfo.Command); Assert.AreEqual(filterExpected.ParseInfo.Args, filterGot.ParseInfo.Args); } private static void ValidateForBlock(DjangoBlock expected, DjangoBlock got) { var forExpected = (DjangoForBlock)expected; var forGot = (DjangoForBlock)got; Assert.AreEqual(forExpected.ParseInfo.Start, forGot.ParseInfo.Start); Assert.AreEqual(forExpected.InStart, forGot.InStart); } private static void ValidateAutoEscape(DjangoBlock expected, DjangoBlock got) { var aeExpected = (DjangoAutoEscapeBlock)expected; var aeGot = (DjangoAutoEscapeBlock)got; Assert.AreEqual(aeExpected.ParseInfo.Start, aeGot.ParseInfo.Start); Assert.AreEqual(aeExpected.ParseInfo.Command, aeGot.ParseInfo.Command); Assert.AreEqual(aeExpected.ParseInfo.Args, aeGot.ParseInfo.Args); } private static void ValidateArgumentless(DjangoBlock expected, DjangoBlock got) { var aeExpected = (DjangoArgumentlessBlock)expected; var aeGot = (DjangoArgumentlessBlock)got; Assert.AreEqual(aeExpected.ParseInfo.Start, aeGot.ParseInfo.Start); Assert.AreEqual(aeExpected.ParseInfo.Command, aeGot.ParseInfo.Command); Assert.AreEqual(aeExpected.ParseInfo.Args, aeGot.ParseInfo.Args); } private void ValidateBlock(DjangoBlock expected, DjangoBlock got) { Assert.AreEqual(expected.GetType(), got.GetType()); _blockValidators[expected.GetType()](expected, got); } #endregion #region Template tokenizer tests [TestMethod, Priority(1)] public void TestSimpleVariable() { var code = @"<html> <head><title></title></head> <body> {{ content }} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Variable, 50, 62), new TemplateToken(TemplateTokenKind.Text, 63, 82) ); } [TestMethod, Priority(1)] public void TestEmbeddedWrongClose() { var code = @"<html> <head><title></title></head> <body> {{ content %} }} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Variable, 50, 65), new TemplateToken(TemplateTokenKind.Text, 66, 85) ); } [TestMethod, Priority(1)] public void SingleTrailingChar() { foreach (var code in new[] { "{{fob}}\n", "{{fob}}a" }) { TokenizerTest(code, new TemplateToken(TemplateTokenKind.Variable, 0, 6), new TemplateToken(TemplateTokenKind.Text, 7, 7) ); } } // struct TemplateTokenResult { public readonly TemplateToken Token; public readonly char? Start, End; public TemplateTokenResult(TemplateToken token, char? start = null, char? end = null) { Token = token; Start = start; End = end; } public static implicit operator TemplateTokenResult(TemplateToken token) { return new TemplateTokenResult(token); } } [TestMethod, Priority(1)] public void TestSimpleBlock() { var code = @"<html> <head><title></title></head> <body> {% block %} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Block, 50, 60), new TemplateToken(TemplateTokenKind.Text, 61, code.Length - 1)); } [TestMethod, Priority(1)] public void TestSimpleComment() { var code = @"<html> <head><title></title></head> <body> {# comment #} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Comment, 50, 62), new TemplateToken(TemplateTokenKind.Text, 63, code.Length - 1)); } [TestMethod, Priority(1)] public void TestUnclosedVariable() { var code = @"<html> <head><title></title></head> <body> {{ content </body> </html>"; TokenizerTest(code, /*unclosed*/true, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Variable, 50, 80, isClosed: false) ); } [TestMethod, Priority(1)] public void TestTextStartAndEnd() { var code = @"<html> <head><title></title></head> <body> <p>{{ content }}</p> </body> </html>"; TokenizerTest(code, new TemplateTokenResult( new TemplateToken(TemplateTokenKind.Text, 0, code.IndexOf("<p>") + 2), '<', '>' ), new TemplateToken(TemplateTokenKind.Variable, code.IndexOf("<p>") + 3, code.IndexOf("</p>") - 1), new TemplateTokenResult( new TemplateToken(TemplateTokenKind.Text, code.IndexOf("</p>"), code.Length - 1), '<', '>' ) ); } [TestMethod, Priority(1)] public void TestUnclosedComment() { var code = @"<html> <head><title></title></head> <body> {# content </body> </html>"; TokenizerTest(code, /*unclosed*/true, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Comment, 50, 80, isClosed: false) ); } [TestMethod, Priority(1)] public void TestUnclosedBlock() { var code = @"<html> <head><title></title></head> <body> {% content </body> </html>"; TokenizerTest(code, /*unclosed*/true, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Block, 50, 80, isClosed: false) ); } private void TokenizerTest(string text, params TemplateTokenResult[] expected) { TokenizerTest(text, false, expected); } private void TokenizerTest(string text, bool unclosed, params TemplateTokenResult[] expected) { var tokenizer = new TemplateTokenizer(new StringReader(text)); var tokens = tokenizer.GetTokens().ToArray(); bool passed = false; try { Assert.AreEqual(expected.Length, tokens.Length); Assert.AreEqual(0, tokens[0].Start); Assert.AreEqual(text.Length - 1, tokens[tokens.Length - 1].End); for (int i = 0; i < expected.Length; i++) { var expectedToken = expected[i].Token; Assert.AreEqual(expectedToken.Kind, tokens[i].Kind); Assert.AreEqual(expectedToken.Start, tokens[i].Start); Assert.AreEqual(expectedToken.End, tokens[i].End); switch (expectedToken.Kind) { case TemplateTokenKind.Block: case TemplateTokenKind.Comment: case TemplateTokenKind.Variable: Assert.AreEqual('{', text[expectedToken.Start]); if (!unclosed) { Assert.AreEqual('}', text[expectedToken.End]); } break; } if (expected[i].Start != null) { Assert.AreEqual(expected[i].Start, text[expectedToken.Start]); } if (expected[i].End != null) { Assert.AreEqual(expected[i].End, text[expectedToken.End]); } } passed = true; } finally { if (!passed) { List<string> res = new List<string>(); for (int i = 0; i < tokens.Length; i++) { res.Add( String.Format("new TemplateToken(TemplateTokenKind.{0}, {1}, {2})", tokens[i].Kind, tokens[i].Start, tokens[i].End ) ); } Console.WriteLine(String.Join(",\r\n", res)); } } } #endregion } class TestCompletionContext : IDjangoCompletionContext { private readonly string[] _variables; private readonly Dictionary<string, TagInfo> _filters; internal static TestCompletionContext Simple = new TestCompletionContext(new[] { "fob", "oar" }, new[] { "cut", "lower" }); public TestCompletionContext(string[] variables, string[] filters) { _variables = variables; _filters = new Dictionary<string, TagInfo>(); foreach (var filter in filters) { _filters[filter] = new TagInfo("", null); } } #region IDjangoCompletionContext Members public Dictionary<string, TagInfo> Filters { get { return _filters; } } public string[] Variables { get { return _variables; } } public Dictionary<string, PythonMemberType> GetMembers(string name) { return new Dictionary<string, PythonMemberType>(); } #endregion } }
using System; using System.Collections.Generic; using UnityEngine; namespace Facebook { sealed class AndroidFacebook : AbstractFacebook, IFacebook { public const int BrowserDialogMode = 0; private const string AndroidJavaFacebookClass = "com.facebook.unity.FB"; private const string CallbackIdKey = "callback_id"; // key Hash used for Android SDK private string keyHash; public string KeyHash { get { return keyHash; } } #region IFacebook public override int DialogMode { get { return BrowserDialogMode; } set { } } public override bool LimitEventUsage { get { return limitEventUsage; } set { limitEventUsage = value; CallFB("SetLimitEventUsage", value.ToString()); } } #endregion private FacebookDelegate deepLinkDelegate; #region FBJava #if UNITY_ANDROID private AndroidJavaClass fbJava; private AndroidJavaClass FB { get { if (fbJava == null) { fbJava = new AndroidJavaClass(AndroidJavaFacebookClass); if (fbJava == null) { throw new MissingReferenceException(string.Format("AndroidFacebook failed to load {0} class", AndroidJavaFacebookClass)); } } return fbJava; } } #endif private void CallFB(string method, string args) { #if UNITY_ANDROID FB.CallStatic(method, args); #else FbDebug.Error("Using Android when not on an Android build! Doesn't Work!"); #endif } #endregion #region FBAndroid protected override void OnAwake() { keyHash = ""; #if UNITY_ANDROID && DEBUG AndroidJNIHelper.debug = true; #endif } private bool IsErrorResponse(string response) { //var res = MiniJSON.Json.Deserialize(response); return false; } private InitDelegate onInitComplete = null; public override void Init( InitDelegate onInitComplete, string appId, bool cookie = false, bool logging = true, bool status = true, bool xfbml = false, string channelUrl = "", string authResponse = null, bool frictionlessRequests = false, HideUnityDelegate hideUnityDelegate = null) { if (string.IsNullOrEmpty(appId)) { throw new ArgumentException("appId cannot be null or empty!"); } var parameters = new Dictionary<string, object>(); parameters.Add("appId", appId); if (cookie != false) { parameters.Add("cookie", true); } if (logging != true) { parameters.Add("logging", false); } if (status != true) { parameters.Add("status", false); } if (xfbml != false) { parameters.Add("xfbml", true); } if (!string.IsNullOrEmpty(channelUrl)) { parameters.Add("channelUrl", channelUrl); } if (!string.IsNullOrEmpty(authResponse)) { parameters.Add("authResponse", authResponse); } if (frictionlessRequests != false) { parameters.Add("frictionlessRequests", true); } var paramJson = MiniJSON.Json.Serialize(parameters); this.onInitComplete = onInitComplete; this.CallFB("Init", paramJson.ToString()); } public void OnInitComplete(string message) { this.isInitialized = true; OnLoginComplete(message); if (this.onInitComplete != null) { this.onInitComplete(); } } public override void Login(string scope = "", FacebookDelegate callback = null) { var parameters = new Dictionary<string, object>(); parameters.Add("scope", scope); var paramJson = MiniJSON.Json.Serialize(parameters); AddAuthDelegate(callback); this.CallFB("Login", paramJson); } public void OnLoginComplete(string message) { var parameters = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message); if (parameters.ContainsKey("user_id")) { isLoggedIn = true; userId = (string)parameters["user_id"]; accessToken = (string)parameters["access_token"]; accessTokenExpiresAt = FromTimestamp(int.Parse((string)parameters["expiration_timestamp"])); } if (parameters.ContainsKey("key_hash")) { keyHash = (string)parameters["key_hash"]; } OnAuthResponse(new FBResult(message)); } public void OnGroupCreateComplete(string message) { var result = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message); var callbackId = (string)result[CallbackIdKey]; result.Remove(CallbackIdKey); OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result))); } //TODO: move into AbstractFacebook public void OnAccessTokenRefresh(string message) { var parameters = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message); if (parameters.ContainsKey("access_token")) { accessToken = (string)parameters["access_token"]; accessTokenExpiresAt = FromTimestamp(int.Parse((string)parameters["expiration_timestamp"])); } } public override void Logout() { this.CallFB("Logout", ""); } public void OnLogoutComplete(string message) { isLoggedIn = false; userId = ""; accessToken = ""; } public override void AppRequest( string message, OGActionType actionType, string objectId, string[] to = null, List<object> filters = null, string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "", FacebookDelegate callback = null) { if (string.IsNullOrEmpty(message)) { throw new ArgumentNullException("message", "message cannot be null or empty!"); } if (actionType != null && string.IsNullOrEmpty(objectId)) { throw new ArgumentNullException("objectId", "You cannot provide an actionType without an objectId"); } if (actionType == null && !string.IsNullOrEmpty(objectId)) { throw new ArgumentNullException("actionType", "You cannot provide an objectId without an actionType"); } var paramsDict = new Dictionary<string, object>(); // Marshal all the above into the thing paramsDict["message"] = message; if (callback != null) { paramsDict["callback_id"] = AddFacebookDelegate(callback); } if (actionType != null && !string.IsNullOrEmpty(objectId)) { paramsDict["action_type"] = actionType.ToString(); paramsDict["object_id"] = objectId; } if (to != null) { paramsDict["to"] = string.Join(",", to); } if (filters != null && filters.Count > 0) { string mobileFilter = filters[0] as string; if(mobileFilter != null) { paramsDict["filters"] = mobileFilter; } } if (maxRecipients != null) { paramsDict["max_recipients"] = maxRecipients.Value; } if (!string.IsNullOrEmpty(data)) { paramsDict["data"] = data; } if (!string.IsNullOrEmpty(title)) { paramsDict["title"] = title; } CallFB("AppRequest", MiniJSON.Json.Serialize(paramsDict)); } public void OnAppRequestsComplete(string message) { var rawResult = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message); if (rawResult.ContainsKey(CallbackIdKey)) { var result = new Dictionary<string, object>(); var callbackId = (string)rawResult[CallbackIdKey]; rawResult.Remove(CallbackIdKey); if (rawResult.Count > 0) { List<string> to = new List<string>(rawResult.Count - 1); foreach (string key in rawResult.Keys) { if (!key.StartsWith("to")) { result[key] = rawResult[key]; continue; } to.Add((string)rawResult[key]); } result.Add("to", to); rawResult.Clear(); OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result))); } else { //if we make it here java returned a callback message with only an id //this isnt supposed to happen OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result), "Malformed request response. Please file a bug with facebook here: https://developers.facebook.com/bugs/create")); } } } public override void FeedRequest( string toId = "", string link = "", string linkName = "", string linkCaption = "", string linkDescription = "", string picture = "", string mediaSource = "", string actionName = "", string actionLink = "", string reference = "", Dictionary<string, string[]> properties = null, FacebookDelegate callback = null) { Dictionary<string, object> paramsDict = new Dictionary<string, object>(); // Marshal all the above into the thing if (callback != null) { paramsDict["callback_id"] = AddFacebookDelegate(callback); } if (!string.IsNullOrEmpty(toId)) { paramsDict.Add("to", toId); } if (!string.IsNullOrEmpty(link)) { paramsDict.Add("link", link); } if (!string.IsNullOrEmpty(linkName)) { paramsDict.Add("name", linkName); } if (!string.IsNullOrEmpty(linkCaption)) { paramsDict.Add("caption", linkCaption); } if (!string.IsNullOrEmpty(linkDescription)) { paramsDict.Add("description", linkDescription); } if (!string.IsNullOrEmpty(picture)) { paramsDict.Add("picture", picture); } if (!string.IsNullOrEmpty(mediaSource)) { paramsDict.Add("source", mediaSource); } if (!string.IsNullOrEmpty(actionName) && !string.IsNullOrEmpty(actionLink)) { Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add("name", actionName); dict.Add("link", actionLink); paramsDict.Add("actions", new[] { dict }); } if (!string.IsNullOrEmpty(reference)) { paramsDict.Add("ref", reference); } if (properties != null) { Dictionary<string, object> newObj = new Dictionary<string, object>(); foreach (KeyValuePair<string, string[]> pair in properties) { if (pair.Value.Length < 1) continue; if (pair.Value.Length == 1) { // String-string newObj.Add(pair.Key, pair.Value[0]); } else { // String-Object with two parameters Dictionary<string, object> innerObj = new Dictionary<string, object>(); innerObj.Add("text", pair.Value[0]); innerObj.Add("href", pair.Value[1]); newObj.Add(pair.Key, innerObj); } } paramsDict.Add("properties", newObj); } CallFB("FeedRequest", MiniJSON.Json.Serialize(paramsDict)); } public void OnFeedRequestComplete(string message) { var rawResult = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message); if (rawResult.ContainsKey(CallbackIdKey)) { var result = new Dictionary<string, object>(); var callbackId = (string)rawResult[CallbackIdKey]; rawResult.Remove(CallbackIdKey); if (rawResult.Count > 0) { foreach (string key in rawResult.Keys) { result[key] = rawResult[key]; } rawResult.Clear(); OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result))); } else { //if we make it here java returned a callback message with only a callback id //this isnt supposed to happen OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result), "Malformed request response. Please file a bug with facebook here: https://developers.facebook.com/bugs/create")); } } } public override void Pay( string product, string action = "purchaseitem", int quantity = 1, int? quantityMin = null, int? quantityMax = null, string requestId = null, string pricepointId = null, string testCurrency = null, FacebookDelegate callback = null) { throw new PlatformNotSupportedException("There is no Facebook Pay Dialog on Android"); } public override void GameGroupCreate( string name, string description, string privacy = "CLOSED", FacebookDelegate callback = null) { var paramsDict = new Dictionary<string, object>(); paramsDict["name"] = name; paramsDict["description"] = description; paramsDict["privacy"] = privacy; if (callback != null) { paramsDict["callback_id"] = AddFacebookDelegate(callback); } CallFB("GameGroupCreate", MiniJSON.Json.Serialize (paramsDict)); } public override void GameGroupJoin( string id, FacebookDelegate callback = null) { var paramsDict = new Dictionary<string, object>(); paramsDict["id"] = id; if (callback != null) { paramsDict["callback_id"] = AddFacebookDelegate(callback); } CallFB("GameGroupJoin", MiniJSON.Json.Serialize (paramsDict)); } public override void GetDeepLink(FacebookDelegate callback) { if (callback != null) { deepLinkDelegate = callback; CallFB("GetDeepLink", ""); } } public void OnGetDeepLinkComplete(string message) { var rawResult = (Dictionary<string, object>) MiniJSON.Json.Deserialize(message); if (deepLinkDelegate != null) { object deepLink = ""; rawResult.TryGetValue("deep_link", out deepLink); deepLinkDelegate(new FBResult(deepLink.ToString())); } } public override void AppEventsLogEvent( string logEvent, float? valueToSum = null, Dictionary<string, object> parameters = null) { var paramsDict = new Dictionary<string, object>(); paramsDict["logEvent"] = logEvent; if (valueToSum.HasValue) { paramsDict["valueToSum"] = valueToSum.Value; } if (parameters != null) { paramsDict["parameters"] = ToStringDict(parameters); } CallFB("AppEvents", MiniJSON.Json.Serialize(paramsDict)); } public override void AppEventsLogPurchase( float logPurchase, string currency = "USD", Dictionary<string, object> parameters = null) { var paramsDict = new Dictionary<string, object>(); paramsDict["logPurchase"] = logPurchase; paramsDict["currency"] = (!string.IsNullOrEmpty(currency)) ? currency : "USD"; if (parameters != null) { paramsDict["parameters"] = ToStringDict(parameters); } CallFB("AppEvents", MiniJSON.Json.Serialize(paramsDict)); } #endregion #region Helper Functions public override void PublishInstall(string appId, FacebookDelegate callback = null) { var parameters = new Dictionary<string, string>(2); parameters["app_id"] = appId; if (callback != null) { parameters["callback_id"] = AddFacebookDelegate(callback); } CallFB("PublishInstall", MiniJSON.Json.Serialize(parameters)); } public void OnPublishInstallComplete(string message) { var response = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message); if (response.ContainsKey("callback_id")) { OnFacebookResponse((string)response["callback_id"], new FBResult("")); } } public override void ActivateApp(string appId = null) { var parameters = new Dictionary<string, string>(1); if (!string.IsNullOrEmpty(appId)) { parameters["app_id"] = appId; } CallFB("ActivateApp", MiniJSON.Json.Serialize(parameters)); } private Dictionary<string, string> ToStringDict(Dictionary<string, object> dict) { if (dict == null) { return null; } var newDict = new Dictionary<string, string>(); foreach (KeyValuePair<string, object> kvp in dict) { newDict[kvp.Key] = kvp.Value.ToString(); } return newDict; } //TODO: move into AbstractFacebook private DateTime FromTimestamp(int timestamp) { return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(timestamp); } #endregion } }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. //using System; using System.Collections.Generic; using System.Net; using Apache.Http; using Apache.Http.Client; using Apache.Http.Impl.Client; using Couchbase.Lite; using Couchbase.Lite.Replicator; using Couchbase.Lite.Util; using NUnit.Framework; using Sharpen; namespace Couchbase.Lite.Replicator { public class ChangeTrackerTest : LiteTestCase { public const string Tag = "ChangeTracker"; /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerOneShot() { ChangeTrackerTestWithMode(ChangeTracker.ChangeTrackerMode.OneShot, true); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerLongPoll() { ChangeTrackerTestWithMode(ChangeTracker.ChangeTrackerMode.LongPoll, true); } /// <exception cref="System.Exception"></exception> public virtual void ChangeTrackerTestWithMode(ChangeTracker.ChangeTrackerMode mode , bool useMockReplicator) { CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); CountDownLatch changeReceivedSignal = new CountDownLatch(1); Uri testURL = GetReplicationURL(); ChangeTrackerClient client = new _ChangeTrackerClient_42(changeTrackerFinishedSignal , useMockReplicator, changeReceivedSignal); ChangeTracker changeTracker = new ChangeTracker(testURL, mode, false, 0, client); changeTracker.SetUsePOST(IsTestingAgainstSyncGateway()); changeTracker.Start(); try { bool success = changeReceivedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } changeTracker.Stop(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_42 : ChangeTrackerClient { public _ChangeTrackerClient_42(CountDownLatch changeTrackerFinishedSignal, bool useMockReplicator , CountDownLatch changeReceivedSignal) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; this.useMockReplicator = useMockReplicator; this.changeReceivedSignal = changeReceivedSignal; } public void ChangeTrackerStopped(ChangeTracker tracker) { changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change.Get("seq"); if (useMockReplicator) { NUnit.Framework.Assert.AreEqual("1", seq.ToString()); } changeReceivedSignal.CountDown(); } public HttpClient GetHttpClient() { if (useMockReplicator) { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.SetResponder("_changes", new _Responder_62()); return mockHttpClient; } else { return new DefaultHttpClient(); } } private sealed class _Responder_62 : CustomizableMockHttpClient.Responder { public _Responder_62() { } /// <exception cref="System.IO.IOException"></exception> public HttpResponse Execute(HttpRequestMessage httpUriRequest) { string json = "{\"results\":[\n" + "{\"seq\":\"1\",\"id\":\"doc1-138\",\"changes\":[{\"rev\":\"1-82d\"}]}],\n" + "\"last_seq\":\"*:50\"}"; return CustomizableMockHttpClient.GenerateHttpResponseObject(json); } } private readonly CountDownLatch changeTrackerFinishedSignal; private readonly bool useMockReplicator; private readonly CountDownLatch changeReceivedSignal; } public virtual void TestChangeTrackerWithConflictsIncluded() { Uri testURL = GetReplicationURL(); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, true, 0, null); NUnit.Framework.Assert.AreEqual("_changes?feed=longpoll&limit=50&heartbeat=300000&style=all_docs&since=0" , changeTracker.GetChangesFeedPath()); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerWithFilterURL() { Uri testURL = GetReplicationURL(); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, false, 0, null); // set filter changeTracker.SetFilterName("filter"); // build filter map IDictionary<string, object> filterMap = new Dictionary<string, object>(); filterMap.Put("param", "value"); // set filter map changeTracker.SetFilterParams(filterMap); NUnit.Framework.Assert.AreEqual("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=filter&param=value" , changeTracker.GetChangesFeedPath()); } public virtual void TestChangeTrackerWithDocsIds() { Uri testURL = GetReplicationURL(); ChangeTracker changeTrackerDocIds = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, false, 0, null); IList<string> docIds = new AList<string>(); docIds.AddItem("doc1"); docIds.AddItem("doc2"); changeTrackerDocIds.SetDocIDs(docIds); string docIdsUnencoded = "[\"doc1\",\"doc2\"]"; string docIdsEncoded = URLEncoder.Encode(docIdsUnencoded); string expectedFeedPath = string.Format("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=_doc_ids&doc_ids=%s" , docIdsEncoded); string changesFeedPath = changeTrackerDocIds.GetChangesFeedPath(); NUnit.Framework.Assert.AreEqual(expectedFeedPath, changesFeedPath); changeTrackerDocIds.SetUsePOST(true); IDictionary<string, object> postBodyMap = changeTrackerDocIds.ChangesFeedPOSTBodyMap (); NUnit.Framework.Assert.AreEqual("_doc_ids", postBodyMap.Get("filter")); NUnit.Framework.Assert.AreEqual(docIds, postBodyMap.Get("doc_ids")); string postBody = changeTrackerDocIds.ChangesFeedPOSTBody(); NUnit.Framework.Assert.IsTrue(postBody.Contains(docIdsUnencoded)); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerBackoffExceptions() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); TestChangeTrackerBackoff(mockHttpClient); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerBackoffInvalidJson() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderReturnInvalidChangesFeedJson(); TestChangeTrackerBackoff(mockHttpClient); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerRecoverableError() { int errorCode = 503; string statusMessage = "Transient Error"; int numExpectedChangeCallbacks = 2; RunChangeTrackerTransientError(ChangeTracker.ChangeTrackerMode.LongPoll, errorCode , statusMessage, numExpectedChangeCallbacks); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerRecoverableIOException() { int errorCode = -1; // special code to tell it to throw an IOException string statusMessage = null; int numExpectedChangeCallbacks = 2; RunChangeTrackerTransientError(ChangeTracker.ChangeTrackerMode.LongPoll, errorCode , statusMessage, numExpectedChangeCallbacks); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerNonRecoverableError() { int errorCode = 404; string statusMessage = "NOT FOUND"; int numExpectedChangeCallbacks = 1; RunChangeTrackerTransientError(ChangeTracker.ChangeTrackerMode.LongPoll, errorCode , statusMessage, numExpectedChangeCallbacks); } /// <exception cref="System.Exception"></exception> private void RunChangeTrackerTransientError(ChangeTracker.ChangeTrackerMode mode, int errorCode, string statusMessage, int numExpectedChangeCallbacks) { CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); CountDownLatch changeReceivedSignal = new CountDownLatch(numExpectedChangeCallbacks ); Uri testURL = GetReplicationURL(); ChangeTrackerClient client = new _ChangeTrackerClient_197(changeTrackerFinishedSignal , changeReceivedSignal, errorCode, statusMessage); ChangeTracker changeTracker = new ChangeTracker(testURL, mode, false, 0, client); changeTracker.SetUsePOST(IsTestingAgainstSyncGateway()); changeTracker.Start(); try { bool success = changeReceivedSignal.Await(30, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } changeTracker.Stop(); try { bool success = changeTrackerFinishedSignal.Await(30, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_197 : ChangeTrackerClient { public _ChangeTrackerClient_197(CountDownLatch changeTrackerFinishedSignal, CountDownLatch changeReceivedSignal, int errorCode, string statusMessage) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; this.changeReceivedSignal = changeReceivedSignal; this.errorCode = errorCode; this.statusMessage = statusMessage; } public void ChangeTrackerStopped(ChangeTracker tracker) { changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { changeReceivedSignal.CountDown(); } public HttpClient GetHttpClient() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); CustomizableMockHttpClient.Responder sentinal = this.DefaultChangesResponder(); Queue<CustomizableMockHttpClient.Responder> responders = new List<CustomizableMockHttpClient.Responder >(); responders.AddItem(this.DefaultChangesResponder()); responders.AddItem(CustomizableMockHttpClient.TransientErrorResponder(errorCode, statusMessage)); ResponderChain responderChain = new ResponderChain(responders, sentinal); mockHttpClient.SetResponder("_changes", responderChain); return mockHttpClient; } private CustomizableMockHttpClient.Responder DefaultChangesResponder() { return new _Responder_222(); } private sealed class _Responder_222 : CustomizableMockHttpClient.Responder { public _Responder_222() { } /// <exception cref="System.IO.IOException"></exception> public HttpResponse Execute(HttpRequestMessage httpUriRequest) { string json = "{\"results\":[\n" + "{\"seq\":\"1\",\"id\":\"doc1-138\",\"changes\":[{\"rev\":\"1-82d\"}]}],\n" + "\"last_seq\":\"*:50\"}"; return CustomizableMockHttpClient.GenerateHttpResponseObject(json); } } private readonly CountDownLatch changeTrackerFinishedSignal; private readonly CountDownLatch changeReceivedSignal; private readonly int errorCode; private readonly string statusMessage; } /// <exception cref="System.Exception"></exception> private void TestChangeTrackerBackoff(CustomizableMockHttpClient mockHttpClient) { Uri testURL = GetReplicationURL(); CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); ChangeTrackerClient client = new _ChangeTrackerClient_263(changeTrackerFinishedSignal , mockHttpClient); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, false, 0, client); changeTracker.SetUsePOST(IsTestingAgainstSyncGateway()); changeTracker.Start(); // sleep for a few seconds Sharpen.Thread.Sleep(5 * 1000); // make sure we got less than 10 requests in those 10 seconds (if it was hammering, we'd get a lot more) NUnit.Framework.Assert.IsTrue(mockHttpClient.GetCapturedRequests().Count < 25); NUnit.Framework.Assert.IsTrue(changeTracker.backoff.GetNumAttempts() > 0); mockHttpClient.ClearResponders(); mockHttpClient.AddResponderReturnEmptyChangesFeed(); // at this point, the change tracker backoff should cause it to sleep for about 3 seconds // and so lets wait 3 seconds until it wakes up and starts getting valid responses Sharpen.Thread.Sleep(3 * 1000); // now find the delta in requests received in a 2s period int before = mockHttpClient.GetCapturedRequests().Count; Sharpen.Thread.Sleep(2 * 1000); int after = mockHttpClient.GetCapturedRequests().Count; // assert that the delta is high, because at this point the change tracker should // be hammering away NUnit.Framework.Assert.IsTrue((after - before) > 25); // the backoff numAttempts should have been reset to 0 NUnit.Framework.Assert.IsTrue(changeTracker.backoff.GetNumAttempts() == 0); changeTracker.Stop(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_263 : ChangeTrackerClient { public _ChangeTrackerClient_263(CountDownLatch changeTrackerFinishedSignal, CustomizableMockHttpClient mockHttpClient) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; this.mockHttpClient = mockHttpClient; } public void ChangeTrackerStopped(ChangeTracker tracker) { Log.V(ChangeTrackerTest.Tag, "changeTrackerStopped"); changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change.Get("seq"); Log.V(ChangeTrackerTest.Tag, "changeTrackerReceivedChange: " + seq.ToString()); } public HttpClient GetHttpClient() { return mockHttpClient; } private readonly CountDownLatch changeTrackerFinishedSignal; private readonly CustomizableMockHttpClient mockHttpClient; } // ChangeTrackerMode.Continuous mode does not work, do not use it. /// <exception cref="System.Exception"></exception> public virtual void FailingTestChangeTrackerContinuous() { CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); CountDownLatch changeReceivedSignal = new CountDownLatch(1); Uri testURL = GetReplicationURL(); ChangeTrackerClient client = new _ChangeTrackerClient_333(changeTrackerFinishedSignal , changeReceivedSignal); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .Continuous, false, 0, client); changeTracker.SetUsePOST(IsTestingAgainstSyncGateway()); changeTracker.Start(); try { bool success = changeReceivedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } changeTracker.Stop(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_333 : ChangeTrackerClient { public _ChangeTrackerClient_333(CountDownLatch changeTrackerFinishedSignal, CountDownLatch changeReceivedSignal) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; this.changeReceivedSignal = changeReceivedSignal; } public void ChangeTrackerStopped(ChangeTracker tracker) { changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change.Get("seq"); changeReceivedSignal.CountDown(); } public HttpClient GetHttpClient() { return new DefaultHttpClient(); } private readonly CountDownLatch changeTrackerFinishedSignal; private readonly CountDownLatch changeReceivedSignal; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using Models; /// <summary> /// HttpClientFailure operations. /// </summary> public partial interface IHttpClientFailure { /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Head400WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Get400WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Put400WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Patch400WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Post400WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Delete400WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 401 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Head401WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 402 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Get402WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 403 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Get403WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 404 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Put404WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 405 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Patch405WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 406 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Post406WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 407 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Delete407WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 409 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Put409WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 410 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Head410WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 411 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Get411WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 412 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Get412WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 413 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Put413WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 414 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Patch414WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 415 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Post415WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 416 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Get416WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 417 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Delete417WithHttpMessagesAsync(bool? booleanValue = default(bool?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Return 429 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The 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> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Error>> Head429WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
// 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 Xunit; namespace System.Linq.Tests { public class JoinTests { private class AnagramEqualityComparer : IEqualityComparer<string> { public bool Equals(string x, string y) { if (ReferenceEquals(x, y)) return true; if (x == null | y == null) return false; int length = x.Length; if (length != y.Length) return false; using (var en = x.OrderBy(i => i).GetEnumerator()) { foreach (char c in y.OrderBy(i => i)) { en.MoveNext(); if (c != en.Current) return false; } } return true; } public int GetHashCode(string obj) { int hash = 0; foreach (char c in obj) hash ^= (int)c; return hash; } } public struct CustomerRec { public string name; public int custID; } public struct OrderRec { public int orderID; public int custID; public int total; } public struct AnagramRec { public string name; public int orderID; public int total; } public struct JoinRec { public string name; public int orderID; public int total; } public static JoinRec createJoinRec(CustomerRec cr, OrderRec or) { return new JoinRec { name = cr.name, orderID = or.orderID, total = or.total }; } public static JoinRec createJoinRec(CustomerRec cr, AnagramRec or) { return new JoinRec { name = cr.name, orderID = or.orderID, total = or.total }; } [Fact] public void OuterEmptyInnerNonEmpty() { CustomerRec[] outer = { }; OrderRec[] inner = new [] { new OrderRec{ orderID = 45321, custID = 98022, total = 50 }, new OrderRec{ orderID = 97865, custID = 32103, total = 25 } }; JoinRec[] expected = { }; Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void FirstOuterMatchesLastInnerLastOuterMatchesFirstInnerSameNumberElements() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Prakash", custID = 98022 }, new CustomerRec{ name = "Tim", custID = 99021 }, new CustomerRec{ name = "Robert", custID = 99022 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 45321, custID = 99022, total = 50 }, new OrderRec{ orderID = 43421, custID = 29022, total = 20 }, new OrderRec{ orderID = 95421, custID = 98022, total = 9 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Prakash", orderID = 95421, total = 9 }, new JoinRec{ name = "Robert", orderID = 45321, total = 50 } }; Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void NullComparer() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Prakash", custID = 98022 }, new CustomerRec{ name = "Tim", custID = 99021 }, new CustomerRec{ name = "Robert", custID = 99022 } }; AnagramRec[] inner = new [] { new AnagramRec{ name = "miT", orderID = 43455, total = 10 }, new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Prakash", orderID = 323232, total = 9 } }; Assert.Equal(expected, outer.Join(inner, e => e.name, e => e.name, createJoinRec, null)); } [Fact] public void CustomComparer() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Prakash", custID = 98022 }, new CustomerRec{ name = "Tim", custID = 99021 }, new CustomerRec{ name = "Robert", custID = 99022 } }; AnagramRec[] inner = new [] { new AnagramRec{ name = "miT", orderID = 43455, total = 10 }, new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Prakash", orderID = 323232, total = 9 }, new JoinRec{ name = "Tim", orderID = 43455, total = 10 } }; Assert.Equal(expected, outer.Join(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void OuterNull() { CustomerRec[] outer = null; AnagramRec[] inner = new [] { new AnagramRec{ name = "miT", orderID = 43455, total = 10 }, new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 } }; Assert.Throws<ArgumentNullException>("outer", () => outer.Join(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void InnerNull() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Prakash", custID = 98022 }, new CustomerRec{ name = "Tim", custID = 99021 }, new CustomerRec{ name = "Robert", custID = 99022 } }; AnagramRec[] inner = null; Assert.Throws<ArgumentNullException>("inner", () => outer.Join(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void OuterKeySelectorNull() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Prakash", custID = 98022 }, new CustomerRec{ name = "Tim", custID = 99021 }, new CustomerRec{ name = "Robert", custID = 99022 } }; AnagramRec[] inner = new [] { new AnagramRec{ name = "miT", orderID = 43455, total = 10 }, new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Prakash", orderID = 323232, total = 9 }, new JoinRec{ name = "Tim", orderID = 43455, total = 10 } }; Assert.Throws<ArgumentNullException>("outerKeySelector", () => outer.Join(inner, null, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void InnerKeySelectorNull() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Prakash", custID = 98022 }, new CustomerRec{ name = "Tim", custID = 99021 }, new CustomerRec{ name = "Robert", custID = 99022 } }; AnagramRec[] inner = new [] { new AnagramRec{ name = "miT", orderID = 43455, total = 10 }, new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 } }; Assert.Throws<ArgumentNullException>("innerKeySelector", () => outer.Join(inner, e => e.name, null, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNull() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Prakash", custID = 98022 }, new CustomerRec{ name = "Tim", custID = 99021 }, new CustomerRec{ name = "Robert", custID = 99022 } }; AnagramRec[] inner = new [] { new AnagramRec{ name = "miT", orderID = 43455, total = 10 }, new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 } }; Assert.Throws<ArgumentNullException>("resultSelector", () => outer.Join(inner, e => e.name, e => e.name, (Func<CustomerRec, AnagramRec, JoinRec>)null, new AnagramEqualityComparer())); } [Fact] public void SkipsNullElements() { string[] outer = new [] { null, string.Empty }; string[] inner = new [] { null, string.Empty }; string[] expected = new [] { string.Empty }; Assert.Equal(expected, outer.Join(inner, e => e, e => e, (x, y) => y, EqualityComparer<string>.Default)); } [Fact] public void OuterNonEmptyInnerEmpty() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 43434 }, new CustomerRec{ name = "Bob", custID = 34093 } }; OrderRec[] inner = { }; JoinRec[] expected = { }; Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void SingleElementEachAndMatches() { CustomerRec[] outer = new [] { new CustomerRec { name = "Prakash", custID = 98022 } }; OrderRec[] inner = new [] { new OrderRec { orderID = 45321, custID = 98022, total = 50 } }; JoinRec[] expected = new [] { new JoinRec { name = "Prakash", orderID = 45321, total = 50 } }; Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void SingleElementEachAndDoesntMatch() { CustomerRec[] outer = new [] { new CustomerRec { name = "Prakash", custID = 98922 } }; OrderRec[] inner = new [] { new OrderRec { orderID = 45321, custID = 98022, total = 50 } }; JoinRec[] expected = { }; Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void SelectorsReturnNull() { int?[] inner = { null, null, null }; int?[] outer = { null, null }; int?[] expected = { }; Assert.Equal(expected, outer.Join(inner, e => e, e => e, (x, y) => x)); } [Fact] public void InnerSameKeyMoreThanOneElementAndMatches() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Prakash", custID = 98022 }, new CustomerRec{ name = "Tim", custID = 99021 }, new CustomerRec{ name = "Robert", custID = 99022 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 45321, custID = 98022, total = 50 }, new OrderRec{ orderID = 45421, custID = 98022, total = 10 }, new OrderRec{ orderID = 43421, custID = 99022, total = 20 }, new OrderRec{ orderID = 85421, custID = 98022, total = 18 }, new OrderRec{ orderID = 95421, custID = 99021, total = 9 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Prakash", orderID = 45321, total = 50 }, new JoinRec{ name = "Prakash", orderID = 45421, total = 10 }, new JoinRec{ name = "Prakash", orderID = 85421, total = 18 }, new JoinRec{ name = "Tim", orderID = 95421, total = 9 }, new JoinRec{ name = "Robert", orderID = 43421, total = 20 } }; Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void OuterSameKeyMoreThanOneElementAndMatches() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Prakash", custID = 98022 }, new CustomerRec{ name = "Bob", custID = 99022 }, new CustomerRec{ name = "Tim", custID = 99021 }, new CustomerRec{ name = "Robert", custID = 99022 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 45321, custID = 98022, total = 50 }, new OrderRec{ orderID = 43421, custID = 99022, total = 20 }, new OrderRec{ orderID = 95421, custID = 99021, total = 9 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Prakash", orderID = 45321, total = 50 }, new JoinRec{ name = "Bob", orderID = 43421, total = 20 }, new JoinRec{ name = "Tim", orderID = 95421, total = 9 }, new JoinRec{ name = "Robert", orderID = 43421, total = 20 } }; Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void NoMatches() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Prakash", custID = 98022 }, new CustomerRec{ name = "Bob", custID = 99022 }, new CustomerRec{ name = "Tim", custID = 99021 }, new CustomerRec{ name = "Robert", custID = 99022 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 45321, custID = 18022, total = 50 }, new OrderRec{ orderID = 43421, custID = 29022, total = 20 }, new OrderRec{ orderID = 95421, custID = 39021, total = 9 } }; JoinRec[] expected = { }; Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec)); } } }
// 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.Collections.Immutable; using System.Diagnostics; using System.Threading; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DisposeAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Runtime { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DisposableFieldsShouldBeDisposed : DiagnosticAnalyzer { internal const string RuleId = "CA2213"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DisposableFieldsShouldBeDisposedTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DisposableFieldsShouldBeDisposedMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DisposableFieldsShouldBeDisposedDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessage, DiagnosticCategory.Usage, RuleLevel.Disabled, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze); context.RegisterSymbolStartAction(OnSymbolStart, SymbolKind.NamedType); } private static void OnSymbolStart(SymbolStartAnalysisContext symbolStartContext) { if (!DisposeAnalysisHelper.TryGetOrCreate(symbolStartContext.Compilation, out DisposeAnalysisHelper? disposeAnalysisHelper) || !ShouldAnalyze(symbolStartContext, disposeAnalysisHelper)) { return; } var fieldDisposeValueMap = PooledConcurrentDictionary<IFieldSymbol, /*disposed*/bool>.GetInstance(); var hasErrors = false; symbolStartContext.RegisterOperationAction(_ => hasErrors = true, OperationKind.Invalid); // Disposable fields with initializer at declaration must be disposed. symbolStartContext.RegisterOperationAction(OnFieldInitializer, OperationKind.FieldInitializer); // Instance fields initialized in constructor/method body with a locally created disposable object must be disposed. symbolStartContext.RegisterOperationBlockStartAction(OnOperationBlockStart); // Report diagnostics at symbol end. symbolStartContext.RegisterSymbolEndAction(OnSymbolEnd); return; // Local functions void AddOrUpdateFieldDisposedValue(IFieldSymbol field, bool disposed) { Debug.Assert(!field.IsStatic); Debug.Assert(disposeAnalysisHelper!.IsDisposable(field.Type)); fieldDisposeValueMap.AddOrUpdate(field, addValue: disposed, updateValueFactory: (f, currentValue) => currentValue || disposed); } static bool ShouldAnalyze(SymbolStartAnalysisContext symbolStartContext, DisposeAnalysisHelper disposeAnalysisHelper) { // We only want to analyze types which are disposable (implement System.IDisposable directly or indirectly) // and have at least one disposable field. var namedType = (INamedTypeSymbol)symbolStartContext.Symbol; return disposeAnalysisHelper.IsDisposable(namedType) && !disposeAnalysisHelper.GetDisposableFields(namedType).IsEmpty && !symbolStartContext.Options.IsConfiguredToSkipAnalysis(Rule, namedType, symbolStartContext.Compilation, symbolStartContext.CancellationToken); } bool IsDisposeMethod(IMethodSymbol method) => disposeAnalysisHelper!.GetDisposeMethodKind(method) != DisposeMethodKind.None; bool HasDisposeMethod(INamedTypeSymbol namedType) { foreach (var method in namedType.GetMembers().OfType<IMethodSymbol>()) { if (IsDisposeMethod(method)) { return true; } } return false; } void OnFieldInitializer(OperationAnalysisContext operationContext) { RoslynDebug.Assert(disposeAnalysisHelper != null); var initializedFields = ((IFieldInitializerOperation)operationContext.Operation).InitializedFields; foreach (var field in initializedFields) { if (!field.IsStatic && disposeAnalysisHelper.GetDisposableFields(field.ContainingType).Contains(field)) { AddOrUpdateFieldDisposedValue(field, disposed: false); } } } void OnOperationBlockStart(OperationBlockStartAnalysisContext operationBlockStartContext) { RoslynDebug.Assert(disposeAnalysisHelper != null); if (operationBlockStartContext.OwningSymbol is not IMethodSymbol containingMethod) { return; } if (disposeAnalysisHelper.HasAnyDisposableCreationDescendant(operationBlockStartContext.OperationBlocks, containingMethod)) { PointsToAnalysisResult? lazyPointsToAnalysisResult = null; operationBlockStartContext.RegisterOperationAction(operationContext => { var fieldReference = (IFieldReferenceOperation)operationContext.Operation; var field = fieldReference.Field; // Only track instance fields on the current instance. if (field.IsStatic || fieldReference.Instance?.Kind != OperationKind.InstanceReference) { return; } // Check if this is a Disposable field that is not currently being tracked. if (fieldDisposeValueMap.ContainsKey(field) || !disposeAnalysisHelper.GetDisposableFields(field.ContainingType).Contains(field)) { return; } // We have a field reference for a disposable field. // Check if it is being assigned a locally created disposable object. if (fieldReference.Parent is ISimpleAssignmentOperation simpleAssignmentOperation && simpleAssignmentOperation.Target == fieldReference) { if (lazyPointsToAnalysisResult == null) { var cfg = operationBlockStartContext.OperationBlocks.GetControlFlowGraph(); if (cfg == null) { hasErrors = true; return; } var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(operationContext.Compilation); var interproceduralAnalysisConfig = InterproceduralAnalysisConfiguration.Create( operationBlockStartContext.Options, Rule, cfg, operationBlockStartContext.Compilation, InterproceduralAnalysisKind.None, operationBlockStartContext.CancellationToken); var pointsToAnalysisResult = PointsToAnalysis.TryGetOrComputeResult(cfg, containingMethod, operationBlockStartContext.Options, wellKnownTypeProvider, PointsToAnalysisKind.PartialWithoutTrackingFieldsAndProperties, interproceduralAnalysisConfig, interproceduralAnalysisPredicate: null, pessimisticAnalysis: false, performCopyAnalysis: false); if (pointsToAnalysisResult == null) { hasErrors = true; return; } Interlocked.CompareExchange(ref lazyPointsToAnalysisResult, pointsToAnalysisResult, null); } PointsToAbstractValue assignedPointsToValue = lazyPointsToAnalysisResult[simpleAssignmentOperation.Value.Kind, simpleAssignmentOperation.Value.Syntax]; foreach (var location in assignedPointsToValue.Locations) { if (disposeAnalysisHelper.IsDisposableCreationOrDisposeOwnershipTransfer(location, containingMethod)) { AddOrUpdateFieldDisposedValue(field, disposed: false); break; } } } }, OperationKind.FieldReference); } // Mark fields disposed in Dispose method(s). if (IsDisposeMethod(containingMethod)) { var disposableFields = disposeAnalysisHelper.GetDisposableFields(containingMethod.ContainingType); if (!disposableFields.IsEmpty) { if (disposeAnalysisHelper.TryGetOrComputeResult(operationBlockStartContext.OperationBlocks, containingMethod, operationBlockStartContext.Options, Rule, PointsToAnalysisKind.Complete, trackInstanceFields: true, trackExceptionPaths: false, cancellationToken: operationBlockStartContext.CancellationToken, disposeAnalysisResult: out var disposeAnalysisResult, pointsToAnalysisResult: out var pointsToAnalysisResult)) { RoslynDebug.Assert(disposeAnalysisResult.TrackedInstanceFieldPointsToMap != null); BasicBlock exitBlock = disposeAnalysisResult.ControlFlowGraph.GetExit(); foreach (var fieldWithPointsToValue in disposeAnalysisResult.TrackedInstanceFieldPointsToMap) { IFieldSymbol field = fieldWithPointsToValue.Key; PointsToAbstractValue pointsToValue = fieldWithPointsToValue.Value; Debug.Assert(disposeAnalysisHelper.IsDisposable(field.Type)); ImmutableDictionary<AbstractLocation, DisposeAbstractValue> disposeDataAtExit = disposeAnalysisResult.ExitBlockOutput.Data; var disposed = false; foreach (var location in pointsToValue.Locations) { if (disposeDataAtExit.TryGetValue(location, out DisposeAbstractValue disposeValue)) { switch (disposeValue.Kind) { // For MaybeDisposed, conservatively mark the field as disposed as we don't support path sensitive analysis. case DisposeAbstractValueKind.MaybeDisposed: case DisposeAbstractValueKind.Unknown: case DisposeAbstractValueKind.Escaped: case DisposeAbstractValueKind.Disposed: disposed = true; AddOrUpdateFieldDisposedValue(field, disposed); break; } } if (disposed) { break; } } } } } } } void OnSymbolEnd(SymbolAnalysisContext symbolEndContext) { try { if (hasErrors) { return; } foreach (var kvp in fieldDisposeValueMap) { IFieldSymbol field = kvp.Key; bool disposed = kvp.Value; // Flag non-disposed fields only if the containing type has a Dispose method implementation. if (!disposed && HasDisposeMethod(field.ContainingType)) { // '{0}' contains field '{1}' that is of IDisposable type '{2}', but it is never disposed. Change the Dispose method on '{0}' to call Close or Dispose on this field. var arg1 = field.ContainingType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); var arg2 = field.Name; var arg3 = field.Type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); var diagnostic = field.CreateDiagnostic(Rule, arg1, arg2, arg3); symbolEndContext.ReportDiagnostic(diagnostic); } } } finally { fieldDisposeValueMap.Free(symbolEndContext.CancellationToken); } } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Management.Automation.Internal; namespace System.Management.Automation.Provider { #region ItemCmdletProvider /// <summary> /// The base class for Cmdlet providers that expose an item as an MSH path. /// </summary> /// /// <remarks> /// The ItemCmdletProvider class is a base class that a provider derives from to /// inherit a set of methods that allows the Monad engine /// to provide a core set of commands for getting and setting of data on one or /// more items. A provider should derive from this class if they want /// to take advantage of the item core commands that are /// already implemented by the Monad engine. This allows users to have common /// commands and semantics across multiple providers. /// </remarks> public abstract class ItemCmdletProvider : DriveCmdletProvider { #region internal methods /// <summary> /// Internal wrapper for the GetItem protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="path"> /// The path to the item to retrieve. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Nothing is returned, but all objects should be written to the WriteObject method. /// </returns> /// internal void GetItem(string path, CmdletProviderContext context) { Context = context; // Call virtual method GetItem(path); } // GetItem /// <summary> /// Gives the provider to attach additional parameters to /// the get-item cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implemenation returns null. (no additional parameters) /// </returns> /// internal object GetItemDynamicParameters(string path, CmdletProviderContext context) { Context = context; return GetItemDynamicParameters(path); } // GetItemDynamicParameters /// <summary> /// Internal wrapper for the SetItem protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="path"> /// The path to the item to set. /// </param> /// /// <param name="value"> /// The value of the item specified by the path. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// The item that was set at the specified path. /// </returns> /// internal void SetItem( string path, object value, CmdletProviderContext context) { providerBaseTracer.WriteLine("ItemCmdletProvider.SetItem"); Context = context; // Call virtual method SetItem(path, value); } // SetItem /// <summary> /// Gives the provider to attach additional parameters to /// the set-item cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="value"> /// The value of the item specified by the path. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implemenation returns null. (no additional parameters) /// </returns> /// internal object SetItemDynamicParameters( string path, object value, CmdletProviderContext context) { Context = context; return SetItemDynamicParameters(path, value); } // SetItemDynamicParameters /// <summary> /// Internal wrapper for the ClearItem protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="path"> /// The path to the item to clear. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// internal void ClearItem( string path, CmdletProviderContext context) { providerBaseTracer.WriteLine("ItemCmdletProvider.ClearItem"); Context = context; // Call virtual method ClearItem(path); } // ClearItem /// <summary> /// Gives the provider to attach additional parameters to /// the clear-item cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implemenation returns null. (no additional parameters) /// </returns> /// internal object ClearItemDynamicParameters( string path, CmdletProviderContext context) { Context = context; return ClearItemDynamicParameters(path); } // ClearItemDynamicParameters /// <summary> /// Internal wrapper for the InvokeDefaultAction protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="path"> /// The path to the item to perform the default action on. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// internal void InvokeDefaultAction( string path, CmdletProviderContext context) { providerBaseTracer.WriteLine("ItemCmdletProvider.InvokeDefaultAction"); Context = context; // Call virtual method InvokeDefaultAction(path); } // InvokeDefaultAction /// <summary> /// Gives the provider to attach additional parameters to /// the invoke-item cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implemenation returns null. (no additional parameters) /// </returns> /// internal object InvokeDefaultActionDynamicParameters( string path, CmdletProviderContext context) { Context = context; return InvokeDefaultActionDynamicParameters(path); } // InvokeDefaultActionDynamicParameters /// <summary> /// Internal wrapper for the Exists protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="path"> /// The path to the item to see if it exists. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// True if the item exists, false otherwise. /// </returns> /// internal bool ItemExists(string path, CmdletProviderContext context) { Context = context; // Call virtual method bool itemExists = false; try { // Some providers don't expect non-valid path elements, and instead // throw an exception here. itemExists = ItemExists(path); } catch (Exception e) { // ignore non-severe exceptions CommandProcessorBase.CheckForSevereException(e); } return itemExists; } // Exists /// <summary> /// Gives the provider to attach additional parameters to /// the test-path cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implemenation returns null. (no additional parameters) /// </returns> /// internal object ItemExistsDynamicParameters( string path, CmdletProviderContext context) { Context = context; return ItemExistsDynamicParameters(path); } // ItemExistsDynamicParameters /// <summary> /// Internal wrapper for the IsValidPath protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="path"> /// The path to check for validity. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// True if the path is syntactically and semantically valid for the provider, or /// false otherwise. /// </returns> /// /// <remarks> /// This test should not verify the existance of the item at the path. It should /// only perform syntactic and semantic validation of the path. For instance, for /// the file system provider, that path should be canonicalized, syntactically verified, /// and ensure that the path does not refer to a device. /// </remarks> /// internal bool IsValidPath(string path, CmdletProviderContext context) { Context = context; // Call virtual method return IsValidPath(path); } // IsValidPath /// <summary> /// Internal wrapper for the ExpandPath protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. Only called for providers that declare /// the ExpandWildcards capability. /// </summary> /// /// <param name="path"> /// The path to expand. Expansion must be consistent with the wildcarding /// rules of PowerShell's WildcardPattern class. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// A list of provider paths that this path expands to. They must all exist. /// </returns> /// internal string[] ExpandPath(string path, CmdletProviderContext context) { Context = context; // Call virtual method return ExpandPath(path); } // IsValidPath #endregion internal methods #region Protected methods /// <summary> /// Gets the item at the specified path. /// </summary> /// /// <param name="path"> /// The path to the item to retrieve. /// </param> /// /// <returns> /// Nothing is returned, but all objects should be written to the WriteItemObject method. /// </returns> /// /// <remarks> /// Providers override this method to give the user access to the provider objects using /// the get-item and get-childitem cmdlets. /// /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/> /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those /// requirements by accessing the appropriate property from the base class. /// /// By default overrides of this method should not write objects that are generally hidden from /// the user unless the Force property is set to true. For instance, the FileSystem provider should /// not call WriteItemObject for hidden or system files unless the Force property is set to true. /// /// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>. /// </remarks> protected virtual void GetItem(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.CmdletProvider_NotSupported); } } /// <summary> /// Gives the provider an opportunity to attach additional parameters to /// the get-item cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implemenation returns null. (no additional parameters) /// </returns> protected virtual object GetItemDynamicParameters(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } // GetItemDynamicParameters /// <summary> /// Sets the item specified by the path. /// </summary> /// /// <param name="path"> /// The path to the item to set. /// </param> /// /// <param name="value"> /// The value of the item specified by the path. /// </param> /// /// <returns> /// Nothing. The item that was set should be passed to the WriteItemObject method. /// </returns> /// /// <remarks> /// Providers override this method to give the user the ability to modify provider objects using /// the set-item cmdlet. /// /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/> /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those /// requirements by accessing the appropriate property from the base class. /// /// By default overrides of this method should not set or write objects that are generally hidden from /// the user unless the Force property is set to true. An error should be sent to the WriteError method if /// the path represents an item that is hidden from the user and Force is set to false. /// /// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>. /// </remarks> protected virtual void SetItem( string path, object value) { using (PSTransactionManager.GetEngineProtectionScope()) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.CmdletProvider_NotSupported); } } /// <summary> /// Gives the provider an opportunity to attach additional parameters to /// the set-item cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="value"> /// The value of the item specified by the path. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implemenation returns null. (no additional parameters) /// </returns> protected virtual object SetItemDynamicParameters(string path, object value) { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } // SetItemDynamicParameters /// <summary> /// Clears the item specified by the path. /// </summary> /// /// <param name="path"> /// The path to the item to clear. /// </param> /// /// <returns> /// Nothing. The item that was cleared should be passed to the WriteItemObject method. /// </returns> /// /// <remarks> /// Providers override this method to give the user the ability to clear provider objects using /// the clear-item cmdlet. /// /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/> /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those /// requirements by accessing the appropriate property from the base class. /// /// By default overrides of this method should not clear or write objects that are generally hidden from /// the user unless the Force property is set to true. An error should be sent to the WriteError method if /// the path represents an item that is hidden from the user and Force is set to false. /// /// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>. /// </remarks> protected virtual void ClearItem( string path) { using (PSTransactionManager.GetEngineProtectionScope()) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.CmdletProvider_NotSupported); } } /// <summary> /// Gives the provider an opportunity to attach additional parameters to /// the clear-item cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implemenation returns null. (no additional parameters) /// </returns> protected virtual object ClearItemDynamicParameters(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } // ClearItemDynamicParameters /// <summary> /// Invokes the default action on the specified item. /// </summary> /// /// <param name="path"> /// The path to the item to perform the default action on. /// </param> /// /// <returns> /// Nothing. The item that was set should be passed to the WriteItemObject method. /// </returns> /// /// <remarks> /// The default implemenation does nothing. /// /// Providers override this method to give the user the ability to invoke provider objects using /// the invoke-item cmdlet. Think of the invocation as a double click in the Windows Shell. This /// method provides a default action based on the path that was passed. /// /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/> /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those /// requirements by accessing the appropriate property from the base class. /// /// By default overrides of this method should not invoke objects that are generally hidden from /// the user unless the Force property is set to true. An error should be sent to the WriteError method if /// the path represents an item that is hidden from the user and Force is set to false. /// </remarks> protected virtual void InvokeDefaultAction( string path) { using (PSTransactionManager.GetEngineProtectionScope()) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.CmdletProvider_NotSupported); } } /// <summary> /// Gives the provider an opportunity to attach additional parameters to /// the invoke-item cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implemenation returns null. (no additional parameters) /// </returns> protected virtual object InvokeDefaultActionDynamicParameters(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } // InvokeDefaultActionDynamicParameters /// <summary> /// Determines if an item exists at the specified path. /// </summary> /// /// <param name="path"> /// The path to the item to see if it exists. /// </param> /// /// <returns> /// True if the item exists, false otherwise. /// </returns> /// /// <returns> /// Nothing. The item that was set should be passed to the WriteItemObject method. /// </returns> /// /// <remarks> /// Providers override this method to give the user the ability to check for the existence of provider objects using /// the set-item cmdlet. /// /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/> /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those /// requirements by accessing the appropriate property from the base class. /// /// The implemenation of this method should take into account any form of access to the object that may /// make it visible to the user. For instance, if a user has write access to a file in the file system /// provider bug not read access, the file still exists and the method should return true. Sometimes this /// may require checking the parent to see if the child can be enumerated. /// /// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>. /// </remarks> protected virtual bool ItemExists(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.CmdletProvider_NotSupported); } } /// <summary> /// Gives the provider an opportunity to attach additional parameters to /// the test-path cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implemenation returns null. (no additional parameters) /// </returns> protected virtual object ItemExistsDynamicParameters(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } // ItemExistsDynamicParameters /// <summary> /// Providers must override this method to verify the syntax and semantics /// of their paths. /// </summary> /// /// <param name="path"> /// The path to check for validity. /// </param> /// /// <returns> /// True if the path is syntactically and semantically valid for the provider, or /// false otherwise. /// </returns> /// /// <remarks> /// This test should not verify the existance of the item at the path. It should /// only perform syntactic and semantic validation of the path. For instance, for /// the file system provider, that path should be canonicalized, syntactically verified, /// and ensure that the path does not refer to a device. /// </remarks> protected abstract bool IsValidPath(string path); /// <summary> /// Expand a provider path that contains wildcards to a list of provider /// paths that the path represents.Only called for providers that declare /// the ExpandWildcards capability. /// </summary> /// /// <param name="path"> /// The path to expand. Expansion must be consistent with the wildcarding /// rules of PowerShell's WildcardPattern class. /// </param> /// /// <returns> /// A list of provider paths that this path expands to. They must all exist. /// </returns> /// protected virtual string[] ExpandPath(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return new string[] { path }; } } // IsValidPath #endregion Protected methods } // ItemCmdletProvider #endregion ItemCmdletProvider } // namespace System.Management.Automation
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Pathoschild.Stardew.Automate.Framework.Models; using Pathoschild.Stardew.Automate.Framework.Storage; using Pathoschild.Stardew.Common; using StardewValley; using StardewValley.Buildings; using StardewValley.Locations; using StardewValley.Objects; using StardewValley.TerrainFeatures; using SObject = StardewValley.Object; namespace Pathoschild.Stardew.Automate.Framework { /// <summary>Constructs machine groups.</summary> internal class MachineGroupFactory { /********* ** Fields *********/ /// <summary>The automation factories which construct machines, containers, and connectors.</summary> private readonly IList<IAutomationFactory> AutomationFactories = new List<IAutomationFactory>(); /// <summary>Get the configuration for specific machines by ID, if any.</summary> private readonly Func<string, ModConfigMachine> GetMachineOverride; /// <summary>Build a storage manager for the given containers.</summary> private readonly Func<IContainer[], StorageManager> BuildStorage; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="getMachineOverride">Get the configuration for specific machines by ID, if any.</param> /// <param name="buildStorage">Build a storage manager for the given containers.</param> public MachineGroupFactory(Func<string, ModConfigMachine> getMachineOverride, Func<IContainer[], StorageManager> buildStorage) { this.GetMachineOverride = getMachineOverride; this.BuildStorage = buildStorage; } /// <summary>Add an automation factory.</summary> /// <param name="factory">An automation factory which construct machines, containers, and connectors.</param> public void Add(IAutomationFactory factory) { this.AutomationFactories.Add(factory); } /// <summary>Get the unique key which identifies a location.</summary> /// <param name="location">The location instance.</param> public string GetLocationKey(GameLocation location) { return location.uniqueName.Value != null && location.uniqueName.Value != location.Name ? $"{location.Name} ({location.uniqueName.Value})" : location.Name; } /// <summary>Sort machines by priority.</summary> /// <param name="machines">The machines to sort.</param> public IEnumerable<IMachine> SortMachines(IEnumerable<IMachine> machines) { return ( from machine in machines let config = this.GetMachineOverride(machine.MachineTypeID) orderby config?.Priority ?? 0 descending select machine ); } /// <summary>Get all machine groups in a location.</summary> /// <param name="location">The location to search.</param> public IEnumerable<IMachineGroup> GetMachineGroups(GameLocation location) { MachineGroupBuilder builder = new MachineGroupBuilder(this.GetLocationKey(location), this.SortMachines, this.BuildStorage); LocationFloodFillIndex locationIndex = new LocationFloodFillIndex(location); ISet<Vector2> visited = new HashSet<Vector2>(); foreach (Vector2 tile in location.GetTiles()) { this.FloodFillGroup(builder, location, tile, locationIndex, visited); if (builder.HasTiles()) { yield return builder.Build(); builder.Reset(); } } } /// <summary>Get whether an object is automatable.</summary> /// <param name="location">The location to check.</param> /// <param name="tile">The tile to check.</param> /// <param name="obj">The object to check.</param> public bool IsAutomatable(GameLocation location, Vector2 tile, SObject obj) { return this.GetEntityFor(location, tile, obj) != null; } /// <summary>Get whether a terrain feature is automatable.</summary> /// <param name="location">The location to check.</param> /// <param name="tile">The tile to check.</param> /// <param name="terrainFeature">The terrain feature to check.</param> public bool IsAutomatable(GameLocation location, Vector2 tile, TerrainFeature terrainFeature) { return this.GetEntityFor(location, tile, terrainFeature) != null; } /// <summary>Get whether a building is automatable.</summary> /// <param name="location">The location to check.</param> /// <param name="tile">The tile to check.</param> /// <param name="building">The building to check.</param> public bool IsAutomatable(BuildableGameLocation location, Vector2 tile, Building building) { return this.GetEntityFor(location, tile, building) != null; } /// <summary>Get the registered automation factories.</summary> public IEnumerable<IAutomationFactory> GetFactories() { return this.AutomationFactories.Select(p => p); } /********* ** Private methods *********/ /// <summary>Extend the given machine group to include all machines and containers connected to the given tile, if any.</summary> /// <param name="machineGroup">The machine group to extend.</param> /// <param name="location">The location to search.</param> /// <param name="origin">The first tile to check.</param> /// <param name="locationIndex">An indexed view of the location.</param> /// <param name="visited">A lookup of visited tiles.</param> private void FloodFillGroup(MachineGroupBuilder machineGroup, GameLocation location, in Vector2 origin, LocationFloodFillIndex locationIndex, ISet<Vector2> visited) { // skip if already visited if (visited.Contains(origin)) return; // flood-fill connected machines & containers Queue<Vector2> queue = new Queue<Vector2>(); queue.Enqueue(origin); while (queue.Any()) { // get tile Vector2 tile = queue.Dequeue(); if (!visited.Add(tile)) continue; // add machines, containers, or connectors which covers this tile if (this.TryAddEntity(machineGroup, location, locationIndex, tile)) { foreach (Rectangle tileArea in machineGroup.NewTileAreas) { // mark visited foreach (Vector2 cur in tileArea.GetTiles()) visited.Add(cur); // connect entities on surrounding tiles foreach (Vector2 next in tileArea.GetSurroundingTiles()) { if (!visited.Contains(next)) queue.Enqueue(next); } } machineGroup.NewTileAreas.Clear(); } } } /// <summary>Add any machine, container, or connector on the given tile to the machine group.</summary> /// <param name="group">The machine group to extend.</param> /// <param name="location">The location to search.</param> /// <param name="locationIndex">An indexed view of the location.</param> /// <param name="tile">The tile to search.</param> private bool TryAddEntity(MachineGroupBuilder group, GameLocation location, LocationFloodFillIndex locationIndex, in Vector2 tile) { IAutomatable entity = this.GetEntity(location, locationIndex, tile); switch (entity) { case null: return false; case IMachine machine: if (this.GetMachineOverride(machine.MachineTypeID)?.Enabled != false) group.Add(machine); return true; case IContainer container: if (container.StorageAllowed() || container.TakingItemsAllowed()) { group.Add(container); return true; } return false; default: group.Add(entity.TileArea); // connector return true; } } /// <summary>Get a machine, container, or connector from the given tile, if any.</summary> /// <param name="location">The location to search.</param> /// <param name="locationIndex">An indexed view of the location.</param> /// <param name="tile">The tile to search.</param> private IAutomatable GetEntity(GameLocation location, LocationFloodFillIndex locationIndex, Vector2 tile) { // from entity foreach (object target in locationIndex.GetEntities(tile)) { switch (target) { case SObject obj: { IAutomatable entity = this.GetEntityFor(location, tile, obj); if (entity != null) return entity; if (obj is IndoorPot pot && pot.bush.Value != null) { entity = this.GetEntityFor(location, tile, pot.bush.Value); if (entity != null) return entity; } } break; case TerrainFeature feature: { IAutomatable entity = this.GetEntityFor(location, tile, feature); if (entity != null) return entity; } break; case Building building: { IAutomatable entity = this.GetEntityFor((BuildableGameLocation)location, tile, building); if (entity != null) return entity; } break; } } // from tile position foreach (IAutomationFactory factory in this.AutomationFactories) { IAutomatable entity = factory.GetForTile(location, tile); if (entity != null) return entity; } // none found return null; } /// <summary>Get a machine, container, or connector from the given object, if any.</summary> /// <param name="location">The location to search.</param> /// <param name="tile">The tile to search.</param> /// <param name="obj">The object to check.</param> private IAutomatable GetEntityFor(GameLocation location, Vector2 tile, SObject obj) { foreach (IAutomationFactory factory in this.AutomationFactories) { IAutomatable entity = factory.GetFor(obj, location, tile); if (entity != null) return entity; } return null; } /// <summary>Get a machine, container, or connector from the given terrain feature, if any.</summary> /// <param name="location">The location to search.</param> /// <param name="tile">The tile to search.</param> /// <param name="feature">The terrain feature to check.</param> private IAutomatable GetEntityFor(GameLocation location, Vector2 tile, TerrainFeature feature) { foreach (IAutomationFactory factory in this.AutomationFactories) { IAutomatable entity = factory.GetFor(feature, location, tile); if (entity != null) return entity; } return null; } /// <summary>Get a machine, container, or connector from the given building, if any.</summary> /// <param name="location">The location to search.</param> /// <param name="tile">The tile to search.</param> /// <param name="building">The building to check.</param> private IAutomatable GetEntityFor(BuildableGameLocation location, Vector2 tile, Building building) { foreach (IAutomationFactory factory in this.AutomationFactories) { IAutomatable entity = factory.GetFor(building, location, tile); if (entity != null) return entity; } return null; } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace IO.Swagger.Model { /// <summary> /// /// </summary> [DataContract] public class VariableUserSource : IEquatable<VariableUserSource> { /// <summary> /// Initializes a new instance of the <see cref="VariableUserSource" /> class. /// </summary> public VariableUserSource() { } /// <summary> /// ID of User /// </summary> /// <value>ID of User</value> [DataMember(Name="user_id", EmitDefaultValue=false)] public int? UserId { get; set; } /// <summary> /// ID of variable /// </summary> /// <value>ID of variable</value> [DataMember(Name="variable_id", EmitDefaultValue=false)] public int? VariableId { get; set; } /// <summary> /// ID of source /// </summary> /// <value>ID of source</value> [DataMember(Name="source_id", EmitDefaultValue=false)] public int? SourceId { get; set; } /// <summary> /// Time that this measurement occurred Uses epoch minute (epoch time divided by 60) /// </summary> /// <value>Time that this measurement occurred Uses epoch minute (epoch time divided by 60)</value> [DataMember(Name="timestamp", EmitDefaultValue=false)] public int? Timestamp { get; set; } /// <summary> /// Earliest measurement time /// </summary> /// <value>Earliest measurement time</value> [DataMember(Name="earliest_measurement_time", EmitDefaultValue=false)] public int? EarliestMeasurementTime { get; set; } /// <summary> /// Latest measurement time /// </summary> /// <value>Latest measurement time</value> [DataMember(Name="latest_measurement_time", EmitDefaultValue=false)] public int? LatestMeasurementTime { get; set; } /// <summary> /// When the record was first created. Use ISO 8601 datetime format /// </summary> /// <value>When the record was first created. Use ISO 8601 datetime format</value> [DataMember(Name="created_at", EmitDefaultValue=false)] public DateTime? CreatedAt { get; set; } /// <summary> /// When the record in the database was last updated. Use ISO 8601 datetime format /// </summary> /// <value>When the record in the database was last updated. Use ISO 8601 datetime format</value> [DataMember(Name="updated_at", EmitDefaultValue=false)] public DateTime? UpdatedAt { 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 VariableUserSource {\n"); sb.Append(" UserId: ").Append(UserId).Append("\n"); sb.Append(" VariableId: ").Append(VariableId).Append("\n"); sb.Append(" SourceId: ").Append(SourceId).Append("\n"); sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); sb.Append(" EarliestMeasurementTime: ").Append(EarliestMeasurementTime).Append("\n"); sb.Append(" LatestMeasurementTime: ").Append(LatestMeasurementTime).Append("\n"); sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); sb.Append(" UpdatedAt: ").Append(UpdatedAt).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 VariableUserSource); } /// <summary> /// Returns true if VariableUserSource instances are equal /// </summary> /// <param name="obj">Instance of VariableUserSource to be compared</param> /// <returns>Boolean</returns> public bool Equals(VariableUserSource other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.UserId == other.UserId || this.UserId != null && this.UserId.Equals(other.UserId) ) && ( this.VariableId == other.VariableId || this.VariableId != null && this.VariableId.Equals(other.VariableId) ) && ( this.SourceId == other.SourceId || this.SourceId != null && this.SourceId.Equals(other.SourceId) ) && ( this.Timestamp == other.Timestamp || this.Timestamp != null && this.Timestamp.Equals(other.Timestamp) ) && ( this.EarliestMeasurementTime == other.EarliestMeasurementTime || this.EarliestMeasurementTime != null && this.EarliestMeasurementTime.Equals(other.EarliestMeasurementTime) ) && ( this.LatestMeasurementTime == other.LatestMeasurementTime || this.LatestMeasurementTime != null && this.LatestMeasurementTime.Equals(other.LatestMeasurementTime) ) && ( this.CreatedAt == other.CreatedAt || this.CreatedAt != null && this.CreatedAt.Equals(other.CreatedAt) ) && ( this.UpdatedAt == other.UpdatedAt || this.UpdatedAt != null && this.UpdatedAt.Equals(other.UpdatedAt) ); } /// <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.UserId != null) hash = hash * 57 + this.UserId.GetHashCode(); if (this.VariableId != null) hash = hash * 57 + this.VariableId.GetHashCode(); if (this.SourceId != null) hash = hash * 57 + this.SourceId.GetHashCode(); if (this.Timestamp != null) hash = hash * 57 + this.Timestamp.GetHashCode(); if (this.EarliestMeasurementTime != null) hash = hash * 57 + this.EarliestMeasurementTime.GetHashCode(); if (this.LatestMeasurementTime != null) hash = hash * 57 + this.LatestMeasurementTime.GetHashCode(); if (this.CreatedAt != null) hash = hash * 57 + this.CreatedAt.GetHashCode(); if (this.UpdatedAt != null) hash = hash * 57 + this.UpdatedAt.GetHashCode(); return hash; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCustomAudienceServiceClientTest { [Category("Autogenerated")][Test] public void GetCustomAudienceRequestObject() { moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict); GetCustomAudienceRequest request = new GetCustomAudienceRequest { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), }; gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Id = -6774108720365892680L, Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled, CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest, Description = "description2cf9da67", Members = { new gagvr::CustomAudienceMember(), }, }; mockGrpcClient.Setup(x => x.GetCustomAudience(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomAudience response = client.GetCustomAudience(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomAudienceRequestObjectAsync() { moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict); GetCustomAudienceRequest request = new GetCustomAudienceRequest { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), }; gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Id = -6774108720365892680L, Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled, CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest, Description = "description2cf9da67", Members = { new gagvr::CustomAudienceMember(), }, }; mockGrpcClient.Setup(x => x.GetCustomAudienceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomAudience>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomAudience responseCallSettings = await client.GetCustomAudienceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomAudience responseCancellationToken = await client.GetCustomAudienceAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomAudience() { moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict); GetCustomAudienceRequest request = new GetCustomAudienceRequest { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), }; gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Id = -6774108720365892680L, Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled, CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest, Description = "description2cf9da67", Members = { new gagvr::CustomAudienceMember(), }, }; mockGrpcClient.Setup(x => x.GetCustomAudience(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomAudience response = client.GetCustomAudience(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomAudienceAsync() { moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict); GetCustomAudienceRequest request = new GetCustomAudienceRequest { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), }; gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Id = -6774108720365892680L, Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled, CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest, Description = "description2cf9da67", Members = { new gagvr::CustomAudienceMember(), }, }; mockGrpcClient.Setup(x => x.GetCustomAudienceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomAudience>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomAudience responseCallSettings = await client.GetCustomAudienceAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomAudience responseCancellationToken = await client.GetCustomAudienceAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomAudienceResourceNames() { moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict); GetCustomAudienceRequest request = new GetCustomAudienceRequest { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), }; gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Id = -6774108720365892680L, Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled, CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest, Description = "description2cf9da67", Members = { new gagvr::CustomAudienceMember(), }, }; mockGrpcClient.Setup(x => x.GetCustomAudience(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomAudience response = client.GetCustomAudience(request.ResourceNameAsCustomAudienceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomAudienceResourceNamesAsync() { moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict); GetCustomAudienceRequest request = new GetCustomAudienceRequest { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), }; gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience { ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Id = -6774108720365892680L, Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled, CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"), Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest, Description = "description2cf9da67", Members = { new gagvr::CustomAudienceMember(), }, }; mockGrpcClient.Setup(x => x.GetCustomAudienceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomAudience>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomAudience responseCallSettings = await client.GetCustomAudienceAsync(request.ResourceNameAsCustomAudienceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomAudience responseCancellationToken = await client.GetCustomAudienceAsync(request.ResourceNameAsCustomAudienceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomAudiencesRequestObject() { moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict); MutateCustomAudiencesRequest request = new MutateCustomAudiencesRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomAudienceOperation(), }, ValidateOnly = true, }; MutateCustomAudiencesResponse expectedResponse = new MutateCustomAudiencesResponse { Results = { new MutateCustomAudienceResult(), }, }; mockGrpcClient.Setup(x => x.MutateCustomAudiences(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null); MutateCustomAudiencesResponse response = client.MutateCustomAudiences(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomAudiencesRequestObjectAsync() { moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict); MutateCustomAudiencesRequest request = new MutateCustomAudiencesRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomAudienceOperation(), }, ValidateOnly = true, }; MutateCustomAudiencesResponse expectedResponse = new MutateCustomAudiencesResponse { Results = { new MutateCustomAudienceResult(), }, }; mockGrpcClient.Setup(x => x.MutateCustomAudiencesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomAudiencesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null); MutateCustomAudiencesResponse responseCallSettings = await client.MutateCustomAudiencesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomAudiencesResponse responseCancellationToken = await client.MutateCustomAudiencesAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomAudiences() { moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict); MutateCustomAudiencesRequest request = new MutateCustomAudiencesRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomAudienceOperation(), }, }; MutateCustomAudiencesResponse expectedResponse = new MutateCustomAudiencesResponse { Results = { new MutateCustomAudienceResult(), }, }; mockGrpcClient.Setup(x => x.MutateCustomAudiences(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null); MutateCustomAudiencesResponse response = client.MutateCustomAudiences(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomAudiencesAsync() { moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict); MutateCustomAudiencesRequest request = new MutateCustomAudiencesRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomAudienceOperation(), }, }; MutateCustomAudiencesResponse expectedResponse = new MutateCustomAudiencesResponse { Results = { new MutateCustomAudienceResult(), }, }; mockGrpcClient.Setup(x => x.MutateCustomAudiencesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomAudiencesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null); MutateCustomAudiencesResponse responseCallSettings = await client.MutateCustomAudiencesAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomAudiencesResponse responseCancellationToken = await client.MutateCustomAudiencesAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Xml; using Google.GData.Client; namespace Google.GData.Extensions { /// <summary> /// GData schema extension describing a reminder on an event. /// </summary> /// <remarks> /// <para>You can represent a set of reminders where each has a (1) reminder /// period and (2) notification method. The method can be either "sms", /// "email", "alert", "none", "all".</para> /// /// <para>The meaning of this set of reminders differs based on whether you /// are reading or writing feeds. When reading, the set of reminders /// returned on an event takes into account both defaults on a /// parent recurring event (when applicable) as well as the user's /// defaults on calendar. If there are no gd:reminders returned that /// means the event has absolutely no reminders. "none" or "all" will /// not apply in this case.</para> /// /// <para>Writing is different because we have to be backwards-compatible /// (see *) with the old way of setting reminders. For easier analysis /// we describe all the behaviors defined in the table below. (Notice /// we only include cases for minutes, as the other cases specified in /// terms of days/hours/absoluteTime can be converted to this case.)</para> /// /// <para>Notice method is case-sensitive: must be in lowercase!</para> /// /// <list type="table"> /// <listheader> /// <term></term> /// <term>No method or method=all</term> /// <term>method=none</term> /// <term>method=email|sms|alert</term> /// </listheader> /// <item> /// <term>No gd:rem</term> /// <term>*No reminder</term> /// <term>N/A</term> /// <term>N/A</term> /// </item> /// <item> /// <term>1 gd:rem</term> /// <term>*Use user's default settings</term> /// <term>No reminder</term> /// <term>InvalidEntryException</term> /// </item> /// <item> /// <term>1 gd:rem min=0</term> /// <term>*Use user's default settings</term> /// <term>No reminder</term> /// <term>InvalidEntryException</term> /// </item> /// <item> /// <term>1 gd:rem min=-1</term> /// <term>*No reminder</term> /// <term>No reminder</term> /// <term>InvalidEntryException</term> /// </item> /// <item> /// <term>1 gd:rem min=+n</term> /// <term>*Override with no +n for user's selected methods</term> /// <term>No reminder</term> /// <term>Set exactly one reminder on event at +n with given method</term> /// </item> /// <item> /// <term>Multiple gd:rem</term> /// <term>InvalidEntryException</term> /// <term>InvalidEntryException</term> /// <term>Copy this set exactly</term> /// </item> /// </list> /// /// <para>Hence, to override an event with a set of reminder time, method /// pairs, just specify them exactly. To clear an event of all /// overrides (and go back to inheriting the user's defaults), one can /// simply specify a single gd:reminder with no extra attributes. To /// have NO event reminders on an event, either set a single /// gd:reminder with negative reminder time, or simply update the event /// with a single gd:reminder method=none.</para> /// </remarks> public class Reminder : IExtensionElementFactory { /// <summary> /// the different reminder methods available /// </summary> public enum ReminderMethod { /// <summary> /// visible alert /// </summary> alert, /// <summary> /// all alerts /// </summary> all, /// <summary> /// alert per email /// </summary> email, /// <summary> /// no aert /// </summary> none, /// <summary> /// alert per SMS /// </summary> sms, /// <summary> /// no alert specified (invalid) /// </summary> unspecified }; /// <summary> /// holds the method type /// </summary> public ReminderMethod Method { get; set; } /// <summary> /// Number of days before the event. /// </summary> public int Days { get; set; } /// <summary> /// Number of hours. /// </summary> public int Hours { get; set; } /// <summary> /// Number of minutes. /// </summary> public int Minutes { get; set; } /// <summary> /// Absolute time of the reminder. /// </summary> public DateTime AbsoluteTime { get; set; } /// <summary> /// Persistence method for the Reminder object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace); if (Days > 0) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeDays, Days.ToString()); } if (Hours > 0) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeHours, Hours.ToString()); } if (Minutes > 0) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeMinutes, Minutes.ToString()); } if (AbsoluteTime != new DateTime(1, 1, 1)) { string date = Utilities.LocalDateTimeInUTC(AbsoluteTime); writer.WriteAttributeString(GDataParserNameTable.XmlAttributeAbsoluteTime, date); } if (Method != ReminderMethod.unspecified) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeMethod, Method.ToString()); } writer.WriteEndElement(); } #region [ Overloaded from IExtensionElementFactory ] /// <summary>Parses an xml node to create a Reminder object.</summary> /// <param name="node">the node to parse node</param> /// <param name="parser">the xml parser to use if we need to dive deeper</param> /// <returns>the created Reminder object</returns> public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { Tracing.TraceCall(); Reminder reminder = null; if (node != null) { object localname = node.LocalName; if (!localname.Equals(XmlName) || !node.NamespaceURI.Equals(XmlNameSpace)) { return null; } } reminder = new Reminder(); if (node != null && node.Attributes != null) { if (node.Attributes[GDataParserNameTable.XmlAttributeAbsoluteTime] != null) { try { reminder.AbsoluteTime = DateTime.Parse(node.Attributes[GDataParserNameTable.XmlAttributeAbsoluteTime].Value); } catch (FormatException fe) { throw new ArgumentException("Invalid g:reminder/@absoluteTime.", fe); } } if (node.Attributes[GDataParserNameTable.XmlAttributeDays] != null) { try { reminder.Days = int.Parse(node.Attributes[GDataParserNameTable.XmlAttributeDays].Value); } catch (FormatException fe) { throw new ArgumentException("Invalid g:reminder/@days.", fe); } } if (node.Attributes[GDataParserNameTable.XmlAttributeHours] != null) { try { reminder.Hours = int.Parse(node.Attributes[GDataParserNameTable.XmlAttributeHours].Value); } catch (FormatException fe) { throw new ArgumentException("Invalid g:reminder/@hours.", fe); } } if (node.Attributes[GDataParserNameTable.XmlAttributeMinutes] != null) { try { reminder.Minutes = int.Parse(node.Attributes[GDataParserNameTable.XmlAttributeMinutes].Value); } catch (FormatException fe) { throw new ArgumentException("Invalid g:reminder/@minutes.", fe); } } if (node.Attributes[GDataParserNameTable.XmlAttributeMethod] != null) { try { reminder.Method = (ReminderMethod) Enum.Parse(typeof (ReminderMethod), node.Attributes[GDataParserNameTable.XmlAttributeMethod].Value, true); } catch (Exception e) { throw new ArgumentException("Invalid g:reminder/@method.", e); } } } return reminder; } /// <summary> /// Returns the constant representing this XML element. /// </summary> public string XmlName { get { return GDataParserNameTable.XmlReminderElement; } } /// <summary> /// Returns the constant representing this XML element. /// </summary> public string XmlNameSpace { get { return BaseNameTable.gNamespace; } } /// <summary> /// Returns the constant representing this XML element. /// </summary> public string XmlPrefix { get { return BaseNameTable.gDataPrefix; } } #endregion } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Windows.Media; using Windows.Media.Core; using Windows.Media.Playback; using Windows.Storage; using Plugin.MediaManager.Abstractions; using Plugin.MediaManager.Abstractions.Enums; using Plugin.MediaManager.Abstractions.EventArguments; namespace Plugin.MediaManager { public class AudioPlayerImplementation : IAudioPlayer { private readonly IVolumeManager _volumeManager; private readonly MediaPlayer _player; private readonly Timer _playProgressTimer; private MediaPlayerStatus _status; private IMediaFile _currentMediaFile; public AudioPlayerImplementation(IVolumeManager volumeManager) { _volumeManager = volumeManager; _player = new MediaPlayer(); _playProgressTimer = new Timer(state => { if (_player.PlaybackSession.PlaybackState == MediaPlaybackState.Playing) { var progress = _player.PlaybackSession.Position.TotalSeconds/ _player.PlaybackSession.NaturalDuration.TotalSeconds; if (double.IsInfinity(progress)) progress = 0; PlayingChanged?.Invoke(this, new PlayingChangedEventArgs(progress, _player.PlaybackSession.Position, _player.PlaybackSession.NaturalDuration)); } }, null, 0, int.MaxValue); _player.MediaFailed += (sender, args) => { _status = MediaPlayerStatus.Failed; _playProgressTimer.Change(0, int.MaxValue); MediaFailed?.Invoke(this, new MediaFailedEventArgs(args.ErrorMessage, args.ExtendedErrorCode)); }; _player.PlaybackSession.PlaybackStateChanged += (sender, args) => { switch (sender.PlaybackState) { case MediaPlaybackState.None: _playProgressTimer.Change(0, int.MaxValue); break; case MediaPlaybackState.Opening: Status = MediaPlayerStatus.Loading; _playProgressTimer.Change(0, int.MaxValue); break; case MediaPlaybackState.Buffering: Status = MediaPlayerStatus.Buffering; _playProgressTimer.Change(0, int.MaxValue); break; case MediaPlaybackState.Playing: if (sender.PlaybackRate <= 0 && sender.Position == TimeSpan.Zero) { Status = MediaPlayerStatus.Stopped; } else { Status = MediaPlayerStatus.Playing; _playProgressTimer.Change(0, 50); } break; case MediaPlaybackState.Paused: Status = MediaPlayerStatus.Paused; _playProgressTimer.Change(0, int.MaxValue); break; default: throw new ArgumentOutOfRangeException(); } }; _player.MediaEnded += (sender, args) => { MediaFinished?.Invoke(this, new MediaFinishedEventArgs(_currentMediaFile)); }; _player.PlaybackSession.BufferingStarted += (sender, args) => { var bufferedTime = TimeSpan.FromSeconds(sender.BufferingProgress * sender.NaturalDuration.TotalSeconds); BufferingChanged?.Invoke(this, new BufferingChangedEventArgs(sender.BufferingProgress, bufferedTime)); }; _player.PlaybackSession.BufferingProgressChanged += (sender, args) => { //This seems not to be fired at all var bufferedTime = TimeSpan.FromSeconds(_player.PlaybackSession.BufferingProgress* _player.PlaybackSession.NaturalDuration.TotalSeconds); BufferingChanged?.Invoke(this, new BufferingChangedEventArgs(_player.PlaybackSession.BufferingProgress, bufferedTime)); }; _player.PlaybackSession.SeekCompleted += (sender, args) => { }; int.TryParse((_player.Volume * 100).ToString(), out var vol); _volumeManager.CurrentVolume = vol; _volumeManager.Muted = _player.IsMuted; _volumeManager.VolumeChanged += VolumeManagerOnVolumeChanged; } private void VolumeManagerOnVolumeChanged(object sender, VolumeChangedEventArgs volumeChangedEventArgs) { _player.Volume = (double) volumeChangedEventArgs.NewVolume; _player.IsMuted = volumeChangedEventArgs.Muted; } public Dictionary<string, string> RequestHeaders { get; set; } public MediaPlayerStatus Status { get { return _status; } private set { _status = value; StatusChanged?.Invoke(this, new StatusChangedEventArgs(_status)); } } public event StatusChangedEventHandler StatusChanged; public event PlayingChangedEventHandler PlayingChanged; public event BufferingChangedEventHandler BufferingChanged; public event MediaFinishedEventHandler MediaFinished; public event MediaFailedEventHandler MediaFailed; public TimeSpan Buffered { get { if (_player == null) return TimeSpan.Zero; return TimeSpan.FromMilliseconds(_player.PlaybackSession.BufferingProgress* _player.PlaybackSession.NaturalDuration.TotalMilliseconds); } } public TimeSpan Duration => _player?.PlaybackSession.NaturalDuration ?? TimeSpan.Zero; public TimeSpan Position => _player?.PlaybackSession.Position ?? TimeSpan.Zero; public Task Pause() { if (_player.PlaybackSession.PlaybackState == MediaPlaybackState.Paused) _player.Play(); else _player.Pause(); return Task.CompletedTask; } public async Task PlayPause() { if ((_status == MediaPlayerStatus.Paused) || (_status == MediaPlayerStatus.Stopped)) await Play(); else await Pause(); } public async Task Play(IMediaFile mediaFile = null) { try { var sameMediaFile = mediaFile == null || mediaFile.Equals(_currentMediaFile); var currentMediaPosition = _player.PlaybackSession?.Position; // This variable will determine whether you will resume your playback or not var resumeMediaFile = Status == MediaPlayerStatus.Paused && sameMediaFile || currentMediaPosition?.TotalSeconds > 0 && sameMediaFile; if(resumeMediaFile) { // TODO: PlaybackRate needs to be configurable rather than hard-coded here //_player.PlaybackSession.PlaybackRate = 1; _player.Play(); return; } if (mediaFile != null) { _currentMediaFile = mediaFile; var mediaPlaybackList = new MediaPlaybackList(); var mediaSource = await CreateMediaSource(mediaFile); var item = new MediaPlaybackItem(mediaSource); mediaPlaybackList.Items.Add(item); _player.Source = mediaPlaybackList; _player.Play(); } } catch (Exception e) { MediaFailed?.Invoke(this, new MediaFailedEventArgs("Unable to start playback", e)); Status = MediaPlayerStatus.Stopped; } } public async Task Seek(TimeSpan position) { _player.PlaybackSession.Position = position; await Task.CompletedTask; } public Task Stop() { _player.PlaybackSession.PlaybackRate = 0; _player.PlaybackSession.Position = TimeSpan.Zero; Status = MediaPlayerStatus.Stopped; return Task.CompletedTask; } private async Task<MediaSource> CreateMediaSource(IMediaFile mediaFile) { switch (mediaFile.Availability) { case ResourceAvailability.Remote: return MediaSource.CreateFromUri(new Uri(mediaFile.Url)); case ResourceAvailability.Local: var du = _player.SystemMediaTransportControls.DisplayUpdater; var storageFile = await StorageFile.GetFileFromPathAsync(mediaFile.Url); var playbackType = mediaFile.Type == MediaFileType.Audio ? MediaPlaybackType.Music : MediaPlaybackType.Video; await du.CopyFromFileAsync(playbackType, storageFile); du.Update(); return MediaSource.CreateFromStorageFile(storageFile); } return MediaSource.CreateFromUri(new Uri(mediaFile.Url)); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Win32; namespace TestUtilities { public class PythonPaths { const string PythonCorePath = "SOFTWARE\\Python\\PythonCore"; public static readonly Guid CPythonGuid = new Guid("{2AF0F10D-7135-4994-9156-5D01C9C11B7E}"); public static readonly Guid CPython64Guid = new Guid("{9A7A9026-48C1-4688-9D5D-E5699D47D074}"); public static readonly Guid IronPythonGuid = new Guid("{80659AB7-4D53-4E0C-8588-A766116CBD46}"); public static readonly Guid IronPython64Guid = new Guid("{FCC291AA-427C-498C-A4D7-4502D6449B8C}"); // Not currently used for auto-detection public static readonly Guid JythonGuid = new Guid("{844BA471-72F7-431B-AA3F-675AFD18E230}"); public static readonly PythonVersion Python25 = GetCPythonVersion(PythonLanguageVersion.V25); public static readonly PythonVersion Python26 = GetCPythonVersion(PythonLanguageVersion.V26); public static readonly PythonVersion Python27 = GetCPythonVersion(PythonLanguageVersion.V27); public static readonly PythonVersion Python30 = GetCPythonVersion(PythonLanguageVersion.V30); public static readonly PythonVersion Python31 = GetCPythonVersion(PythonLanguageVersion.V31); public static readonly PythonVersion Python32 = GetCPythonVersion(PythonLanguageVersion.V32); public static readonly PythonVersion Python33 = GetCPythonVersion(PythonLanguageVersion.V33); public static readonly PythonVersion Python34 = GetCPythonVersion(PythonLanguageVersion.V34); public static readonly PythonVersion Python35 = GetCPythonVersion(PythonLanguageVersion.V35); public static readonly PythonVersion IronPython27 = GetIronPythonVersion(false); public static readonly PythonVersion Python25_x64 = GetCPythonVersion(PythonLanguageVersion.V25, true); public static readonly PythonVersion Python26_x64 = GetCPythonVersion(PythonLanguageVersion.V26, true); public static readonly PythonVersion Python27_x64 = GetCPythonVersion(PythonLanguageVersion.V27, true); public static readonly PythonVersion Python30_x64 = GetCPythonVersion(PythonLanguageVersion.V30, true); public static readonly PythonVersion Python31_x64 = GetCPythonVersion(PythonLanguageVersion.V31, true); public static readonly PythonVersion Python32_x64 = GetCPythonVersion(PythonLanguageVersion.V32, true); public static readonly PythonVersion Python33_x64 = GetCPythonVersion(PythonLanguageVersion.V33, true); public static readonly PythonVersion Python34_x64 = GetCPythonVersion(PythonLanguageVersion.V34, true); public static readonly PythonVersion Python35_x64 = GetCPythonVersion(PythonLanguageVersion.V35, true); public static readonly PythonVersion IronPython27_x64 = GetIronPythonVersion(true); public static readonly PythonVersion Jython27 = GetJythonVersion(PythonLanguageVersion.V27); private static PythonVersion GetIronPythonVersion(bool x64) { var exeName = x64 ? "ipy64.exe" : "ipy.exe"; using (var ipy = Registry.LocalMachine.OpenSubKey("SOFTWARE\\IronPython")) { if (ipy != null) { using (var twoSeven = ipy.OpenSubKey("2.7")) { if (twoSeven != null) { var installPath = twoSeven.OpenSubKey("InstallPath"); if (installPath != null) { var res = installPath.GetValue("") as string; if (res != null) { return new PythonVersion( Path.Combine(res, exeName), PythonLanguageVersion.V27, x64 ? IronPython64Guid : IronPythonGuid ); } } } } } } var ver = new PythonVersion("C:\\Program Files (x86)\\IronPython 2.7\\" + exeName, PythonLanguageVersion.V27, IronPythonGuid); if (File.Exists(ver.InterpreterPath)) { return ver; } return null; } private static PythonVersion GetCPythonVersion(PythonLanguageVersion version, bool x64 = false) { if (!x64) { foreach (var baseKey in new[] { Registry.LocalMachine, Registry.CurrentUser }) { using (var python = baseKey.OpenSubKey(PythonCorePath)) { var res = TryGetCPythonPath(version, python, x64); if (res != null) { return res; } } } } if (Environment.Is64BitOperatingSystem && x64) { foreach (var baseHive in new[] { RegistryHive.LocalMachine, RegistryHive.CurrentUser }) { var python64 = RegistryKey.OpenBaseKey(baseHive, RegistryView.Registry64).OpenSubKey(PythonCorePath); var res = TryGetCPythonPath(version, python64, x64); if (res != null) { return res; } } } var path = "C:\\Python" + version.ToString().Substring(1) + "\\python.exe"; var arch = NativeMethods.GetBinaryType(path); if (arch == ProcessorArchitecture.X86 && !x64) { return new PythonVersion(path, version, CPythonGuid); } else if (arch == ProcessorArchitecture.Amd64 && x64) { return new PythonVersion(path, version, CPython64Guid); } if (x64) { path = "C:\\Python" + version.ToString().Substring(1) + "_x64\\python.exe"; arch = NativeMethods.GetBinaryType(path); if (arch == ProcessorArchitecture.Amd64) { return new PythonVersion(path, version, CPython64Guid); } } return null; } private static PythonVersion TryGetCPythonPath(PythonLanguageVersion version, RegistryKey python, bool x64) { if (python != null) { string versionStr = version.ToString().Substring(1); versionStr = versionStr[0] + "." + versionStr[1]; if (!x64 && version >= PythonLanguageVersion.V35) { versionStr += "-32"; } using (var versionKey = python.OpenSubKey(versionStr + "\\InstallPath")) { if (versionKey != null) { var installPath = versionKey.GetValue(""); if (installPath != null) { var path = Path.Combine(installPath.ToString(), "python.exe"); var arch = NativeMethods.GetBinaryType(path); if (arch == ProcessorArchitecture.X86) { return x64 ? null : new PythonVersion(path, version, CPythonGuid); } else if (arch == ProcessorArchitecture.Amd64) { return x64 ? new PythonVersion(path, version, CPython64Guid) : null; } else { return null; } } } } } return null; } private static PythonVersion GetJythonVersion(PythonLanguageVersion version) { var candidates = new List<DirectoryInfo>(); var ver = version.ToVersion(); var path1 = string.Format("jython{0}{1}*", ver.Major, ver.Minor); var path2 = string.Format("jython{0}.{1}*", ver.Major, ver.Minor); foreach (var drive in DriveInfo.GetDrives()) { if (drive.DriveType != DriveType.Fixed) { continue; } try { candidates.AddRange(drive.RootDirectory.EnumerateDirectories(path1)); candidates.AddRange(drive.RootDirectory.EnumerateDirectories(path2)); } catch { } } foreach (var dir in candidates) { var interpreter = dir.EnumerateFiles("jython.bat").FirstOrDefault(); if (interpreter == null) { continue; } var libPath = dir.EnumerateDirectories("Lib").FirstOrDefault(); if (libPath == null || !libPath.EnumerateFiles("site.py").Any()) { continue; } return new PythonVersion(interpreter.FullName, version, JythonGuid); } return null; } public static IEnumerable<PythonVersion> Versions { get { if (Python25 != null) yield return Python25; if (Python26 != null) yield return Python26; if (Python27 != null) yield return Python27; if (Python30 != null) yield return Python30; if (Python31 != null) yield return Python31; if (Python32 != null) yield return Python32; if (Python33 != null) yield return Python33; if (Python34 != null) yield return Python34; if (Python35 != null) yield return Python35; if (IronPython27 != null) yield return IronPython27; if (Python25_x64 != null) yield return Python25_x64; if (Python26_x64 != null) yield return Python26_x64; if (Python27_x64 != null) yield return Python27_x64; if (Python30_x64 != null) yield return Python30_x64; if (Python31_x64 != null) yield return Python31_x64; if (Python32_x64 != null) yield return Python32_x64; if (Python33_x64 != null) yield return Python33_x64; if (Python34_x64 != null) yield return Python34_x64; if (Python35_x64 != null) yield return Python35_x64; if (IronPython27_x64 != null) yield return IronPython27_x64; if (Jython27 != null) yield return Jython27; } } static class NativeMethods { [DllImport("kernel32", EntryPoint = "GetBinaryTypeW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] private static extern bool _GetBinaryType(string lpApplicationName, out GetBinaryTypeResult lpBinaryType); private enum GetBinaryTypeResult : uint { SCS_32BIT_BINARY = 0, SCS_DOS_BINARY = 1, SCS_WOW_BINARY = 2, SCS_PIF_BINARY = 3, SCS_POSIX_BINARY = 4, SCS_OS216_BINARY = 5, SCS_64BIT_BINARY = 6 } public static ProcessorArchitecture GetBinaryType(string path) { GetBinaryTypeResult result; if (_GetBinaryType(path, out result)) { switch (result) { case GetBinaryTypeResult.SCS_32BIT_BINARY: return ProcessorArchitecture.X86; case GetBinaryTypeResult.SCS_64BIT_BINARY: return ProcessorArchitecture.Amd64; case GetBinaryTypeResult.SCS_DOS_BINARY: case GetBinaryTypeResult.SCS_WOW_BINARY: case GetBinaryTypeResult.SCS_PIF_BINARY: case GetBinaryTypeResult.SCS_POSIX_BINARY: case GetBinaryTypeResult.SCS_OS216_BINARY: default: break; } } return ProcessorArchitecture.None; } } } public class PythonVersion { public readonly string InterpreterPath; public readonly PythonLanguageVersion Version; public readonly Guid Id; public readonly bool IsCPython; public readonly bool IsIronPython; public readonly bool Isx64; public PythonVersion(string path, PythonLanguageVersion pythonLanguageVersion, Guid id) { InterpreterPath = path; Version = pythonLanguageVersion; Id = id; IsCPython = (Id == PythonPaths.CPythonGuid || Id == PythonPaths.CPython64Guid); Isx64 = (Id == PythonPaths.CPython64Guid || Id == PythonPaths.IronPython64Guid); IsIronPython = (Id == PythonPaths.IronPythonGuid || Id == PythonPaths.IronPython64Guid); } public override string ToString() { return string.Format( "{0}Python {1} {2}", IsCPython ? "C" : IsIronPython ? "Iron" : "Other ", Version, Isx64 ? "x64" : "x86" ); } public string PrefixPath { get { return Path.GetDirectoryName(InterpreterPath); } } public string LibPath { get { return Path.Combine(PrefixPath, "Lib"); } } public InterpreterConfiguration Configuration { get { return new InterpreterConfiguration( PrefixPath, InterpreterPath, null, LibPath, "PYTHONPATH", Isx64 ? ProcessorArchitecture.Amd64 : ProcessorArchitecture.X86, Version.ToVersion() ); } } } public static class PythonVersionExtensions { public static void AssertInstalled(this PythonVersion self) { if(self == null || !File.Exists(self.InterpreterPath)) { Assert.Inconclusive("Python interpreter not installed"); } } } }
// 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 defines behaviors specific to a writing system. // A writing system is the collection of scripts and // orthographic rules required to represent a language as text. // // //////////////////////////////////////////////////////////////////////////// using System; using System.Diagnostics; namespace System.Globalization { public class StringInfo { private string _str; private int[] _indexes; // Legacy constructor public StringInfo() : this("") { } // Primary, useful constructor public StringInfo(string value) { this.String = value; } public override bool Equals(object value) { if (value is StringInfo that) { return (_str.Equals(that._str)); } return (false); } public override int GetHashCode() { return _str.GetHashCode(); } // Our zero-based array of index values into the string. Initialize if // our private array is not yet, in fact, initialized. private int[] Indexes { get { if ((null == _indexes) && (0 < this.String.Length)) { _indexes = StringInfo.ParseCombiningCharacters(this.String); } return (_indexes); } } public string String { get { return (_str); } set { if (null == value) { throw new ArgumentNullException(nameof(String), SR.ArgumentNull_String); } _str = value; _indexes = null; } } public int LengthInTextElements { get { if (null == this.Indexes) { // Indexes not initialized, so assume length zero return (0); } return (this.Indexes.Length); } } public string SubstringByTextElements(int startingTextElement) { // If the string is empty, no sense going further. if (null == this.Indexes) { // Just decide which error to give depending on the param they gave us.... if (startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum); } else { throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException); } } return (SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement)); } public string SubstringByTextElements(int startingTextElement, int lengthInTextElements) { if (startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum); } if (this.String.Length == 0 || startingTextElement >= Indexes.Length) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException); } if (lengthInTextElements < 0) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.ArgumentOutOfRange_NeedPosNum); } if (startingTextElement > Indexes.Length - lengthInTextElements) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.Arg_ArgumentOutOfRangeException); } int start = Indexes[startingTextElement]; if (startingTextElement + lengthInTextElements == Indexes.Length) { // We are at the last text element in the string and because of that // must handle the call differently. return (this.String.Substring(start)); } else { return (this.String.Substring(start, (Indexes[lengthInTextElements + startingTextElement] - start))); } } public static string GetNextTextElement(string str) { return (GetNextTextElement(str, 0)); } //////////////////////////////////////////////////////////////////////// // // Get the code point count of the current text element. // // A combining class is defined as: // A character/surrogate that has the following Unicode category: // * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT) // * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA) // * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE) // // In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as: // // 1. If a character/surrogate is in the following category, it is a text element. // It can NOT further combine with characters in the combinging class to form a text element. // * one of the Unicode category in the combinging class // * UnicodeCategory.Format // * UnicodeCateogry.Control // * UnicodeCategory.OtherNotAssigned // 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element. // // Return: // The length of the current text element // // Parameters: // String str // index The starting index // len The total length of str (to define the upper boundary) // ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element. // currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element. // //////////////////////////////////////////////////////////////////////// internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount) { Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); if (index + currentCharCount == len) { // This is the last character/surrogate in the string. return (currentCharCount); } // Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not. int nextCharCount; UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount); if (CharUnicodeInfo.IsCombiningCategory(ucNext)) { // The next element is a combining class. // Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category, // not a format character, and not a control character). if (CharUnicodeInfo.IsCombiningCategory(ucCurrent) || (ucCurrent == UnicodeCategory.Format) || (ucCurrent == UnicodeCategory.Control) || (ucCurrent == UnicodeCategory.OtherNotAssigned) || (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate { // Will fall thru and return the currentCharCount } else { int startIndex = index; // Remember the current index. // We have a valid base characters, and we have a character (or surrogate) that is combining. // Check if there are more combining characters to follow. // Check if the next character is a nonspacing character. index += currentCharCount + nextCharCount; while (index < len) { ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount); if (!CharUnicodeInfo.IsCombiningCategory(ucNext)) { ucCurrent = ucNext; currentCharCount = nextCharCount; break; } index += nextCharCount; } return (index - startIndex); } } // The return value will be the currentCharCount. int ret = currentCharCount; ucCurrent = ucNext; // Update currentCharCount. currentCharCount = nextCharCount; return (ret); } // Returns the str containing the next text element in str starting at // index index. If index is not supplied, then it will start at the beginning // of str. It recognizes a base character plus one or more combining // characters or a properly formed surrogate pair as a text element. See also // the ParseCombiningCharacters() and the ParseSurrogates() methods. public static string GetNextTextElement(string str, int index) { // // Validate parameters. // if (str == null) { throw new ArgumentNullException(nameof(str)); } int len = str.Length; if (index < 0 || index >= len) { if (index == len) { return (string.Empty); } throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } int charLen; UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen); return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen))); } public static TextElementEnumerator GetTextElementEnumerator(string str) { return (GetTextElementEnumerator(str, 0)); } public static TextElementEnumerator GetTextElementEnumerator(string str, int index) { // // Validate parameters. // if (str == null) { throw new ArgumentNullException(nameof(str)); } int len = str.Length; if (index < 0 || (index > len)) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } return (new TextElementEnumerator(str, index, len)); } /* * Returns the indices of each base character or properly formed surrogate pair * within the str. It recognizes a base character plus one or more combining * characters or a properly formed surrogate pair as a text element and returns * the index of the base character or high surrogate. Each index is the * beginning of a text element within a str. The length of each element is * easily computed as the difference between successive indices. The length of * the array will always be less than or equal to the length of the str. For * example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would * return the indices: 0, 2, 4. */ public static int[] ParseCombiningCharacters(string str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } int len = str.Length; int[] result = new int[len]; if (len == 0) { return (result); } int resultCount = 0; int i = 0; int currentCharLen; UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen); while (i < len) { result[resultCount++] = i; i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen); } if (resultCount < len) { int[] returnArray = new int[resultCount]; Array.Copy(result, 0, returnArray, 0, resultCount); return (returnArray); } return (result); } } }
// // WorkingSet.cs // // Author: // Evan Reidland <[email protected]> // // Copyright (c) 2014 Evan Reidland // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using System.Text; using TaskMaster.SimpleJSON; namespace TaskMaster.IO { public class FileList : IReadWriteJSON { //Attempt to protect against potential requests that would get files on disk out of bounds. public static bool IsPathSafe(string path) { return path != null && !Path.IsPathRooted(path) && !path.Contains("~") && !path.Contains(".."); } public static void CreatePathForFile(string filePath) { try { int slashIndex = filePath.LastIndexOf('/'); string directory = filePath; if (slashIndex != -1 && slashIndex < filePath.Length) directory = directory.Substring(0, slashIndex); Directory.CreateDirectory(directory); } catch (Exception e) { Log.Default.Exception(e); } } private MD5 _md5 = MD5.Create(); private Dictionary<string, string> _filesByHash = new Dictionary<string, string>(); public string BaseDirectory { get; private set; } public void Clear() { lock (_filesByHash) _filesByHash.Clear(); } public void CalculateFromDirectory(string path, string pattern = null) { BaseDirectory = path.Replace('\\', '/'); if (string.IsNullOrEmpty(pattern)) pattern = "*"; string[] files = Directory.GetFiles(path, pattern, SearchOption.AllDirectories); foreach (var file in files) { try { string filePath = file.Replace('\\', '/'); byte[] fileData = File.ReadAllBytes(filePath); string hash = BitConverter.ToString(_md5.ComputeHash(fileData)).Replace("-", ""); int length = BaseDirectory.Length; if (!BaseDirectory.EndsWith("/")) length++; filePath = filePath.Substring(length); lock (_filesByHash) _filesByHash[filePath] = hash; Log.Default.Info("File: {0} Hash: {1}", filePath, hash); } catch (Exception e) { Log.Default.Exception(e); } } } public bool HasFile(string name) { return _filesByHash.ContainsKey(name); } public string GetHash(string name) { string hash; _filesByHash.TryGetValue(name, out hash); return hash; } public byte[] ReadFile(string name) { if (IsPathSafe(name)) { try { return File.ReadAllBytes(Path.Combine(BaseDirectory, name)); } catch (Exception e) { Log.Default.Exception(e); } } else Log.Default.Error("Attempted to read unsafe file: {0}", name); return null; } public void WriteFile(string name, string hash, byte[] binary) { string fullPath = Path.Combine(BaseDirectory, name); CreatePathForFile(fullPath); string actualHash = BitConverter.ToString(_md5.ComputeHash(binary)).Replace("-", ""); if (actualHash != hash) Log.Default.Warning("Hash for file {0} does not match the associated hash. {1} != {2}", name, actualHash, hash); _filesByHash[name] = actualHash; File.WriteAllBytes(fullPath, binary); } public List<string> GetRequiredFiles(FileList other) { List<string> missing = new List<string>(); if (other != null) { lock (_filesByHash) { foreach (var filePair in other._filesByHash) { string hash; if (!File.Exists(BaseDirectory + filePair.Key) || !_filesByHash.TryGetValue(filePair.Key, out hash) || hash != filePair.Value) missing.Add(filePair.Key); } } } else missing.AddRange(_filesByHash.Keys); return missing; } public JSONNode SaveToJSON() { JSONClass node = new JSONClass(); JSONClass fileHashes = new JSONClass(); lock (_filesByHash) { foreach (var filePair in _filesByHash) fileHashes[filePair.Key] = filePair.Value.ToString(); } node["files"] = fileHashes; return node; } public void LoadFromJSON(JSONNode node) { if (node != null) { var files = node["files"]; if (files != null && files is JSONClass) { lock (_filesByHash) { foreach (KeyValuePair<string, JSONNode> pair in files as JSONClass) _filesByHash[pair.Key] = pair.Value; } } else { if (files == null) Log.Default.Error("Can't load files list because the node does not contain it."); else Log.Default.Error("Can't load files because files node is not a JSONClass"); } } } public void LoadFromFile(string fileName) { try { LoadFromFile(JSON.Parse(File.ReadAllText(fileName))); } catch (Exception e) { Log.Default.Exception(e); } } public void SaveToFile(string fileName) { File.WriteAllText(fileName, SaveToJSON().ToString(), System.Text.Encoding.UTF8); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using achihapi.ViewModels; using System.Data; using System.Data.SqlClient; using achihapi.Utilities; using System.Net; using Microsoft.Extensions.Caching.Memory; namespace achihapi.Controllers { [Produces("application/json")] [Route("api/FinanceADPTmpDoc")] public class FinanceADPTmpDocController : Controller { private IMemoryCache _cache; public FinanceADPTmpDocController(IMemoryCache cache) { _cache = cache; } // GET: api/FinanceADPTmpDoc [HttpGet] [Authorize] public async Task<IActionResult> Get([FromQuery]Int32 hid, Boolean skipPosted = true, DateTime? dtbgn = null, DateTime? dtend = null) { if (hid <= 0) return BadRequest("No HID inputted"); String usrName = String.Empty; if (Startup.UnitTestMode) usrName = UnitTestUtility.UnitTestUser; else { var usrObj = HIHAPIUtility.GetUserClaim(this); usrName = usrObj.Value; } if (String.IsNullOrEmpty(usrName)) return BadRequest("User cannot recognize"); List<FinanceTmpDocDPViewModel> listVm = new List<FinanceTmpDocDPViewModel>(); SqlConnection conn = null; SqlCommand cmd = null; SqlDataReader reader = null; String queryString = ""; String strErrMsg = ""; HttpStatusCode errorCode = HttpStatusCode.OK; try { queryString = HIHDBUtility.getFinanceDocADPListQueryString() + " WHERE [HID] = @hid "; if (skipPosted) queryString += " AND [REFDOCID] IS NULL "; if (dtbgn.HasValue) queryString += " AND [TRANDATE] >= @dtbgn "; if (dtend.HasValue) queryString += " AND [TRANDATE] <= @dtend "; queryString += " ORDER BY [TRANDATE] DESC"; using(conn = new SqlConnection(Startup.DBConnectionString)) { await conn.OpenAsync(); // Check Home assignment with current user try { HIHAPIUtility.CheckHIDAssignment(conn, hid, usrName); } catch (Exception) { errorCode = HttpStatusCode.BadRequest; throw; } cmd = new SqlCommand(queryString, conn); cmd.Parameters.AddWithValue("@hid", hid); if (dtbgn.HasValue) cmd.Parameters.AddWithValue("@dtbgn", dtbgn.Value); if (dtbgn.HasValue) cmd.Parameters.AddWithValue("@dtend", dtend.Value); reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { FinanceTmpDocDPViewModel dpvm = new FinanceTmpDocDPViewModel(); HIHDBUtility.FinTmpDocADP_DB2VM(reader, dpvm); listVm.Add(dpvm); } } } } catch (Exception exp) { System.Diagnostics.Debug.WriteLine(exp.Message); strErrMsg = exp.Message; if (errorCode == HttpStatusCode.OK) errorCode = HttpStatusCode.InternalServerError; } finally { if (reader != null) { reader.Dispose(); reader = null; } if (cmd != null) { cmd.Dispose(); cmd = null; } if (conn != null) { conn.Dispose(); conn = null; } } if (errorCode != HttpStatusCode.OK) { switch (errorCode) { case HttpStatusCode.Unauthorized: return Unauthorized(); case HttpStatusCode.NotFound: return NotFound(); case HttpStatusCode.BadRequest: return BadRequest(strErrMsg); default: return StatusCode(500, strErrMsg); } } var setting = new Newtonsoft.Json.JsonSerializerSettings { DateFormatString = HIHAPIConstants.DateFormatPattern, ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }; return new JsonResult(listVm, setting); } // GET: api/FinanceADPTmpDoc/5 [HttpGet("{id}")] public IActionResult Get([FromRoute]int id) { return BadRequest(); } // POST: api/FinanceADPTmpDoc [HttpPost] [Authorize] public async Task<IActionResult> Post([FromQuery]Int32 hid, Int32 docid) { // The post here is: // 1. Post a normal document with the content from this template doc // 2. Update the template doc with REFDOCID // Basic check if (hid <= 0|| docid <= 0) { return BadRequest("No data inputted!"); } // Update the database SqlConnection conn = null; SqlCommand cmd = null; SqlDataReader reader = null; SqlTransaction tran = null; String queryString = String.Empty; String strErrMsg = String.Empty; FinanceTmpDocDPViewModel vmTmpDoc = new FinanceTmpDocDPViewModel(); HomeDefViewModel vmHome = new HomeDefViewModel(); FinanceDocumentUIViewModel vmFIDOC = new FinanceDocumentUIViewModel(); HttpStatusCode errorCode = HttpStatusCode.OK; String usrName = String.Empty; if (Startup.UnitTestMode) usrName = UnitTestUtility.UnitTestUser; else { var usrObj = HIHAPIUtility.GetUserClaim(this); usrName = usrObj.Value; } if (String.IsNullOrEmpty(usrName)) return BadRequest("User cannot recognize"); try { using(conn = new SqlConnection(Startup.DBConnectionString)) { await conn.OpenAsync(); // Check: HID, it requires more info than just check, so it implemented it if (hid != 0) { String strHIDCheck = HIHDBUtility.getHomeDefQueryString() + " WHERE [ID]= @hid AND [USER] = @user"; cmd = new SqlCommand(strHIDCheck, conn); cmd.Parameters.AddWithValue("@hid", hid); cmd.Parameters.AddWithValue("@user", usrName); reader = await cmd.ExecuteReaderAsync(); if (!reader.HasRows) { errorCode = HttpStatusCode.BadRequest; throw new Exception("Not home found!"); } else { while (reader.Read()) { HIHDBUtility.HomeDef_DB2VM(reader, vmHome); // It shall be only one entry if found! break; } } reader.Dispose(); reader = null; cmd.Dispose(); cmd = null; } if (vmHome == null || String.IsNullOrEmpty(vmHome.BaseCurrency) || vmHome.ID != hid) { errorCode = HttpStatusCode.BadRequest; throw new Exception("Home Definition is invalid"); } // Check: DocID String checkString = HIHDBUtility.getFinanceDocADPListQueryString() + " WHERE [DOCID] = " + docid.ToString() + " AND [HID] = " + hid.ToString(); cmd = new SqlCommand(checkString, conn); reader = cmd.ExecuteReader(); if (!reader.HasRows) { errorCode = HttpStatusCode.BadRequest; throw new Exception("Invalid Doc ID inputted: " + docid.ToString()); } else { while (reader.Read()) { HIHDBUtility.FinTmpDocADP_DB2VM(reader, vmTmpDoc); // It shall be only one entry if found! break; } } reader.Dispose(); reader = null; cmd.Dispose(); cmd = null; // Check: Tmp doc has posted or not? if (vmTmpDoc == null || (vmTmpDoc.RefDocID.HasValue && vmTmpDoc.RefDocID.Value > 0)) { errorCode = HttpStatusCode.BadRequest; throw new Exception("Tmp Doc not existed yet or has been posted"); } if (!vmTmpDoc.ControlCenterID.HasValue && !vmTmpDoc.OrderID.HasValue) { errorCode = HttpStatusCode.BadRequest; throw new Exception("Tmp doc lack of control center or order"); } if (vmTmpDoc.TranAmount == 0) { errorCode = HttpStatusCode.BadRequest; throw new Exception("Tmp doc lack of amount"); } // Now go ahead for the creating tran = conn.BeginTransaction(); cmd = null; Int32 nNewDocID = 0; vmFIDOC.Desp = vmTmpDoc.Desp; vmFIDOC.DocType = FinanceDocTypeViewModel.DocType_Normal; vmFIDOC.HID = hid; //vmFIDOC.TranAmount = vmTmpDoc.TranAmount; vmFIDOC.TranCurr = vmHome.BaseCurrency; vmFIDOC.TranDate = vmTmpDoc.TranDate; vmFIDOC.CreatedAt = DateTime.Now; FinanceDocumentItemUIViewModel vmItem = new FinanceDocumentItemUIViewModel { AccountID = vmTmpDoc.AccountID }; if (vmTmpDoc.ControlCenterID.HasValue) vmItem.ControlCenterID = vmTmpDoc.ControlCenterID.Value; if (vmTmpDoc.OrderID.HasValue) vmItem.OrderID = vmTmpDoc.OrderID.Value; vmItem.Desp = vmTmpDoc.Desp; vmItem.ItemID = 1; vmItem.TranAmount = vmTmpDoc.TranAmount; vmItem.TranType = vmTmpDoc.TranType; vmFIDOC.Items.Add(vmItem); // Now go ahead for the creating queryString = HIHDBUtility.GetFinDocHeaderInsertString(); // Header cmd = new SqlCommand(queryString, conn) { Transaction = tran }; HIHDBUtility.BindFinDocHeaderInsertParameter(cmd, vmFIDOC, usrName); SqlParameter idparam = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int); idparam.Direction = ParameterDirection.Output; Int32 nRst = await cmd.ExecuteNonQueryAsync(); nNewDocID = (Int32)idparam.Value; vmFIDOC.ID = nNewDocID; cmd.Dispose(); cmd = null; // Then, creating the items foreach (FinanceDocumentItemUIViewModel ivm in vmFIDOC.Items) { queryString = HIHDBUtility.GetFinDocItemInsertString(); cmd = new SqlCommand(queryString, conn) { Transaction = tran }; HIHDBUtility.BindFinDocItemInsertParameter(cmd, ivm, nNewDocID); await cmd.ExecuteNonQueryAsync(); cmd.Dispose(); cmd = null; } // Then, update the template doc queryString = @"UPDATE [dbo].[t_fin_tmpdoc_dp] SET [REFDOCID] = @REFDOCID ,[UPDATEDBY] = @UPDATEDBY ,[UPDATEDAT] = @UPDATEDAT WHERE [HID] = @HID AND [DOCID] = @DOCID"; cmd = new SqlCommand(queryString, conn) { Transaction = tran }; cmd.Parameters.AddWithValue("@REFDOCID", nNewDocID); cmd.Parameters.AddWithValue("@UPDATEDBY", usrName); cmd.Parameters.AddWithValue("@UPDATEDAT", DateTime.Now); cmd.Parameters.AddWithValue("@HID", hid); cmd.Parameters.AddWithValue("@DOCID", docid); await cmd.ExecuteNonQueryAsync(); tran.Commit(); // Update the buffer of the relevant Account! var cacheAccountKey = String.Format(CacheKeys.FinAccount, hid, vmTmpDoc.AccountID); this._cache.Remove(cacheAccountKey); } } catch (Exception exp) { #if DEBUG System.Diagnostics.Debug.WriteLine(exp.Message); #endif if (tran != null) tran.Rollback(); strErrMsg = exp.Message; if (errorCode == HttpStatusCode.OK) errorCode = HttpStatusCode.InternalServerError; } finally { if (tran != null) { tran.Dispose(); tran = null; } if (reader != null) { reader.Dispose(); reader = null; } if (cmd != null) { cmd.Dispose(); cmd = null; } if (conn != null) { conn.Dispose(); conn = null; } } if (errorCode != HttpStatusCode.OK) { switch (errorCode) { case HttpStatusCode.Unauthorized: return Unauthorized(); case HttpStatusCode.NotFound: return NotFound(); case HttpStatusCode.BadRequest: return BadRequest(strErrMsg); default: return StatusCode(500, strErrMsg); } } var setting = new Newtonsoft.Json.JsonSerializerSettings { DateFormatString = HIHAPIConstants.DateFormatPattern, ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }; return new JsonResult(vmFIDOC, setting); } // PUT: api/FinanceADPTmpDoc/5 [HttpPut("{id}")] public IActionResult Put([FromRoute]int id, [FromBody]FinanceTmpDocDPViewModel vm) { return BadRequest(); } // DELETE: api/ApiWithActions/5 [HttpDelete("{id}")] public IActionResult Delete([FromRoute]int id) { return BadRequest(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Management.Automation.Language; using System.Runtime.InteropServices.ComTypes; namespace System.Management.Automation.ComInterop { internal sealed class IDispatchMetaObject : ComFallbackMetaObject { private readonly IDispatchComObject _self; internal IDispatchMetaObject(Expression expression, IDispatchComObject self) : base(expression, BindingRestrictions.Empty, self) { _self = self; } public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { Requires.NotNull(binder, nameof(binder)); ComMethodDesc method = null; // See if this is actually a property set ComBinder.ComInvokeMemberBinder comInvokeBinder = binder as ComBinder.ComInvokeMemberBinder; if ((comInvokeBinder != null) && (comInvokeBinder.IsPropertySet)) { DynamicMetaObject value = args[args.Length - 1]; bool holdsNull = value.Value == null && value.HasValue; if (!_self.TryGetPropertySetter(binder.Name, out method, value.LimitType, holdsNull)) { _self.TryGetPropertySetterExplicit(binder.Name, out method, value.LimitType, holdsNull); } } // Otherwise, try property get if (method == null) { if (!_self.TryGetMemberMethod(binder.Name, out method)) { _self.TryGetMemberMethodExplicit(binder.Name, out method); } } if (method != null) { List<ParameterExpression> temps = new List<ParameterExpression>(); List<Expression> initTemps = new List<Expression>(); bool[] isByRef = ComBinderHelpers.ProcessArgumentsForCom(method, ref args, temps, initTemps); return BindComInvoke(args, method, binder.CallInfo, isByRef, temps, initTemps); } return base.BindInvokeMember(binder, args); } public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { Requires.NotNull(binder, nameof(binder)); if (_self.TryGetGetItem(out ComMethodDesc method)) { List<ParameterExpression> temps = new List<ParameterExpression>(); List<Expression> initTemps = new List<Expression>(); bool[] isByRef = ComBinderHelpers.ProcessArgumentsForCom(method, ref args, temps, initTemps); return BindComInvoke(args, method, binder.CallInfo, isByRef, temps, initTemps); } return base.BindInvoke(binder, args); } private DynamicMetaObject BindComInvoke(DynamicMetaObject[] args, ComMethodDesc method, CallInfo callInfo, bool[] isByRef, List<ParameterExpression> temps, List<Expression> initTemps) { DynamicMetaObject invoke = new ComInvokeBinder( callInfo, args, isByRef, IDispatchRestriction(), Expression.Constant(method), Expression.Property( Helpers.Convert(Expression, typeof(IDispatchComObject)), typeof(IDispatchComObject).GetProperty(nameof(IDispatchComObject.DispatchObject)) ), method ).Invoke(); if (temps != null && temps.Count > 0) { Expression invokeExpression = invoke.Expression; Expression call = Expression.Block(invokeExpression.Type, temps, initTemps.Append(invokeExpression)); invoke = new DynamicMetaObject(call, invoke.Restrictions); } return invoke; } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { ComBinder.ComGetMemberBinder comBinder = binder as ComBinder.ComGetMemberBinder; bool canReturnCallables = comBinder?._canReturnCallables ?? false; Requires.NotNull(binder, nameof(binder)); // 1. Try methods if (_self.TryGetMemberMethod(binder.Name, out ComMethodDesc method)) { if (((method.InvokeKind & INVOKEKIND.INVOKE_PROPERTYGET) == INVOKEKIND.INVOKE_PROPERTYGET) && (method.ParamCount == 0)) { return BindGetMember(method, canReturnCallables); } } // 2. Try events if (_self.TryGetMemberEvent(binder.Name, out ComEventDesc @event)) { return BindEvent(@event); } // 3. Try methods explicitly by name if (_self.TryGetMemberMethodExplicit(binder.Name, out method)) { if (((method.InvokeKind & INVOKEKIND.INVOKE_PROPERTYGET) == INVOKEKIND.INVOKE_PROPERTYGET) && (method.ParamCount == 0)) { return BindGetMember(method, canReturnCallables); } } // 4. Fallback return base.BindGetMember(binder); } private DynamicMetaObject BindGetMember(ComMethodDesc method, bool canReturnCallables) { if (method.IsDataMember) { if (method.ParamCount == 0) { return BindComInvoke(DynamicMetaObject.EmptyMetaObjects, method, new CallInfo(0), Array.Empty<bool>(), null, null); } } // ComGetMemberBinder does not expect callables. Try to call always. if (!canReturnCallables) { return BindComInvoke(DynamicMetaObject.EmptyMetaObjects, method, new CallInfo(0), Array.Empty<bool>(), null, null); } return new DynamicMetaObject( Expression.Call( typeof(ComRuntimeHelpers).GetMethod(nameof(ComRuntimeHelpers.CreateDispCallable)), Helpers.Convert(Expression, typeof(IDispatchComObject)), Expression.Constant(method) ), IDispatchRestriction() ); } private DynamicMetaObject BindEvent(ComEventDesc eventDesc) { // BoundDispEvent CreateComEvent(object rcw, Guid sourceIid, int dispid) Expression result = Expression.Call( typeof(ComRuntimeHelpers).GetMethod(nameof(ComRuntimeHelpers.CreateComEvent)), ComObject.RcwFromComObject(Expression), Expression.Constant(eventDesc.SourceIID), Expression.Constant(eventDesc.Dispid) ); return new DynamicMetaObject( result, IDispatchRestriction() ); } public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { Requires.NotNull(binder, nameof(binder)); if (_self.TryGetGetItem(out ComMethodDesc getItem)) { List<ParameterExpression> temps = new List<ParameterExpression>(); List<Expression> initTemps = new List<Expression>(); bool[] isByRef = ComBinderHelpers.ProcessArgumentsForCom(getItem, ref indexes, temps, initTemps); return BindComInvoke(indexes, getItem, binder.CallInfo, isByRef, temps, initTemps); } return base.BindGetIndex(binder, indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { Requires.NotNull(binder, nameof(binder)); if (_self.TryGetSetItem(out ComMethodDesc setItem)) { List<ParameterExpression> temps = new List<ParameterExpression>(); List<Expression> initTemps = new List<Expression>(); bool[] isByRef = ComBinderHelpers.ProcessArgumentsForCom(setItem, ref indexes, temps, initTemps); isByRef = isByRef.AddLast(false); // Convert the value to the target type DynamicMetaObject updatedValue = new DynamicMetaObject( value.CastOrConvertMethodArgument( value.LimitType, setItem.Name, "SetIndex", allowCastingToByRefLikeType: false, temps, initTemps), value.Restrictions); var result = BindComInvoke(indexes.AddLast(updatedValue), setItem, binder.CallInfo, isByRef, temps, initTemps); // Make sure to return the value; some languages need it. return new DynamicMetaObject( Expression.Block(result.Expression, Expression.Convert(value.Expression, typeof(object))), result.Restrictions ); } return base.BindSetIndex(binder, indexes, value); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { Requires.NotNull(binder, nameof(binder)); return // 1. Check for simple property put TryPropertyPut(binder, value) ?? // 2. Check for event handler hookup where the put is dropped TryEventHandlerNoop(binder, value) ?? // 3. Fallback base.BindSetMember(binder, value); } private DynamicMetaObject TryPropertyPut(SetMemberBinder binder, DynamicMetaObject value) { bool holdsNull = value.Value == null && value.HasValue; if (_self.TryGetPropertySetter(binder.Name, out ComMethodDesc method, value.LimitType, holdsNull) || _self.TryGetPropertySetterExplicit(binder.Name, out method, value.LimitType, holdsNull)) { BindingRestrictions restrictions = IDispatchRestriction(); Expression dispatch = Expression.Property( Helpers.Convert(Expression, typeof(IDispatchComObject)), typeof(IDispatchComObject).GetProperty(nameof(IDispatchComObject.DispatchObject)) ); DynamicMetaObject result = new ComInvokeBinder( new CallInfo(1), new[] { value }, new bool[] { false }, restrictions, Expression.Constant(method), dispatch, method ).Invoke(); // Make sure to return the value; some languages need it. return new DynamicMetaObject( Expression.Block(result.Expression, Expression.Convert(value.Expression, typeof(object))), result.Restrictions ); } return null; } private DynamicMetaObject TryEventHandlerNoop(SetMemberBinder binder, DynamicMetaObject value) { if (_self.TryGetMemberEvent(binder.Name, out _) && value.LimitType == typeof(BoundDispEvent)) { // Drop the event property set. return new DynamicMetaObject( Expression.Constant(null), value.Restrictions.Merge(IDispatchRestriction()).Merge(BindingRestrictions.GetTypeRestriction(value.Expression, typeof(BoundDispEvent))) ); } return null; } private BindingRestrictions IDispatchRestriction() { return IDispatchRestriction(Expression, _self.ComTypeDesc); } internal static BindingRestrictions IDispatchRestriction(Expression expr, ComTypeDesc typeDesc) { return BindingRestrictions.GetTypeRestriction( expr, typeof(IDispatchComObject) ).Merge( BindingRestrictions.GetExpressionRestriction( Expression.Equal( Expression.Property( Helpers.Convert(expr, typeof(IDispatchComObject)), typeof(IDispatchComObject).GetProperty(nameof(IDispatchComObject.ComTypeDesc)) ), Expression.Constant(typeDesc) ) ) ); } protected override ComUnwrappedMetaObject UnwrapSelf() { return new ComUnwrappedMetaObject( ComObject.RcwFromComObject(Expression), IDispatchRestriction(), _self.RuntimeCallableWrapper ); } } }